diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..14cee8b5 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index 1a517801..53d6d047 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,5 @@ node_modules -examples/**/dist - -.DS_Store -yarn.lock - -.temp -.vscode - -# Jest -coverage \ No newline at end of file +examples/*/dist +examples/*/*/dist +examples/eegnfb/yarn.lock +.DS_Store \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..6f3a2913 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "liveServer.settings.port": 5501 +} \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0ccc0781..00000000 --- a/LICENSE +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. \ No newline at end of file diff --git a/README.md b/README.md index f9f6f4c3..53853f7f 100644 --- a/README.md +++ b/README.md @@ -1,88 +1,116 @@ + # graphscript [![Npm package version](https://img.shields.io/npm/v/graphscript)](https://npmjs.com/package/graphscript) [![Npm package monthly downloads](https://badgen.net/npm/dm/graphscript)](https://npmjs.ccom/package/graphscript) -[![License: LGPL v3](https://img.shields.io/badge/license-LGPL_v3-blue.svg)](https://www.gnu.org/licenses/LGPL-3.0) +[![License: AGPL v3](https://img.shields.io/badge/license-AGPL_v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) +[![Discord](https://img.shields.io/badge/community-discord-7289da.svg?sanitize=true)](https://discord.gg/CDxskSh9ZB)

-
+
For happy code!

-## This API is still under construction -There's plenty of working tools available already. However, we are randomly breaking/finding old broken code and improving things constantly as we push out a model we feel can be competitive. 100% FOSS! - -Also, we are going to turn this spec into something that supports a visual editor for games and applications built right into VSCode: [Notes](https://docs.google.com/document/d/18EZ1UgztDTi5w7B8xdgAWzMF2TDoZubMnkuVbW-y4cU/edit?usp=sharing ) -
-**GraphScript** is a highly customizable, high performance library for creating complex full stack software and library architectures. It's based around graphs hierarchies, event systems, and microservices, with an intuitive composition and node/function indexing tree system for rapid development. -

- -Check out the code in [examples](./examples) for very clear, compelling implementatons that flex our rapidly evolving feature sets. Get in touch at brewster.joshua1@gmail.com if you'd like to contribute and see this evolve. - -## Core Concepts -**graphscript** is organized by the basic principles of graph theory: - -1. **Graph:** These are contained in a shared scope. -2. **Nodes:** There is a hierarchy of objects. -3. **Connections:** Within each shared scope, properties can be linked in order to react to each other. - -Beyond these basic concepts, nodes can be direct proxies for generic javascript functions, objects or class instances from any libraries, enabling an intuitive frontend/backend hierarchical organization scheme that can plug right in as an event system for existing object-oriented programs. - -### Graphs and Graph Nodes -See [Graphs and GraphNodes](./docs/Graph.md) for more information. - -The basic connectivity framework. You can design entire apps or modules as nested object (or scope) associations with the graph node properties and event system. We've demonstrated dozens of modules in the examples and throughout the source code. Just dump them in a Graph and you can quickly build event systems with a clear readable hierarchy. This isn't a rigid system as you'll see in the [examples](./examples/). Add more GraphScript properties (which we distinguish with a *__*) using **loaders** to customize node instantiation behaviors e.g. for spawning a multithreaded app from a fairly simple hierarchical definition for the desired i/o scheme. - -### Services -See [Services](./docs/Service.md) for more information. - -This forms a microservices layer on top of the graph system. It makes it easier to communicate between separate graphs that track their own properties. We've implemented all kinds of protocols (HTTP, WebRTC, WSS, Event Sources, End-to-End encryption, etc) on top of this to demonstrate the convenience of a graph-based event system for software pipelining. - -[Included Services](./docs/Service.md#included-services) contains a reference of the services included in the main graphscript packages. - -## Packages - -### `graphscript`: A GraphScript distribution for browsers (~211kb) -#### Package Features -- Graphs, Services -- Web Workers, including convenient canvas renderer multithreading and MessageChannel pipelining -- WebRTC -- WebSockets -- Event Sources -- Session system for syncing data across connections (e.g. for game servers) -- Router for creating user systems and connection routing by user assocation. -- End 2 End encryption (via `sjcl`) - -### `graphscript-node`: A GraphScript build for Node.js (~238Kb) -#### Package Features -- Graphs, Services -- Experimental pure nodejs HTTP/HTTPS server for rapid prototyping. Tie requests to graph node properties or use a simple page templating system. -- Websocket server and Websockets (via `ws`) -- Server-Sent Events (via `better-sse`) -- Child-Processes (still need to add a polyfill for web workers) -- Session system for syncing data across connections (e.g. for game servers) -- Router for creating user systems and connection routing by user assocation. -- End 2 End encryption (via `sjcl`) - - -### `graphscript-core` : (~26kb) -#### Package Features -- A minimal GraphScript distribution featuring only Graphs, the EventHandler, and the base loaders. Should work in browser and node.js - -### `graphscript-services`: A collection of additional GraphScript services and general bloat. -#### Package Features -- User database system made for use with Mongoose/MongoDB. Includes dozens of boilerplate data structures for a simple query system with optional user permissions and access token verification. -- Entity Component System - a semi out-of-date but functional ECS format. -- WebGL plotter, can handle millions of points. -- Node templates (e.g. for use with the remoteGraphRoutes) for receiving data from sensors and stuff. - -#### Extras - - `graphscript-services.gpu`: Experimental `gpu.js` plugin. ~500kb, use it with workers for best results. - - `graphscript-services.storage`: Some BrowserFS, CSV, and Google Drive utilities. Not very complete. - -### Contributing - -Want to see this API improve faster? Please contribute or create issues and offer perspective. This repo is mostly a labor of love by Josh, with Garrett swooping in to reality check the actual utility of it from time to time. We want this to API to give you open web super powers, so we can all move on to building much more interesting end products as a community, as well as get more students, engineers, and researchers working in a collaborative development environment. This is the future! Down with knowledge and tool hoarding! - -### See also: -- [`device-decoder`](https://github.com/joshbrew/device-decoder) - Complex Browser USB and Browser or Native Mobile Bluetooth driver set that is by-default multithreaded using our web worker system. You can use the worker system to create fully-threaded pipelines from the device codec without touching the main thread. +**GraphScript** is an extensible standard for defining special properties on a hierarchy of reactive objects. + +> **Note:** **graphscript** is a core library of the [Brains@Play Framework](https://github.com/brainsatplay/brainsatplay) + +## The Library +**graphscript** is an object-oriented library organized based on the principles of graph theory. + +1. **Nodes:** There is a hierarchy of objects. +2. **Graph:** These are contained in a shared scope. +3. **Edges:** Node properties can be linked to modifying each other. + +Beyond these basic features, you can selectively enable other GraphScript properties (distinguished with a *__*) using loaders. + +Scroll through the code in [examples](https://github.com/brainsatplay/graphscript/blob/master/examples) for very clear, compelling implementatons that flex our features. + +### Installation +- **Browser:** `npm i graphscript` + - ~190kb dist + +- **Node:** `npm i graphscript-node` + - ~220Kb dist + +- **Core:** `npm i graphscript-core` + - ~20Kb dist +- **Additional Services:** `npm i graphscript-services` + + +### Additional Documentation +1. [Graphs and GraphNodes](https://github.com/brainsatplay/graphscript/blob/master/docs/Graph.md) +2. [Services](https://github.com/brainsatplay/graphscript/blob/master/docs/Service.md) + - [Included Services](https://github.com/brainsatplay/graphscript/blob/master/docs/Service.md#included-services) + +## Acknowledgments +This library is maintained by [Garrett Flynn](https://github.com/garrettmflynn) and [Joshua Brewster](https://github.com/joshbrew), who use contract work and community contributions through [Open Collective](https://opencollective.com/brainsatplay) to support themselves. + +### Backers +[Support us with a monthly donation](https://opencollective.com/brainsatplay#backer) and help us continue our activities! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Sponsors + +[Become a sponsor](https://opencollective.com/brainsatplay#sponsor) and get your logo here with a link to your site! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/___package.json b/___package.json index 50c712c3..96338018 100644 --- a/___package.json +++ b/___package.json @@ -1,6 +1,6 @@ { "name": "graphscript-core", - "version": "0.3.2", + "version": "0.2.23", "description": "Comprehensive acyclic-graph based application architecture with microservices and networking.", "main": "dist/index.core.js", "module": "dist/index.core.esm.js", @@ -21,7 +21,7 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": {}, "nodemonConfig": { "env": { diff --git a/__package.json b/__package.json index f9e4ebad..0c4164a9 100644 --- a/__package.json +++ b/__package.json @@ -1,6 +1,6 @@ { "name": "graphscript-node", - "version": "0.3.2", + "version": "0.2.23", "description": "Comprehensive acyclic-graph based application architecture with microservices and networking", "main": "dist/index.node.js", "types": "dist/index.node.d.ts", @@ -20,13 +20,13 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "better-sse": "~0.10.0", - "brainsatplay-math": "~0.1.0", + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", - "ws": "~8.14.2" + "ws": "~8.11.0" }, "nodemonConfig": { "env": { diff --git a/_old/_oldGraph.ts b/_old/_oldGraph.ts index 7066c290..7d052ff0 100644 --- a/_old/_oldGraph.ts +++ b/_old/_oldGraph.ts @@ -43,7 +43,7 @@ export function parseFunctionFromText(method='') { // go-here-do-that utilities. Create an object node tree and make it do... things // same setup as sequencer but object/array/tag only (no functions), and can add arbitrary properties to mutate on objects // or propagate to children/parents with utility calls that get added to the objects -//Joshua Brewster and Garrett Flynn LGPLv3.0 +//Joshua Brewster and Garrett Flynn AGPLv3.0 export type OperatorType = ( //can be async ...args:any //input arguments, e.g. output from another node diff --git a/core/Graph.ts b/core/Graph.ts new file mode 100644 index 00000000..03404e8e --- /dev/null +++ b/core/Graph.ts @@ -0,0 +1,854 @@ +//graphnodes but we are going to define graph nodes as scopes and graphs as instances of scopes, +// then the execution behaviors will be made plugins to recognize settings on the objects optionally. This is more generic + +import { EventHandler } from "./utils/EventHandler"; + +export const state = new EventHandler(); + + +export type GraphNodeProperties = { + __props?:Function|GraphNodeProperties, //a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. + __operator?:((...args:any[])=>any)|string, //The 'main' function of the graph node, children will call this function if triggered by a parent. Functions passed as graphnodeproperties become the operator which can set state. + __children?:{[key:string]:GraphNodeProperties}, //child nodes belonging to this node, e.g. for propagating results + __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true,subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs + __onconnected?:((node)=>void|((node)=>void)[]), //what happens once the node is created? + __ondisconnected?:((node)=>void|((node)=>void)[]), //what happens when the node is deleted? + __node?:{ //node specific properties, can contain a lot more things + tag?:string, + state?:EventHandler, //by default has a global shared state + inputState?:boolean //we can track inputs on a node, subscribe to state with 'input' on the end of the tag or 'tag.prop' + [key:string]:any + }, + [key:string]:any +} + + +export type Loader = ( + node:GraphNode, + parent:Graph|GraphNode, + graph:Graph, + tree:any, + properties:GraphNodeProperties, + key:string +)=>void; + +export type GraphOptions = { + tree?:{[key:string]:any}, + loaders?:{ + [key:string]:Loader|{ + init?:Loader, + connected?:(node)=>void, + disconnected?:(node)=>void} + }, + state?:EventHandler, + mapGraphs?:false, //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? + [key:string]:any +} + +//this is a scope +export class GraphNode { + + __node:{ + [key:string]:any + } = { //GraphNode-specific properties + tag:`node${Math.floor(Math.random()*1000000000000000)}`, + unique:`${Math.random()}`, + state, + // operator: undefined as any, + // graph: undefined as any, + // children: undefined as any, + // localState: undefined as any, + // oncreate:undefined as any, //function or array of functions + // ondelete:undefined as any, //function or array of functions + // listeners:undefined as any, //e.g. { 'nodeA.x':(newX)=>{console.log('nodeA.x changed:',x)} } + // source:undefined as any// source graph if a graph is passed as properties + } + + __children?; + __operator?; + __listeners?; + __props?; + + [key:string]:any + + //pass GraphNodeProperties, functions, or tags of other nodes + constructor(properties:any, parent?:{[key:string]:any}, graph?:Graph) { + + let orig = properties; + if(typeof properties === 'function') { + if(isNativeClass(properties)) { //works on custom classes + console.log(properties); + properties = new properties(); //this is a class that returns a node definition + } else properties = { + __operator:properties, + __node:{ + forward:true, //propagate operator results to children + tag:properties.name + } + }; + } else if (typeof properties === 'string') { + if(graph?.get(properties)) { + properties = graph.get(properties); + } + } + if(!properties.__node.initial) properties.__node.initial = orig; //original object or function + + if(typeof properties === 'object') { + if(properties.__props) { //e.g. some generic javascript object or class constructor that we want to proxy. Functions passed here are treated as constructors. E.g. pass an HTML canvas element for the node then set this.width on the node to set the canvas width + if (typeof properties.__props === 'function') properties.__props = new properties.__props(); + if (typeof properties.__props === 'object') { + this.__proxyObject(properties.__props); + } + } + + if (typeof properties.__node === 'string') { + //copy + if(graph?.get(properties.__node.tag)) { + properties = graph.get(properties.__node.tag); + } else properties.__node = {} + } else if(!properties.__node) properties.__node = {}; + + if(graph) { + properties.__node.graph = graph; + } + + if(properties.__operator) { + if (typeof properties.__operator === 'string') { + if(graph) { + let n = graph.get(properties.__operator); + if(n) properties.__operator = n.__operator; + if(!properties.__node.tag && (properties.__operator as Function).name) + properties.__node.tag = (properties.__operator as Function).name; + } + } + if(typeof properties.__operator === 'function') + properties.__operator = this.__setOperator(properties.__operator); + + } + + if(!properties.__node.tag) { + if(properties.__operator?.name) + properties.__node.tag = properties.__operator.name; + else + properties.__node.tag = `node${Math.floor(Math.random()*1000000000000000)}`; + } + + //nested graphs or 2nd level+ nodes get their parents as a tag + if(!properties.__parent && parent) properties.__parent = parent; + if(parent?.__node && (!(parent instanceof Graph || properties instanceof Graph))) + properties.__node.tag = parent.__node.tag + '.' + properties.__node.tag; //load parents first + + if(parent instanceof Graph && properties instanceof Graph) { + + if(properties.__node.loaders) Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); //let the parent graph adopt the child graph's loaders + + if(parent.__node.mapGraphs) { + //do we still want to register the child graph's nodes on the parent graph with unique tags for navigation? Need to add cleanup in this case + properties.__node.nodes.forEach((n) => {parent.set(properties.__node.tag+'.'+n.__node.tag,n)}); + + let ondelete = () => { properties.__node.nodes.forEach((n) => {parent.__node.nodes.delete(properties.__node.tag+'.'+n.__node.tag)}); } + this.__addOndisconnected(ondelete); + + } + } + + properties.__node = Object.assign(this.__node,properties.__node); + + let keys = Object.getOwnPropertyNames(properties); + for(const key of keys) { this[key] = properties[key]; } + + + if (typeof properties.default === 'function' && !properties.__operator) { //make it so the node is subscribable + let fn = properties.default.bind(this); + this.default = (...args) => { + if(this.__node.inputState) this.__node.state.setValue(this.__node.unique+'input',args); + let result = fn(...args); + if(typeof result?.then === 'function') { + result.then((res)=>{ if(res !== undefined) this.__node.state.setValue( this.__node.unique,res ) }).catch(console.error); + } else if(result !== undefined) this.__node.state.setValue(this.__node.unique,result); + return result; + } + + properties.default = this.default; + } + + if(properties instanceof Graph) this.__node.source = properties; //keep tabs on source graphs passed to make nodes + + + } + } + + //subscribe an output or input with an arbitrary callback + __subscribe = (callback:string|GraphNode|((res)=>void), key?:string, subInput?:boolean, bound?:string, target?:string) => { + + const subscribeToFunction = (k, setTarget = (callback, target?) => callback, triggerCallback=callback) => { + let sub = this.__node.state.subscribeTrigger(k, triggerCallback); + + // Add details to trigger + let trigger = this.__node.state.getTrigger(k,sub); + trigger.source = this.__node.tag; + if(key) trigger.key = key; + trigger.target = setTarget(callback) // Non-string value + if(bound) trigger.bound = bound; + + return sub + } + + const subscribeToGraph = (callback) => { + let fn = this.__node.graph.get(callback); + if(!fn && callback.includes('.')) { + let n = this.__node.graph.get(callback.substring(0,callback.lastIndexOf('.'))) + let key = callback.substring(callback.lastIndexOf('.')+1); + if(n && typeof n[key] === 'function') callback = (...args) => { return n[key](...args); }; + //console.log(n, fn); + } + } + + if(key) { + // console.log(key,this.__node.tag, 'callback:', callback); + if(!this.__node.localState) { + this.__addLocalState(this); + } + + if(typeof callback === 'string') { + if(typeof this[callback] === 'function') callback = this[callback]; + else if(this.__node.graph) subscribeToGraph(callback) + } + let sub; + + let k = subInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key; + + if(typeof callback === 'function') sub = subscribeToFunction(k) + else if((callback as GraphNode)?.__node) sub = subscribeToFunction(k, + (callback, target) => target ? target : (callback as GraphNode).__node.unique, + (state:any)=>{ if((callback as any).__operator) (callback as any).__operator(state); } + ) + + return sub; + } + else { + + // Get node based on the graph + if(typeof callback === 'string') { + if(this.__node.graph) callback = this.__node.graph.get(callback); + else callback = this.__node.graph.nodes.get(callback); + } + + let sub; + let k = subInput ? this.__node.unique+'input' : this.__node.unique; + if(typeof callback === 'function') sub = subscribeToFunction(k) + else if((callback as GraphNode)?.__node) sub = subscribeToFunction(k, + (callback, target) => target ? target : (callback as GraphNode).__node.unique, + (state:any)=>{ if((callback as any).__operator) (callback as any).__operator(state); } + ) + + return sub; + } + } + + //unsub the callback + __unsubscribe = (sub?:number, key?:string, subInput?:boolean) => { + + if(key) { + return this.__node.state.unsubscribeTrigger(subInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key, sub); + } + else return this.__node.state.unsubscribeTrigger(subInput ? this.__node.unique+'input' : this.__node.unique, sub); + + } + + __setOperator = (fn:(...args:any[])=>any) => { + fn = fn.bind(this); + this.__operator = (...args) => { + if(this.__node.inputState) this.__node.state.setValue(this.__node.unique+'input',args); + let result = fn(...args); + if(this.__node.state.triggers[this.__node.unique]) { //don't set state (i.e. copy the result) if no subscriptions + if(typeof result?.then === 'function') { + result.then((res)=>{ if(res !== undefined) this.__node.state.setValue( this.__node.unique,res ) }).catch(console.error); + } else if(result !== undefined) this.__node.state.setValue(this.__node.unique,result); + } + return result; + } + + if(!this.__subscribedToParent) { + if(this.__parent instanceof GraphNode && this.__parent.__operator) { + let sub = this.__parent.__subscribe(this); + let ondelete = () => { this.__parent?.__unsubscribe(sub); delete this.__subscribedToParent;} + this.__addOndisconnected(ondelete); + this.__subscribedToParent = true; + } + } + + return this.__operator; + } + + __addLocalState(props?:{[key:string]:any}) { + if(!props) return; + if(!this.__node.localState) { + this.__node.localState = {}; + } + let localState = this.__node.localState; + for (let k in props) { + if(this.__props && this.__props[k]) continue; //already given a local state, continue + if(typeof props[k] === 'function') { + if(!k.startsWith('_')) { + let fn = props[k].bind(this) as Function; + props[k] = (...args) => { //all functions get state functionality when called, incl resolving async results for you + if(this.__node.inputState) this.__node.state.setValue(this.__node.unique+'.'+k+'input',args); + let result = fn(...args); + if(typeof result?.then === 'function') { + if(this.__node.state.triggers[this.__node.unique+'.'+k]) result.then((res)=>{ this.__node.state.setValue( this.__node.unique+'.'+k, res ) }).catch(console.error); + } else if(this.__node.state.triggers[this.__node.unique+'.'+k]) this.__node.state.setValue(this.__node.unique+'.'+k,result); + return result; + } + this[k] = props[k]; + } + } else { + localState[k] = props[k]; + //console.log(k, localState[k]); + + let definition = { + get: () => { + return localState[k]; + }, + set: (v) => { + localState[k] = v; + if(this.__node.state.triggers[this.__node.unique+'.'+k]) this.__node.state.setValue(this.__node.unique+'.'+k,v); //this will update localState and trigger local key subscriptions + }, + enumerable: true, + configurable: true + } as any; + + Object.defineProperty(this, k, definition); + + if(typeof this.__node.initial === 'object') { + let dec = Object.getOwnPropertyDescriptor(this.__node.initial,k); + if(dec === undefined || dec?.configurable) { + Object.defineProperty(this.__node.initial, k, definition); + } + } + } + } + } + + //we can proxy an original object and function outputs on the node + __proxyObject = (obj) => { + + let allProps = getAllProperties(obj); + + for(const k of allProps) { + if(typeof this[k] === 'undefined') { + if(typeof obj[k] === 'function') { + this[k] = (...args) => { //all functions get state functionality when called, incl resolving async results for you + if(this.__node.inputState) this.__node.state.setValue(this.__node.unique+'.'+k+'input',args); + let result = obj[k](...args); + if(this.__node.state.triggers[this.__node.unique+'.'+k]) { + if(typeof result?.then === 'function') { + result.then((res)=>{ this.__node.state.setValue( this.__node.unique+'.'+k, res ) }).catch(console.error); + } else this.__node.state.setValue(this.__node.unique+'.'+k,result); + } + return result; + } + } else { + + let definition = { + get:()=>{return obj[k]}, + set:(value) => { + obj[k] = value; + if(this.__node.state.triggers[this.__node.unique+'.'+k]) this.__node.state.setValue(this.__node.unique+'.'+k,value); + }, + enumerable: true, + configurable: true + } + + Object.defineProperty(this, k, definition); + } + } + } + } + + __addOnconnected(callback:(node)=>void) { + if(Array.isArray(this.__ondisconnected)) { this.__onconnected.push(callback); } + else if (typeof this.__onconnected === 'function') { this.__onconnected = [callback,this.__onconnected] } + else this.__onconnected = callback; + } + + __addOndisconnected(callback:(node)=>void) { + if(Array.isArray(this.__ondisconnected)) { this.__ondisconnected.push(callback); } + else if (typeof this.__ondisconnected === 'function') { this.__ondisconnected = [callback,this.__ondisconnected] } + else this.__ondisconnected = callback; + } + + __callConnected(node=this) { + if(typeof this.__onconnected === 'function') { this.__onconnected(this); } + else if (Array.isArray(this.__onconnected)) { this.__onconnected.forEach((o:Function) => { o(this); }) } + } + + __callDisconnected(node=this) { + if(typeof this.__ondisconnected === 'function') this.__ondisconnected(this); + else if (Array.isArray(this.__ondisconnected)) { this.__ondisconnected.forEach((o:Function) => {o(this)}); } + } + +} + +export class Graph { + + [key:string]:any; + + __node:{ + tag:string, + state:EventHandler, + nodes:Map + [key:string]:any + } = { + tag:`graph${Math.floor(Math.random()*1000000000000000)}`, + nodes:new Map(), + state, + // addState:true //apply the addLocalState on node init + // mapGraphs:false //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? + // tree:undefined as any, + // loaders:undefined as any, + } + + + constructor( + options?:GraphOptions + ) { + this.init(options); + } + + init = (options?:GraphOptions) => { + if(options) { + recursivelyAssign(this.__node, options); //assign loaders etc + if(options.tree) this.setTree(options.tree); + } + } + + setTree = (tree:{[key:string]:any}) => { + + this.__node.tree = Object.assign(this.__node.tree ? this.__node.tree : {}, tree); + + let cpy = Object.assign({},tree); + if(cpy.__node) delete cpy.__node; //we can specify __node behaviors on the tree too to specify listeners + + let listeners = this.recursiveSet(cpy,this,undefined,tree); + + //make the tree a node + if(tree.__node) { + if(!tree.__node.tag) tree.__node._tag = `tree${Math.floor(Math.random()*1000000000000000)}` + else if (!this.get(tree.__node.tag)) { + let node = new GraphNode(tree,this,this); //blank node essentially for creating listeners + this.set(node.__node.tag,node); + for(const l in this.__node.loaders) { + if(typeof this.__node.loaders[l] === 'object') { + if(this.__node.loaders[l].init) this.__node.loaders[l](node,parent,this,this.__node.tree,tree); + if(this.__node.loaders[l].connected) node.__addOnconnected(this.__node.loaders[l].connect); + if(this.__node.loaders[l].disconnected) node.__addOndisconnected(this.__node.loaders[l].disconnect); + } else if (typeof this.__node.loaders === 'function') this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag); } //run any passes on the nodes to set things up further + if(node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } //now the tree can specify nodes + } + } else if (tree.__listeners) { + this.setListeners(tree.__listeners) + } + + //now setup event listeners + this.setListeners(listeners); + + return cpy; //should be the node tree + + } + + setLoaders = (loaders:{[key:string]:(node:GraphNode,parent:Graph|GraphNode,graph:Graph,tree:any,props:any,key:string)=>void}, replace?:boolean) => { + if(replace) this.__node.loaders = loaders; + else Object.assign(this.__node.loaders,loaders); + + return this.__node.loaders; + } + + add = (properties:any, parent?:GraphNode|string) => { + + let listeners = {}; //collect listener props declared + if(typeof parent === 'string') parent = this.get(parent); + + let instanced; + if(typeof properties === 'function') { + if(isNativeClass(properties)) { //works on custom classes + if(properties.prototype instanceof GraphNode) { properties = properties.prototype.constructor(properties,parent,this); instanced = true; } //reinstantiate a new node with the old node's props + else properties = new properties(); //this is a class that returns a node definition + } else properties = { __operator:properties }; + } + else if (typeof properties === 'string') properties = this.__node.tree[properties]; + + if(!instanced) { + properties = Object.assign({},properties); //make sure we don't mutate the original object + } + if(!properties.__node) properties.__node = {}; + properties.__node.initial = properties; + + if(typeof properties === 'object' && (!properties?.__node?.tag || !this.get(properties.__node.tag))) { + let node; + if(instanced) node = properties; + else node = new GraphNode(properties, parent as GraphNode, this); + this.set(node.__node.tag,node); + for(const l in this.__node.loaders) { + if(typeof this.__node.loaders[l] === 'object') { + if(this.__node.loaders[l].init) this.__node.loaders[l](node,parent,this,this.__node.tree,properties, node.__node.tag); + if(this.__node.loaders[l].connected) node.__addOnconnected(this.__node.loaders[l].connect); + if(this.__node.loaders[l].disconnected) node.__addOndisconnected(this.__node.loaders[l].disconnect); + } else if (typeof this.__node.loaders === 'function') this.__node.loaders[l](node,parent,this,this.__node.tree,properties, node.__node.tag); } //run any passes on the nodes to set things up further + this.__node.tree[node.__node.tag] = properties; //reference the original props by tag in the tree for children + //console.log('old:',properties.__node,'new:',node.__node); + + if(node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } + + if(node.__children) { + node.__children = Object.assign({},node.__children); + this.recursiveSet(node.__children, node, listeners,node.__children); + } + + //now setup event listeners + this.setListeners(listeners); + + node.__callConnected(); + + return node; + + } + + return; + } + + recursiveSet = (t,parent,listeners={},origin) => { + let keys = Object.getOwnPropertyNames(origin); + for(const key of keys) { + if(key.includes('__')) continue; + let p = origin[key]; + if(Array.isArray(p)) continue; + let instanced; + if(typeof p === 'function') { + if(isNativeClass(p)) { //works on custom classes + p = new p(); //this is a class that returns a node definition + if(p instanceof GraphNode) { p = p.prototype.constructor(p,parent,this); instanced = true; } //re-instance a new node + } else p = { __operator:p }; + } + else if (typeof p === 'string') p = this.__node.tree[p]; + else if (typeof p === 'boolean') p = this.__node.tree[key]; + if(typeof p === 'object') { + + if(!instanced) { + p = Object.assign({},p); //make sure we don't mutate the original object + } + if(!p.__node) p.__node = {}; + if(!p.__node.tag) p.__node.tag = key; + p.__node.initial = t[key]; + if((this.get(p.__node.tag) && !(parent?.__node && this.get(parent.__node.tag + '.' + p.__node.tag))) || (parent?.__node && this.get(parent.__node.tag + '.' + p.__node.tag))) continue; //don't duplicate a node we already have in the graph by tag + let node; + if(instanced) node = p; + else node = new GraphNode(p, parent as GraphNode, this); + this.set(node.__node.tag,node); + for(const l in this.__node.loaders) { this.__node.loaders[l](node,parent,this,t,t[key],key); } //run any passes on the nodes to set things up further + t[key] = node; //replace child with a graphnode + this.__node.tree[node.__node.tag] = p; //reference the original props by tag in the tree for children + if(node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } + if(node.__children) { + node.__children = Object.assign({},node.__children); + this.recursiveSet(node.__children, node, listeners,node.__children); + } + + node.__callConnected(); + } + } + return listeners; + } + + remove = (node:GraphNode|string, clearListeners:boolean=true) => { + this.unsubscribe(node); + + if(typeof node === 'string') node = this.get(node); + + if(node instanceof GraphNode) { + this.delete(node.__node.tag); + delete this.__node.tree[node.__node.tag]; + + if(clearListeners) { + this.clearListeners(node); + } + + node.__callDisconnected(); + + const recursiveRemove = (t) => { + for(const key in t) { + this.unsubscribe(t[key]); + this.delete(t[key].__node.tag); + delete this.__node.tree[t[key].__node.tag] + this.delete(key); + delete this.__node.tree[key] + + //console.log(key, 'removing child',t[key]); + t[key].__node.tag = t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf('.')+1); + + if(clearListeners) { + this.clearListeners(t[key]); + } + + t[key].__callDisconnected(); + + if(t[key].__children) { + recursiveRemove(t[key].__children); + } + + // console.log('removed!', t[key]) + } + } + + if(node.__children) { + recursiveRemove(node.__children); + } + } + + if((node as any)?.__node.tag && (node as any)?.__parent) { + delete (node as any)?.__parent; + (node as any).__node.tag = (node as any).__node.tag.substring((node as any).__node.tag.indexOf('.')+1); + } + + return node; + } + + run = (node:string|GraphNode, ...args:any[]) => { + if(typeof node === 'string') { + let nd = this.get(node); + if(!nd && node.includes('.')) { + nd = this.get(node.substring(0,node.lastIndexOf('.'))); + if(typeof nd?.[node.substring(node.lastIndexOf('.')+1)] === 'function') return nd[node.substring(node.lastIndexOf('.')+1)](...args); + } else if(nd?.__operator) return nd.__operator(...args); + } + if((node as GraphNode)?.__operator) { + return (node as GraphNode)?.__operator(...args); + } + } + + setListeners = (listeners:{[key:string]:{[key:string]:any}}) => { + //now setup event listeners + for(const key in listeners) { + let node = this.get(key); + if(typeof listeners[key] === 'object') { + for(const k in listeners[key]) { + let n = this.get(k); + let sub; + if( typeof listeners[key][k] !== 'object' ) listeners[key][k] = { __callback:listeners[key][k] }; + else if(!listeners[key][k].__callback) { //this is an object specifying multiple input + for(const kk in listeners[key][k]) { + if(typeof listeners[key][k][kk] !== 'object') { + listeners[key][k][kk] = {__callback: listeners[key][k][kk]} + if(listeners[key][k][kk].__callback === true) listeners[key][k][kk].__callback = node.__operator; + } + let nn = this.get(kk); + if(nn) { + if(!nn) { + let tag = k.substring(0,k.lastIndexOf('.')); + nn = this.get(tag); + if(n) { + sub = this.subscribe(nn, listeners[key][k][kk].__callback, k.substring(k.lastIndexOf('.')+1), listeners[key][k][kk].inputState, key, k); + if(typeof node.__listeners[k][kk] !== 'object') node.__listeners[k][kk] = { __callback: listeners[key][k][kk].__callback, inputState:listeners[key][k][kk]?.inputState }; + node.__listeners[k][kk].sub = sub; + } + } else { + sub = this.subscribe(nn, listeners[key][k][kk].__callback, undefined, listeners[key][k].inputState, key, k); + if(typeof node.__listeners[k][kk] !== 'object') node.__listeners[k][kk] = { __callback: listeners[key][k][kk].__callback, inputState: listeners[key][k][kk]?.inputState }; + node.__listeners[k][kk].sub = sub; + } + } + } + } + if(listeners[key][k].__callback) { + if(listeners[key][k].__callback === true) listeners[key][k].__callback = node.__operator; + if( typeof listeners[key][k].__callback === 'function') listeners[key][k].__callback = listeners[key][k].__callback.bind(node); + if(typeof node.__listeners !== 'object') node.__listeners = {}; //if we want to subscribe a node with listeners that doesn't predeclare them + if(!n) { + let tag = k.substring(0,k.lastIndexOf('.')); + n = this.get(tag); + if(n) { + sub = this.subscribe(n, listeners[key][k].__callback, k.substring(k.lastIndexOf('.')+1), listeners[key][k].inputState, key, k); + if(typeof node.__listeners[k] !== 'object') node.__listeners[k] = { __callback: listeners[key][k].__callback, inputState:listeners[key][k]?.inputState }; + node.__listeners[k].sub = sub; + } + } else { + sub = this.subscribe(n, listeners[key][k].__callback, undefined, listeners[key][k].inputState, key, k); + if(typeof node.__listeners[k] !== 'object') node.__listeners[k] = { __callback: listeners[key][k].__callback, inputState: listeners[key][k]?.inputState }; + node.__listeners[k].sub = sub; + } + //console.log(sub); + } + } + } + } + } + + clearListeners = (node:GraphNode|string,listener?:string) => { + if(typeof node === 'string') node = this.get(node) as GraphNode; + if(node?.__listeners) { + //console.log(node?.__listeners); + //console.log(node.__listeners); + for(const key in node.__listeners) { + if(listener && key !== listener) continue; + if(typeof node.__listeners[key].sub !== 'number') continue; + let n = this.get(key); + if(!n) { + n = this.get(key.substring(0,key.lastIndexOf('.'))); + //console.log(key.substring(0,key.lastIndexOf('.')),key,n,node.__listeners[key]); + if(n) { + if(!node.__listeners[key].__callback) { + for(const k in node.__listeners[key]) { + this.unsubscribe(n,node.__listeners[key][k].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key][k].inputState); + } + } else this.unsubscribe(n,node.__listeners[key].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key].inputState); + } + } else { + if(!node.__listeners[key].__callback) { + for(const k in node.__listeners[key]) { + this.unsubscribe(n,node.__listeners[key][k].sub, undefined, node.__listeners[key][k].inputState); + } + } else this.unsubscribe(n,node.__listeners[key].sub, undefined, node.__listeners[key].inputState); + } + + //console.log('unsubscribed', key) + delete node.__listeners[key]; + } + } + } + + get = (tag:string) => { return this.__node.nodes.get(tag); }; + set = (tag:string,node:GraphNode) => { return this.__node.nodes.set(tag,node); }; + delete = (tag:string) => { return this.__node.nodes.delete(tag); } + + getProps = (node:GraphNode|string, getInitial?:boolean) => { + if(typeof node === 'string') node = this.get(node); + + if(node instanceof GraphNode) { + + let cpy; + if(getInitial) cpy = Object.assign({}, this.__node.tree[node.__node.tag]); + else { + cpy = Object.assign({},node) as any; + //remove graphnode methods to return the arbitrary props + delete cpy.__unsubscribe; + delete cpy.__setOperator; + delete cpy.__node; + delete cpy.__subscribeState; + delete cpy.__subscribe; + } + } + } + + subscribe = ( + node:GraphNode|string, callback:string|GraphNode|((res:any)=>void), key?:string|undefined, subInput?:boolean, target?:string, bound?:string + ) => { + + let nd = node; + if(!(node instanceof GraphNode)) nd = this.get(node); + + let sub; + + if(typeof callback === 'string') { + + //console.log(node, callback, this.__node.nodes.keys()); + + if(target) { + let method = this.get(target)?.[callback]; + if(typeof method === 'function') callback = method; + } else callback = this.get(callback)?.__operator; + } + + if(nd instanceof GraphNode) { + sub = nd.__subscribe(callback,key,subInput,target,bound); + + let ondelete = () => { + (nd as GraphNode).__unsubscribe(sub,key,subInput); + } + + nd.__addOndisconnected(ondelete); + } else if (typeof node === 'string') { + if(this.get(node)) { + if(callback instanceof GraphNode && callback.__operator) { + sub = (this.get(node) as GraphNode).__subscribe(callback.__operator,key,subInput,target,bound); + let ondelete = () => { + this.get(node).__unsubscribe(sub) + //console.log('unsubscribed', key) + } + + callback.__addOndisconnected(ondelete); + } + else if (typeof callback === 'function' || typeof callback === 'string') { + sub = (this.get(node) as GraphNode).__subscribe(callback,key,subInput,target,bound); + + this.__node.state.getTrigger(this.get(node).__node.unique,sub).source = node; + } + } else { + if(typeof callback === 'string') callback = this.__node.nodes.get(callback).__operator; + if(typeof callback === 'function') sub = this.__node.state.subscribeTrigger(node, callback); + } + } + return sub; + } + + unsubscribe = ( node:GraphNode|string, sub?:number, key?:string, subInput?:boolean) => { + if(node instanceof GraphNode) { + return node.__unsubscribe(sub,key,subInput); + } + else return this.get(node)?.__unsubscribe(sub,key,subInput); + } + + setState = (update:{[key:string]:any}) => { + this.__node.state.setState(update); + } + +} + + +function recursivelyAssign (target,obj) { + for(const key in obj) { + if(obj[key]?.constructor.name === 'Object' && !Array.isArray(obj[key])) { + if(target[key]?.constructor.name === 'Object' && !Array.isArray(target[key])) + recursivelyAssign(target[key], obj[key]); + else target[key] = recursivelyAssign({},obj[key]); + } else { + target[key] = obj[key]; + //if(typeof target[key] === 'function') target[key] = target[key].bind(this); + } + } + + return target; +} + + +export function getAllProperties(obj){ //https://stackoverflow.com/questions/8024149/is-it-possible-to-get-the-non-enumerable-inherited-property-names-of-an-object + var allProps = [], curr = obj + do{ + var props = Object.getOwnPropertyNames(curr) + props.forEach(function(prop){ + if (allProps.indexOf(prop) === -1) + allProps.push(prop) + }) + }while(curr = Object.getPrototypeOf(curr)) + return allProps; +} + +export function instanceObject(obj) { + let props = getAllProperties(obj); //e.g. Math + let instance = {}; + for(const key of props) { + instance[key] = obj[key]; + } + + return instance; + //simply copies methods, nested objects will not be instanced to limit recursion +} + +export function isNativeClass (thing) { + return typeof thing === 'function' && thing.hasOwnProperty('prototype') && !thing.hasOwnProperty('arguments') +} \ No newline at end of file diff --git a/core/Graph2.ts b/core/Graph2.ts new file mode 100644 index 00000000..1963e2b9 --- /dev/null +++ b/core/Graph2.ts @@ -0,0 +1,819 @@ +//graphnodes but we are going to define graph nodes as scopes and graphs as instances of scopes, +// then the execution behaviors will be made plugins to recognize settings on the objects optionally. This is more generic + +import propsLoader from '../core/loaders/props/props.loader' + + +import Monitor from './libraries/esmonitor/dist/index.esm'; +import FlowManager from "./libraries/edgelord/index" + + +const registry = {} +const printed = [] + +function makeNonEnumerable(obj) { + for (let key in obj) { + const desc = Object.getOwnPropertyDescriptor(obj, key); + if (!desc.get && !desc.set) { + if (key.slice(0, 2) === '__') Object.defineProperty(obj, key, { + value: obj[key], + enumerable: false, + configurable: true + }); + } + // else console.error('Will not reset enumerable on getter/setter', key) + } +} + +function applyLoader (node: GraphNode, parent, graph=this, tree= graph.__node.tree, properties, tag=node.__node.tag, loader) { + + const args = [ node,parent,graph,tree,properties, tag ] + + if(typeof loader === 'object') { + if(loader.init) loader(...args); + if(loader.connected) node.__addOnconnected(loader.connect); + if(loader.disconnected) node.__addOndisconnected(loader.disconnect); + } else if (typeof loader === 'function') loader(...args); //run any passes on the nodes to set things up further + +} +function applyLoaders (node: GraphNode, parent, graph=this, tree= graph.__node.tree, properties, tag=node.__node.tag, loaders=this.__node.loaders) { + for(const l in loaders) applyLoader(node,parent,graph,tree,properties,tag,loaders[l]) +} + + + +type AnyObj = {[key:string]:any} +type GraphSpecifier = GraphNode | string + + +export type GraphNodeProperties = { + __props?:Function|GraphNodeProperties, //a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. + __operator?:((...args:any[])=>any)|string, //The 'main' function of the graph node, children will call this function if triggered by a parent. Functions passed as graphnodeproperties become the operator which can set state. + __children?:{[key:string]:GraphNodeProperties}, //child nodes belonging to this node, e.g. for propagating results + __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true,subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs + __onconnected?:((node)=>void|((node)=>void)[]), //what happens once the node is created? + __ondisconnected?:((node)=>void|((node)=>void)[]), //what happens when the node is deleted? + __node?:{ //node specific properties, can contain a lot more things + tag?:string, + [key:string]:any + }, + [key:string]:any +} + + +export type Loader = ( + node:GraphNode, + parent:Graph|GraphNode, + graph:Graph, + tree:any, + properties:GraphNodeProperties, + key:string +)=>void; + + +export type Loaders = Loader[] | {[key:string]:Loader}; + +export type GraphOptions = { + tree?:AnyObj, + loaders?:Loaders, + // { + // [key:string]:Loader|{ + // init?:Loader, + // connected?:(node)=>void, + // disconnected?:(node)=>void} + // }, + // } + mapGraphs?:false, //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? + [key:string]:any +} + + +type GraphOptionsType = { + onInit?: Function +} + +//this is a scope +export class GraphNode { + + // Confirm that the object should be recognized as graph script + __ = Symbol('graphscript') + + __node:{ + [key:string]:any, + flow: FlowManager + ref: GraphNode + graph?: Graph + } = { //GraphNode-specific properties + tag:`node${Math.floor(Math.random()*1000000000000000)}`, + unique:`${Math.random()}`, + ref: this, + flow: new FlowManager() + // operator: undefined as any, + // graph: undefined as any, + // children: undefined as any, + // localState: undefined as any, + // oncreate:undefined as any, //function or array of functions + // ondelete:undefined as any, //function or array of functions + // listeners:undefined as any, //e.g. { 'nodeA.x':(newX)=>{console.log('nodeA.x changed:',x)} } + // source:undefined as any// source graph if a graph is passed as properties + } + + __children?; + __operator?; + __listeners?; + __props?; + + [key:string]:any + + #parent?: AnyObj; + #graph?: Graph; + + #properties: AnyObj = {} + get __properties() { return this.#properties } + + #options = {} + + //pass GraphNodeProperties, functions, or tags of other nodes + constructor(properties?:any, parent?:AnyObj, graph?:Graph, options?: GraphOptionsType) { + this.__init(properties, parent, graph, options) + } + + #applied: string[] = [] + + + #applySetters = (properties=this.#properties, proxy: true | AnyObj =this.#properties, ignore: string[]=[]) => { + + const isProxy = proxy === true + let keys = Object.getOwnPropertyNames(properties); + + if (isProxy) { + proxy = properties + keys = getAllPropertyNames(properties) + + } + + for(const key of keys) { + if (ignore.includes(key)) continue; + if (this.#applied.includes(key)) continue; + + const isGraphScriptProperty = key.slice(0,2) === '__' + if (!isGraphScriptProperty) this.#applied.push(key) + + // Proxy the properties object here + if (key === '__properties') Object.defineProperty(this, key, { + get: () => this.#properties, + enumerable: false, + }) + + // When Props Loader is Specified... + // TODO: Allow this to be specified by the loader itself... + else if (key === '__props') { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => { + proxy[key] = value + this.#applySetters(value, true) + }, + enumerable: false, + configurable: true + }) + } + + // Allow overwriting graphscript properties + else if (isGraphScriptProperty) { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => proxy[key] = value, + enumerable: false, + configurable: true + }) + } + + // Do not overwrite existing properties + else { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => proxy[key] = value, + enumerable: true, //key.slice(0,2) !== '__', // Do not enumerate special keys + configurable: false + }) + } + } + } + + ____apply = this.#applySetters // Public version + + + __init = (properties, parent = this.#parent, graph = this.#graph, options: GraphOptionsType = this.#options) => { + + this.#parent = parent + this.#graph = graph + this.#options = options + + if (properties) { + + let orig = properties; + if(typeof properties === 'function') { + if(isNativeClass(properties)) { //works on custom classes + properties = new properties(); //this is a class that returns a node definition + } else properties = { + __operator:properties, + __node:{ + forward:true, //propagate operator results to children + tag:properties.name + } + }; + } else if (typeof properties === 'string') { + if(graph?.get(properties)) { + properties = graph.get(properties); + } + } + + + if(typeof properties === 'object') { + + // Handle Graph Properties + if(parent instanceof Graph && properties instanceof Graph) { + + if(properties.__node.loaders) Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); //let the parent graph adopt the child graph's loaders + properties = properties.__node.tree // apply the user-specified object properties—not the graph instance + + } + + + if (!properties.__node) properties.__node = {}; + + // Apply original object or function to the node + if(!properties.__node.initial) this.__node.initial = orig; //original object or function + + + // Create Props Proxy + // e.g. some generic javascript object or class constructor that we want to proxy. Functions passed here are treated as constructors. E.g. pass an HTML canvas element for the node then set this.width on the node to set the canvas width + if(properties.__props) { + if (typeof properties.__props === 'function') properties.__props = new properties.__props(); + } + + // Copy + if (typeof properties.__node === 'string') { + if(graph?.get(properties.__node.tag)) { + properties = graph.get(properties.__node.tag); + } else properties.__node = {} + } else if(!properties.__node) properties.__node = {}; + + + // Assign stored properties after you are sure this object will be used + this.#properties = properties + + // Set Operator on Properties + if(properties.__operator) { + if (typeof properties.__operator === 'string') { + if(graph) { + let n = graph.get(properties.__operator); + if(n) properties.__operator = n.__operator; + if(!properties.__node.tag && (properties.__operator as Function).name) + properties.__node.tag = (properties.__operator as Function).name; + } + } + } + + // Create Tag + if(!properties.__node.tag) { + if(properties.__operator?.name) properties.__node.tag = properties.__operator.name; + else properties.__node.tag = `node${Math.floor(Math.random()*1000000000000000)}`; + } + + // if (properties.__node.tag.includes('graph')) console.log('Initializing', this.__node.tag, properties.__node.tag, new Error('test')) + + // Set Graph on Node Properties + if(graph && !properties.__node.graph) properties.__node.graph = graph; + else if (graph) console.error('Skipping!') + // if(graph) properties.__node.graph = graph; + + + //nested graphs or 2nd level+ nodes get their parents as a tag + if(!properties.__parent && parent) properties.__parent = parent; + + if(parent?.__node && (!(parent instanceof Graph || properties instanceof Graph))) properties.__node.tag = parent.__node.tag + '.' + properties.__node.tag; //load parents first + + properties.__node = Object.assign(this.__node, properties.__node); + + this.#applySetters() // Set properties on the graphnode + applyLoaders.call(graph, this, parent, graph, graph?.__node?.tree, properties) // Apply loaders + this.#applySetters(undefined, undefined, ['__props']) // Proxy the new properties too + + + // Graph Script Properties are always non-enumerable + makeNonEnumerable(properties) + makeNonEnumerable(this) + + // for (let key in ogProperties) { + // this[key] = ogProperties[key] // Copy over the original properties (in case new interactions are defined by setters / proxies) + // } + + if(properties instanceof Graph) this.__node.source = properties; //keep tabs on source graphs passed to make nodes + + + + if (typeof options.onInit === 'function') options.onInit(); + + // Create flow manager for this specific node + if (graph){ + + + // FROM BEFORE SERVICE REWRITE + // let target = graph.__node.graph + // if (!target) { + // target = (graph.__node.ref ?? this) + // while (target?.__node?.graph) { + // target = target.__node.graph + // } + // } + // const symbol = target.__node.ref.__ + const symbol = (graph.__node.ref ?? this).__ + + const monitor = graph.__node.monitor + + registry[symbol] = true + // Share flow if passed in + this.__node.flow.setInitialProperties(this.__listeners, undefined, { + id: symbol, // Global symbol for this graph + instance: this, + monitor, + graph, + bound: this.__node.tag, + } + ) + + } else console.error('No flow manager created for ' + this.__node.tag) + } + } + } + + __addOnconnected(callback:(node)=>void) { + if(Array.isArray(this.__onconnected)) { this.__onconnected.push(callback); } + else if (typeof this.__onconnected === 'function') { this.__onconnected = [callback,this.__onconnected] } + else this.__onconnected = callback; + } + + __addOndisconnected(callback:(node)=>void) { + if(Array.isArray(this.__ondisconnected)) { this.__ondisconnected.push(callback); } + else if (typeof this.__ondisconnected === 'function') { this.__ondisconnected = [callback,this.__ondisconnected] } + else this.__ondisconnected = callback; + } + + __callConnected(node=this) { + if(typeof this.__onconnected === 'function') { this.__onconnected(this); } + else if (Array.isArray(this.__onconnected)) { this.__onconnected.forEach((o:Function) => { o.call(this, this); }) } + } + + __callDisconnected(node=this) { + if(typeof this.__ondisconnected === 'function') this.__ondisconnected(this); + else if (Array.isArray(this.__ondisconnected)) { this.__ondisconnected.forEach((o:Function) => {o.call(this, this)}); } + } + +} + +export class Graph { + + [key:string]:any; + + + __node:{ + tag:string, + nodes:Map, + ref: GraphNode, // Always create a GraphNode reference + loaders: Loaders + initial: GraphNodeProperties, + graph?: Graph + monitor: Monitor + [key:string]:any + } = { + tag:`graph${Math.floor(Math.random()*1000000000000000)}`, + nodes:new Map(), + ref: new GraphNode(), + loaders: [ + propsLoader + ], + monitor: new Monitor({ + keySeparator: '.', + fallbacks: ['__children'] + }) + // addState:true //apply the addLocalState on node init + // mapGraphs:false //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? + // tree:undefined as any, + } + + + + constructor( + options?:GraphOptions + ) { + this.init(options); + } + + init = (options?:GraphOptions) => { + if(options) { + + options = Object.assign({}, options) + if (options.loaders) { + this.setLoaders(options.loaders) + delete options.loaders + } + + if (!(options.graph instanceof Graph)) delete options.graph + + recursivelyAssign(this.__node, options); //assign loaders etc + + if(options.tree) this.setTree(options.tree); + // else this.#init() + } + } + + #init = (properties) => { + const node = this.__node.ref + + // const graph = this.__node.graph ?? this + node.__init(properties, this, this, { + onInit: () => { + this.__node.monitor.set(node.__, node.__properties) + } // Register node in graph monitor + }) + return node + } + + setTree = (tree:AnyObj) => { + + // --------------- Recognize node trees ---------------- + // FROM BEFORE SERVICE REWRITE + // const isGraph = tree instanceof Graph + // if (!isGraph) { + const hasGraphscriptProperties = Object.keys(tree).find(str => { + const slice = str.slice(0,2) + return (slice === '__' && str !== '__node') + }) + + if (!hasGraphscriptProperties) tree = {__children: tree} + // } + // else { + // // Update the node information + // const __node = {...tree.__node} + // delete __node.nodes + // delete __node.ref + // // delete __node.flow + // tree = {...tree, __node} + // } + + if (!tree.__node) tree.__node = {} // Set tree as a node (not all nodes are registered in the graph...) + + // ---------------- Preprocess tree ---------------- + this.__node.tree = Object.assign(this.__node.tree ? this.__node.tree : {}, tree); + + let cpy = Object.assign({}, tree); + if(cpy.__node) delete cpy.__node; //we can specify __node behaviors on the tree too to specify listeners + + // Activate the tree by creating active nodes + let listeners = this.recursiveSet(cpy,this,undefined,tree); + + // ---------------- Always Turn the tree into a node ---------------- + // Assign random tag to tree (if one is missing) + if(!tree.__node.tag) tree.__node.tag = this.__node.tag //getRandomTag('tree') + + // Activate Graph GraphNode + const node = this.#init(tree) + + // Activate all children + const children = node.__children + const copy = Object.assign({}, children) + + if (children) listeners = this.recursiveSet(copy, this, undefined, children) // Replace children with GraphNode children + + if(node.__listeners) listeners[node.__node.tag] = node.__listeners; + + // ---------------- Setup event listeners ---------------- + this.__node.nodes.forEach(n => n.__node.flow.start()) //start all node listeners + + // ---------------- "Connect" the Nodes ---------------- + node.__callConnected() + + return cpy; //should be the node tree + + } + + setLoaders = (loaders:{[key:string]:Loader} | Loader[], replace?:boolean) => { + if(replace) this.__node.loaders = loaders; + else { + + // Array Loader Specification + if (Array.isArray(this.__node.loaders)) { + if (Array.isArray(loaders)) this.__node.loaders = [...this.__node.loaders, ...loaders] + else this.__node.loaders = [...this.__node.loaders, ...Object.values(loaders)] + } + + // Object Loader Specification + else Object.assign(this.__node.loaders, loaders); + } + return this.__node.loaders; + } + + add = (properties:any, parent?:GraphSpecifier) => { + + let listeners = {}; //collect listener props declared + if(typeof parent === 'string') parent = this.get(parent); + + let instanced; + if(typeof properties === 'function') { + if(isNativeClass(properties)) { //works on custom classes + if(properties.prototype instanceof GraphNode) { properties = properties.prototype.constructor(properties,parent,this); instanced = true; } //reinstantiate a new node with the old node's props + else properties = new properties(); //this is a class that returns a node definition + } else properties = { __operator:properties }; + } + else if (typeof properties === 'string') properties = this.__node.tree[properties]; + + if(!instanced) { + properties = Object.assign({},properties); //make sure we don't mutate the original object + } + if(!properties.__node) properties.__node = {}; + properties.__node.initial = properties; + + if(typeof properties === 'object' && (!properties?.__node?.tag || !this.get(properties.__node.tag))) { + let node; + if(instanced) node = properties; + else node = new GraphNode(properties, parent as GraphNode, this); + this.set(node.__node.tag,node); + this.__node.tree[node.__node.tag] = properties; //reference the original props by tag in the tree for children + //console.log('old:',properties.__node,'new:',node.__node); + + if(node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } + + if(node.__children) { + const children = node.__children + const copy = Object.assign({}, children) + this.recursiveSet(copy, node, listeners, children); + } + + node.__callConnected(); + + return node; + + } + + return; + } + + recursiveSet = (t,parent,listeners={}, origin = t) => { + let keys = Object.getOwnPropertyNames(origin); + for(const key of keys) { + if(key.includes('__')) continue; + let p = origin[key]; + if(Array.isArray(p)) continue; + let instanced; + if(typeof p === 'function') { + if(isNativeClass(p)) { //works on custom classes + p = new p(); //this is a class that returns a node definition + if(p instanceof GraphNode) { p = p.prototype.constructor(p,parent,this); instanced = true; } //re-instance a new node + } else p = { __operator:p }; + } + else if (typeof p === 'string') p = this.__node.tree[p]; + else if (typeof p === 'boolean') p = this.__node.tree[key]; + if(typeof p === 'object') { + + // Actually we do want to mutate the original object + // if(!instanced) { + // p = Object.assign({},p); //make sure we don't mutate the original object + // } + + if(!p.__node) p.__node = {}; + if(!p.__node.tag) p.__node.tag = key; + p.__node.initial = t[key]; + if((this.get(p.__node.tag) && !(parent?.__node && this.get(parent.__node.tag + '.' + p.__node.tag))) || (parent?.__node && this.get(parent.__node.tag + '.' + p.__node.tag))) continue; //don't duplicate a node we already have in the graph by tag + let node; + if(instanced) node = p; + else { + node = new GraphNode(p, parent as GraphNode, this); + } + this.set(node.__node.tag,node); + // for(const l in this.__node.loaders) { this.__node.loaders[l](node,parent,this,t,t[key],key); } //run any passes on the nodes to set things up further + t[key] = node; //replace child with a graphnode + this.__node.tree[node.__node.tag] = p; //reference the original props by tag in the tree for children + if(node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } + if(node.__children) { + const children = node.__children + const copy = Object.assign({}, children) + this.recursiveSet(copy, node, listeners, children); + } + + let parentNode = (parent instanceof Graph) ? parent.__node.ref : parent; + + parentNode.__addOnconnected(() => node.__callConnected()); + } + } + return listeners; + } + + remove = ( + node:GraphSpecifier, + // clearListeners:boolean=true + ) => { + + if(typeof node === 'string') node = this.get(node); + + if(node instanceof GraphNode) { + this.delete(node.__node.tag); + delete this.__node.tree[node.__node.tag]; + + // if(clearListeners) + this.clearListeners(node); + + + node.__callDisconnected(); + + const recursiveRemove = (t) => { + for(const key in t) { + const node = t[key].__node.ref; // Safe access method for GraphNode class + + this.clearListeners(node) + + this.delete(node.__node.tag); + delete this.__node.tree[node.__node.tag] + this.delete(key); + delete this.__node.tree[key] + + //console.log(key, 'removing child',node); + node.__node.tag = node.__node.tag.substring(node.__node.tag.lastIndexOf('.')+1); + + // if(clearListeners) + this.clearListeners(node); + + node.__callDisconnected(); + if(node.__children) recursiveRemove(node.__children); + } + } + + if(node.__children) recursiveRemove(node.__children); + } + + if((node as any)?.__node.tag && (node as any)?.__parent) { + (node as any).__parent = undefined; + (node as any).__node.tag = (node as any).__node.tag.substring((node as any).__node.tag.indexOf('.')+1); + } + + return node; + } + + run = (node:string|GraphNode, ...args:any[]) => { + if(typeof node === 'string') { + let nd = this.get(node); + if(!nd && node.includes('.')) { + nd = this.get(node.substring(0,node.lastIndexOf('.'))); + if(typeof nd?.[node.substring(node.lastIndexOf('.')+1)] === 'function') return nd[node.substring(node.lastIndexOf('.')+1)](...args); + } else if(nd?.__operator) { + return nd.__operator(...args); + } + } + + console.log('running',node) + if((node as GraphNode)?.__operator) { + return (node as GraphNode)?.__operator(...args); + } + } + + clearListeners = (node:GraphSpecifier) => { + this.unsubscribe(node); // Clear subscriptions BOUND TO this node + this.clear(node); // Clear subscriptions to and from this node + } + + get = (tag:string, base?:GraphSpecifier) => { + + if (base instanceof GraphNode) base = base.__node.tag + + + // Get the node from the graph + if (tag === this.__node.tag) return this.__node.ref + + // Get node in the graph + if (base) { + const relFrom = [base, tag].join('.') // Assume relative targeting first + const got = this.get(relFrom) + if (got) return got + } + + return this.__node.nodes.get(tag); + }; + + set = (tag:string,node:GraphNode) => { + return this.__node.nodes.set(tag,node); + }; + delete = (tag:string) => { return this.__node.nodes.delete(tag); } + + getProps = (node:GraphSpecifier, getInitial?:boolean) => { + if(typeof node === 'string') node = this.get(node); + + if(node instanceof GraphNode) { + + let cpy; + if(getInitial) cpy = Object.assign({}, this.__node.tree[node.__node.tag]); + else { + cpy = Object.assign({},node) as any; + //remove graphnode methods to return the arbitrary props + delete cpy.__unsubscribe; + delete cpy.__setOperator; + delete cpy.__node; + delete cpy.__subscribeState; + delete cpy.__subscribe; + } + } + } + + subscribe = (from: GraphSpecifier, to: GraphSpecifier | Function, value: any = true, bound: GraphSpecifier = this.__node.ref) => { + if(typeof from !== 'string') from = from.__node.tag; + if(typeof bound === 'string') bound = this.get(bound) as GraphNode; + + if (bound) bound.__node.flow.add(from, to, value) + } + + // Unsubscribe subscriptions for a particular node + unsubscribe = (node:GraphSpecifier, from?:GraphSpecifier|symbol, to?:GraphSpecifier ) => this.clear(from, to, node) + + // Clear all nodes of a certain listener (or specific) using from / to syntax + clear = ( from?: GraphSpecifier | symbol, to?:GraphSpecifier, bound?: GraphSpecifier) => { + + const nd = (typeof bound === 'string') ? this.get(bound) : bound + + // Single Unsubscribe + if (typeof from === 'symbol') return this.__node.flow.remove(from) + + // Unsubscribe Using Listener Identifiers + let fromString = (from instanceof GraphNode) ? from.__node.tag : from + let toString = (to instanceof GraphNode) ? to.__node.tag : to + + const remove = (n) => { + const flow = n.__node.flow; + (toString) ? flow.remove(fromString, toString) : flow.clear(fromString); + } + + if (nd) remove(nd) + else { + remove(this.__node.ref) + this.__node.nodes.forEach(remove) + } + } + + + activate = (from, value) => this.__node.ref.__node.flow.activate(from, value); + + // Maintains old behavior for setState + setState = (update:AnyObj) => { + for (let key in update) this.activate(key, update); + } + +} + + +function recursivelyAssign ( + target, + obj, + // ignore:string[] = [] +) { + for(const key in obj) { + // if (ignore.includes(key)) continue; + if(obj[key]?.constructor.name === 'Object' && !Array.isArray(obj[key])) { + if(target[key]?.constructor.name === 'Object' && !Array.isArray(target[key])) + recursivelyAssign(target[key], obj[key]); + else target[key] = recursivelyAssign({},obj[key]); + } else { + target[key] = obj[key]; + //if(typeof target[key] === 'function') target[key] = target[key].bind(this); + } + } + + return target; +} + + +function getAllPropertyNames( obj ) { + var props = []; + do { + + if (obj.constructor.name === 'Object') props.push(...Object.keys(obj)) + else Object.getOwnPropertyNames( obj ).forEach(function ( prop ) { + if ( props.indexOf( prop ) === -1 ) props.push( prop ) + }); + } while ( obj = Object.getPrototypeOf( obj )); + + return props; +} + +export function instanceObject(obj) { + let props = getAllPropertyNames(obj); //e.g. Math + let instance = {} as any; + for(const key of props) instance[key] = obj[key]; + return instance; //simply copies methods, nested objects will not be instanced to limit recursion +} + +export function isNativeClass (thing) { + return typeof thing === 'function' && thing.hasOwnProperty('prototype') && !thing.hasOwnProperty('arguments') +} \ No newline at end of file diff --git a/core/index.ts b/core/index.ts new file mode 100644 index 00000000..98c04593 --- /dev/null +++ b/core/index.ts @@ -0,0 +1,3 @@ +export * from './Graph2' + +export * from './loaders' \ No newline at end of file diff --git a/core/libraries/edgelord/index.ts b/core/libraries/edgelord/index.ts new file mode 100644 index 00000000..4f2628f8 --- /dev/null +++ b/core/libraries/edgelord/index.ts @@ -0,0 +1,625 @@ +import { Graph } from "../../Graph2" + + +// Special Key Definition +const defaultPath = 'default' +const operatorPath = '__operator' +const specialKeys = { + path: '__path', + isGraphScript: '__', + listeners: { + value: '__listeners', + branch: '__branch', + bind: '__bind', + trigger: '__trigger', + format: '__format', + }, +} + +// Symbols to Recognize +const listenerObject = Symbol('listenerObject') +const toSet = Symbol('toSet') +const subscriptionKey = Symbol('subscriptionKey') +const configKey = Symbol('configKey') +const toResolveWithKey = Symbol('toResolveWithKey') + +// Configuration Options +const isConfigObject = (o) => specialKeys.listeners.format in o || specialKeys.listeners.branch in o || specialKeys.listeners.trigger in o || specialKeys.listeners.bind in o + +// Status Definitions +const initializedStatus = 'INITIALIZED' +const registeredStatus = 'REGISTERED' + +// Global References +const globalFrom = {} as any +const globalTo = {} as any +const globalActive = {} + +class Edgelord { + + unique: any = Math.random() + original = {}; + active = {} + globals: any = {} + context: any = { + options: {}, + } + rootPath: string = '' + status = '' + + graph: Graph + + #triggers: any[] = [] + #queue: any[] = [] + #toResolveWith: Edgelord + + constructor (listeners?, root?, context?) { + if (listeners || root || context) this.setInitialProperties(listeners, root, context) + } + + setInitialProperties = (listeners = {}, root, context={}) => { + + Object.assign(this.context, context) + if (root) this.rootPath = root + + if (!this.context.options.keySeparator) this.context.options.keySeparator = this.context.monitor.options.keySeparator + + this.original = listeners + + const globals = [{name: 'active', ref: globalActive}, {name: 'from', ref: globalFrom}, {name: 'to', ref: globalTo}] + globals.forEach((o) => { + if (!o.ref[this.context.id]) o.ref[this.context.id] = {} + this.globals[o.name] = o.ref[this.context.id] + }) + + this.#toResolveWith = this.getManager() + this.runEachListener(listeners, this.addToGlobalLog) + } + + getManager = (mode ='from') => { + + // Check if a higher-level listener is sending information from this root context + let target = (mode === 'to') ? this.globals.to : this.globals.from + this.rootPath.split(this.context.options.keySeparator).forEach((key) => { + if (!target[key]) target[key] = {} + target = target[key] + }) + + // if (Object.keys(target).length) this.#sendsToExternalGraph = true + return target[toResolveWithKey] ?? this + } + + onStart = (f) => { + const res = this.#toResolveWith + const isSame = res === this + if (isSame) { + if (this.status === initializedStatus) f() + else this.#queue.push(f) + } else res.onStart(f) + } + + runEachListener = (listeners, callback) => { + if (!callback) return + for (const first in listeners) { + const second = listeners[first] + + if (!second) { + console.warn('Skipping empty listener:', first) + continue; + } + + // NOTE: Listener sheets are to / from + if (second && typeof second === 'object') { + const from = second + const to = first + for (let fromPath in from) { + callback( + fromPath, // From Path + to, // To Path + from[fromPath] // Value + ) + } + } + + // Immediate Absolute Paths Only + // NOTE: Direct listeners are from / to + else { + const from = first + const to = second + + const typeOf = typeof to + if (typeOf === 'function') callback(from, '', to) + else if (typeOf === 'string') callback(from, to, to) + else console.error('Improperly Formatted Listener', to) + } + } + + } + + register = (listeners = this.original) => { + + this.runEachListener(listeners, this.add) + this.status = registeredStatus + } + + #initialize = (o) => { + const res = this.context.monitor.get(o.path, 'info') + if (typeof res.value === 'function') { + const args = (Array.isArray(o.args)) ? o.args : [o.args] + res.value(...args) + } + else console.error('Cannot yet trigger values...', o) + } + + initialize = (o?) => { + if (!this.status) this.#triggers.push(o) + else if (this.status === registeredStatus) { + this.status = initializedStatus + this.#triggers.forEach(this.#initialize) + this.#queue.forEach(f => f()) + this.#queue = [] + this.#triggers = [] + } else this.#initialize(o) + } + + start = () => { + this.register() + this.initialize() + } + + #getAbsolutePath = (name) => { + const sep = this.context.monitor.options.keySeparator + return ( + !name + || !this.rootPath + || (this.rootPath === name.slice(0, this.rootPath.length) && name[this.rootPath.length] === sep) + ) ? name : [this.rootPath, name].join(sep) + } + + #getPathInfo = (path) => { + + const output = { + absolute: {}, + relative: {} + } as any + + // Transform name to absolute + path = this.#getAbsolutePath(path) + let rel = this.rootPath ? path.replace(`${this.rootPath}.`, '') : path + const baseArr = path.split(this.context.options.keySeparator) + output.absolute.array = [this.context.id, ...baseArr] + output.relative.array = rel.split(this.context.options.keySeparator) + + let obj = this.context.monitor.get(output.relative.array, undefined, this.context.instance, false) // Allow for getting properties + + // Fallback to direct graph reference + if (this.context.graph) { + + // Correct for paths that are relative to the bound object + if (obj && this.context.bound) { + output.absolute.array = [this.context.id, this.context.bound, ...output.absolute.array.slice(1)] + output.relative.array.unshift(this.context.bound) + } + + // Assume you are targeting the global graph + else if (!obj) { + const rel = output.relative.array.join(this.context.options.keySeparator) + obj = this.context.graph.get(rel) + } + } + + const isGraphScript = obj && typeof obj === 'object' && specialKeys.isGraphScript in obj + + // Updates based on default / operators + if (isGraphScript) { + + // Fallback to operator updates + if (obj[operatorPath]){ + output.absolute.array.push(operatorPath) + output.relative.array.push(operatorPath) + } + + // Fallback to default updates + else if (obj[defaultPath]){ + output.absolute.array.push(defaultPath) + output.relative.array.push(defaultPath) + } + } + + output.absolute.value = output.absolute.array.slice(1).join(this.context.options.keySeparator) // update path + output.relative.value = output.relative.array.join(this.context.options.keySeparator) // update path + + return output + } + + add = (from, to, value: any = true, subscription?) => { + + + if (typeof to == 'function') { + value = to + to = '' // Actually to a function + } else if (typeof to !== 'string') { + console.error('Improperly Formatted Listener', from, to, value) + return + } + + if (!value) return // Any non-truthy value is not accepted + + const fromInfo = this.#getPathInfo(from) + const toInfo = this.#getPathInfo(to) + + // Check global for subscription + const absPath = fromInfo.absolute.value + if (!subscription) subscription = this.globals.active[absPath]?.[subscriptionKey] + + // Only subscribe once + if (!subscription) { + subscription =this.context.monitor.on(fromInfo.absolute.array, (path, _, update) => this.activate(path, update), { + ref: this.context.instance, + path: fromInfo.relative.array + }) + // console.log('Subscribing', fromInfo.absolute.array, subscription) + } + + // Use updated string value if modified + if (typeof value == 'string') value = toInfo.absolute.array.slice(1).join(this.context.options.keySeparator) + + const info = { + value, + [listenerObject]: true + } + + const refs = [this.active, this.globals.active] + + refs.forEach(ref => { + if(!ref[absPath]) ref[absPath] = {} + const base = ref[absPath] + if (!base[subscriptionKey]) { + Object.defineProperty(base, subscriptionKey, { + value: subscription, + configurable: true + }) + } + base[toInfo.absolute.value] = info + }) + + // // Update Original + // let base = this.original[toInfo.relative.value] + // if (!base) base = this.original[toInfo.relative.value] = {} + // if (typeof base !== 'object') { + // if (typeof base === 'function') base = this.original[toInfo.relative.value] = {[Symbol('function listener')]: base} // Move function to arbitrary key + // else base = this.original[toInfo.relative.value] = {[base]: true} // Move string to a complex listener + // } + // base[fromInfo.relative.value] = value // complex listener + + // Initalize triggers (possible on higherl-level manager) + const args = value[specialKeys.listeners.trigger] + if (args) this.#toResolveWith.initialize({ + path: fromInfo.absolute.array, + args + }) + + this.addToGlobalLog(absPath) + + + return info + } + + addToGlobalLog = (path, mode = 'from') => { + + const absolutePath = this.#getAbsolutePath(path) + + // Register in global registry + let target = (mode === 'to') ? this.globals.to : this.globals.from + const globalPath = absolutePath.split(this.context.options.keySeparator) + globalPath.forEach((key) => { + if (!target[key]) target[key] = {} + target = target[key] + if (!(target[toResolveWithKey])) target[toResolveWithKey] = this // Always set with the lowest + }) + + } + + // Local removal + remove = (from, to) => { + const fromInfo = this.#getPathInfo(from) + const toInfo = this.#getPathInfo(to) + + const path = [fromInfo.absolute.value, toInfo.absolute.value] + const toRemove = [ + { ref: this.active, path }, + { ref: this.globals.active, path, unlisten: true }, // Remove subscription if required + // { ref: this.original, path: [toInfo.relative.value, fromInfo.relative.value] }, // Just removing from the list + ] + + + toRemove.forEach(o => { + const { ref, path, unlisten } = o + + let base = ref[path[0]] + + if (typeof base === 'object') { + delete base[path[1]] // complex listener + if (Object.keys(base).length === 0) { + delete ref[path[0]] + const sub = base[subscriptionKey] + if (unlisten && sub) { + this.context.monitor.remove(sub) // Cleaning up subscriptions (active only) + } + delete base[subscriptionKey] + } + + } else delete ref[path[0]] // simple listener + + }) + + } + + // Local clearing + clear = (name) => { + const value = this.#getAbsolutePath(name) + + Object.keys(this.active).forEach(from => { + Object.keys(this.active[from]).forEach(to => { + if ( + !value + || from.slice(0, value.length) === value // Matches from + || to.slice(0, value.length) === value // Matches to + ) this.remove(from, to) + }) + }) + } + + has = (from, ref=this.active) => !!ref[from] + + get = (from, ref=this.active) => ref[from] + + + + // ----------------- Global Flow Activation Management ----------------- + activate = (from, update) => { + + console.log('Activating', from, update) + console.log('Active', this.globals.active) + const listenerGroups = [{ + info: this.get(from, this.globals.active), + name: from + }] + + listenerGroups.forEach(group => { + + const info = group.info + + if (info) { + + if (info[listenerObject]) { + + this.pass(from, { + value: info.value, + parent: this.active, + key: group.name, + subscription: info.subscription, + __value: true + }, update) + } else if (typeof info === 'object') { + for (let key in info) { + this.pass(from, { + parent: info, + key, + subscription: info[key].subscription, + value: info[key].value, + }, update) + } + } else console.error('Improperly Formatted Listener', info) + } + }) +} + +pass = (from, target, update) => { + + const id = this.context.id + const isValue = target?.__value + let parent = target.parent + let to = target.key + + + // const rootArr = root.split(this.context.options.keySeparator) + const info = target.parent[to] + target = info.value + + let config = info?.[configKey] // Grab config + + let ogValue = target + const type = typeof target + + const checkIfSetter = (path, willSet) => { + + const info = this.context.monitor.get(path, 'info') + if (info.exists) { + const val = info.value + const noDefault = typeof val !== 'function' && !val?.default + const value = (noDefault) ? toSet : val + + const res = { value } + + if (willSet) { + target = res.value + parent[to] = res + } + + return res + } else return { value: undefined } //, root: undefined } + + } + + const transform = (willSet?) => { + const fullPath = [id] + // if (root) fullPath.push(...rootArr) // correcting for relative string + fullPath.push(...to.split(this.context.options.keySeparator)) + return checkIfSetter(fullPath, willSet) + } + + // ------------------ Grab Correct Target to Listen To ------------------ + + + const getPathArray = (latest) => { + const path = [id] + const topPath: any[] = [] + if (this.rootPath) topPath.push(...this.rootPath.split(this.context.options.keySeparator)) // correcting for relative string + topPath.push(...latest.split(this.context.options.keySeparator)) + path.push(...topPath) + return path + } + + // Confirmation of the target + if (typeof target === 'boolean') { + if (!isValue) transform(true) + else console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`) + } + + // Name of the target + else if (type === 'string') { + const path = getPathArray(ogValue) + checkIfSetter(path, true) + + if (isValue) { + parent[to] = { [ogValue]: parent[to] } + to = ogValue + } + } + + else if (target && type === 'object') { + + // Check if configuration object + const isConfig = isConfigObject(ogValue) + + if (isConfig) { + + if ('value' in ogValue) { + if (isValue) { + target = parent[to] = ogValue.value // setting value + } else { + target = parent[to].value = ogValue.value // setting value + } + } else transform(true) + + if (ogValue){ + if (ogValue) config = ogValue + } + + Object.defineProperty(parent[to], configKey, { value: config }) + } + + } + + // ------------------ Special Keywords ------------------ + let isValidInput = true + + if (config) { + + + const bindKey = specialKeys.listeners.value + if (bindKey in config) { + + // (de)Register listeners at runtime... + const path = getPathArray(config[bindKey].original ?? config[bindKey]) + if (typeof config[bindKey] === 'string') { + const res = this.context.monitor.get(path) + if (!res) target = `because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.` + else { + config[bindKey] = { + value: res, + original: config[bindKey] + } + } + } else if (!config[bindKey].value.__parent) { + target = `because ${config[bindKey].original ?? id.toString()} has become unparented.` + } + + } + + else { + + const branchKey = specialKeys.listeners.branch + const formatKey = specialKeys.listeners.format + + if (branchKey in config) { + + const isValid = config[branchKey].find(o => { + + let localValid: boolean[] = [] + if ('if' in o) localValid.push(o.if(update)) // Condition Function + if ('is' in o) localValid.push(o.is === update) // Equality Check + const isValidLocal = localValid.length > 0 && localValid.reduce((a, b) => a && b, true) + + if (isValidLocal) { + if ('value' in o) update = o.value // set first argument to branch value + } + + return isValidLocal + }) + + if (!isValid) isValidInput = false + } + + + + // NOTE: May turn into an array here + if (formatKey in config) { + try { + update = config[formatKey](update) + if (update === undefined) isValidInput = false + } catch (e) { console.error('Failed to format arguments', e) } + } + + } + } + + // ------------------ Handle Target ------------------ + + // console.log('target', target, isValidInput, update) + if ( + isValidInput // Ensure input is valid + && update !== undefined // Ensure input is not exactly undefined (though null is fine) + ) { + + const arrayUpdate = Array.isArray(update) ? update : [update] + + + // Set New Value on Parent + if (target === toSet) { + const parentPath = [id] + // if (root) parentPath.push(...rootArr) // TODO: Check if this needs fixing + parentPath.push(...to.split(this.context.options.keySeparator)) + const idx = parentPath.pop() + const info = this.context.monitor.get(parentPath, 'info') + if (info.value) info.value[idx] = update + else console.error(`Cannot set value on ${parentPath.filter(str => typeof str !== 'symbol').join(this.context.options.keySeparator)} from ${from}`) + } + + // Direct Object with Default Function + else if (target?.default) target.default.call(target, ...arrayUpdate) // Call with parent context + + // Direct Function + else if (typeof target === 'function') { + const noContext = parent[to][listenerObject] + if (noContext) target.call(config?.[specialKeys.listeners.bind]?.value ?? this.context.instance, ...arrayUpdate) // Call with top-level context + else target(...arrayUpdate) // Call with default context + } + + // Failed + else { + + let baseMessage = (to) ? `listener: ${from} —> ${to}` : `listener from ${from}` + if (parent) { + console.warn(`Deleting ${baseMessage}`, target) + delete parent[to] + } else console.error(`Failed to add ${baseMessage}`, target) + } + } +} + + +} + +export default Edgelord \ No newline at end of file diff --git a/core/libraries/esmonitor/dist/index.esm.js b/core/libraries/esmonitor/dist/index.esm.js new file mode 100644 index 00000000..3ab14c24 --- /dev/null +++ b/core/libraries/esmonitor/dist/index.esm.js @@ -0,0 +1,990 @@ +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// ../common/check.js +var moduleStringTag = "[object Module]"; +var esm = (object) => { + const res = object && (!!Object.keys(object).reduce((a, b) => { + const desc = Object.getOwnPropertyDescriptor(object, b); + const isModule = desc && desc.get && !desc.set ? 1 : 0; + return a + isModule; + }, 0) || Object.prototype.toString.call(object) === moduleStringTag); + return !!res; +}; + +// src/utils.ts +var isSame = (a, b) => { + if (a && typeof a === "object" && b && typeof b === "object") { + const jA = JSON.stringify(a); + const jB = JSON.stringify(b); + return jA === jB; + } else + return a === b; +}; +var iterateSymbols = (obj, callback) => { + return Promise.all(Object.getOwnPropertySymbols(obj).map((sym) => callback(sym, obj[sym]))); +}; +var getPath = (type, info2) => { + const pathType = info2.path[type]; + if (!pathType) + throw new Error("Invalid Path Type"); + const filtered = pathType.filter((v) => typeof v === "string"); + return filtered.join(info2.keySeparator); +}; +var getPathInfo = (path, options) => { + let splitPath = path; + if (typeof path === "string") + splitPath = path.split(options.keySeparator); + else if (typeof path === "symbol") + splitPath = [path]; + return { + id: splitPath[0], + path: splitPath.slice(1) + }; +}; +var runCallback = (callback, path, info2, output, setGlobal = true) => { + if (callback instanceof Function) { + if (output && typeof output === "object" && typeof output.then === "function") + output.then((value) => callback(path, info2, value)); + else + callback(path, info2, output); + } + if (setGlobal && globalThis.ESMonitorState) { + const callback2 = globalThis.ESMonitorState.callback; + globalThis.ESMonitorState.state[path] = { output, value: info2 }; + runCallback(callback2, path, info2, output, false); + } +}; + +// src/Poller.ts +var defaultSamplingRate = 60; +var Poller = class { + constructor(listeners2, sps) { + this.listeners = {}; + this.setOptions = (opts = {}) => { + for (let key in opts) + this[key] = opts[key]; + }; + this.add = (info2) => { + const sub = info2.sub; + this.listeners[sub] = info2; + this.start(); + return true; + }; + this.get = (sub) => this.listeners[sub]; + this.remove = (sub) => { + delete this.listeners[sub]; + if (!Object.keys(this.listeners).length) + this.stop(); + }; + this.poll = (listeners2) => { + iterateSymbols(listeners2, (sym, o) => { + let { callback, current, history } = o; + if (!o.path.resolved) + o.path.resolved = getPath("output", o); + if (!isSame(current, history)) { + runCallback(callback, o.path.resolved, {}, current); + if (typeof current === "object") { + if (Array.isArray(current)) + history = [...current]; + else + history = { ...current }; + } else + listeners2[sym].history = current; + } + }); + }; + this.start = (listeners2 = this.listeners) => { + if (!this.sps) + this.sps = defaultSamplingRate; + else if (!this.#pollingId) { + console.warn("[escode]: Starting Polling!"); + this.#pollingId = setInterval(() => this.poll(listeners2), 1e3 / this.sps); + } + }; + this.stop = () => { + if (this.#pollingId) { + console.warn("[escode]: Stopped Polling!"); + clearInterval(this.#pollingId); + this.#pollingId = void 0; + } + }; + if (listeners2) + this.listeners = listeners2; + if (sps) + this.sps = sps; + } + #pollingId; + #sps; + get sps() { + return this.#sps; + } + set sps(sps) { + this.#sps = sps; + const listeners2 = this.listeners; + const nListeners = Object.keys(listeners2).length; + if (nListeners) { + this.stop(); + this.start(); + } + } +}; + +// src/listeners.ts +var listeners_exports = {}; +__export(listeners_exports, { + functionExecution: () => functionExecution, + functions: () => functions2, + getProxyFunction: () => getProxyFunction, + info: () => info, + register: () => register, + set: () => set, + setterExecution: () => setterExecution, + setters: () => setters +}); + +// src/global.ts +globalThis.ESMonitorState = { + state: {}, + callback: void 0, + info: {} +}; +var global_default = globalThis.ESMonitorState; + +// src/info.ts +var performance = async (callback, args) => { + const tic = globalThis.performance.now(); + const output = await callback(...args); + const toc = globalThis.performance.now(); + return { + output, + value: toc - tic + }; +}; +var infoFunctions = { + performance +}; +var get = (func, args, info2) => { + let result = { + value: {}, + output: void 0 + }; + const infoToGet = { ...global_default.info, ...info2 }; + for (let key in infoToGet) { + if (infoToGet[key] && infoFunctions[key]) { + const ogFunc = func; + func = async (...args2) => { + const o = await infoFunctions[key](ogFunc, args2); + result.value[key] = o.value; + return o.output; + }; + } + } + result.output = func(...args); + return result; +}; + +// src/globals.ts +var isProxy = Symbol("isProxy"); +var fromInspectable = Symbol("fromInspectable"); +var fromInspectableHandler = Symbol("fromInspectableHandler"); + +// ../esc/standards.js +var keySeparator = "."; + +// ../common/pathHelpers.ts +var hasKey = (key, obj) => key in obj; +var getShortcut = (path, shortcuts, keySeparator2) => { + const sc = shortcuts[path[0]]; + if (sc) { + const value = sc[path.slice(1).join(keySeparator2)]; + if (value) + return value; + } +}; +var getFromPath = (baseObject, path, opts = {}) => { + const fallbackKeys = opts.fallbacks ?? []; + const keySeparator2 = opts.keySeparator ?? keySeparator; + if (opts.shortcuts) { + const shortcut = getShortcut(path, opts.shortcuts, keySeparator2); + if (shortcut) { + if (opts.output === "info") + return { value: shortcut, exists: true, shortcut: true }; + else + return shortcut; + } + } + if (typeof path === "string") + path = path.split(keySeparator2).flat(); + else if (typeof path == "symbol") + path = [path]; + let exists; + path = [...path]; + path = path.map((o) => typeof o === "string" ? o.split(keySeparator2) : o).flat(); + let ref = baseObject; + for (let i = 0; i < path.length; i++) { + if (ref) { + const str = path[i]; + if (!hasKey(str, ref) && "__children" in ref) { + for (let i2 in fallbackKeys) { + const key = fallbackKeys[i2]; + if (hasKey(key, ref)) { + ref = ref[key]; + break; + } + } + } + exists = hasKey(str, ref); + if (exists) + ref = ref[str]; + else { + ref = void 0; + exists = true; + } + } + } + if (opts.output === "info") + return { value: ref, exists }; + else + return ref; +}; +var setFromPath = (path, value, ref, opts = {}) => { + const create = opts?.create ?? false; + const keySeparator2 = opts?.keySeparator ?? keySeparator; + if (typeof path === "string") + path = path.split(keySeparator2); + else if (typeof path == "symbol") + path = [path]; + path = [...path]; + const copy = [...path]; + const last = copy.pop(); + if (ref.__children) + ref = ref.__children; + for (let i = 0; i < copy.length; i++) { + const str = copy[i]; + let has = hasKey(str, ref); + if (create && !has) { + ref[str] = {}; + has = true; + } + if (has) + ref = ref[str]; + if (ref.__children) + ref = ref.__children; + } + ref[last] = value; + return true; +}; + +// src/inspectable/handlers.ts +var handlers_exports = {}; +__export(handlers_exports, { + functions: () => functions, + objects: () => objects +}); + +// src/inspectable/define.ts +function define(key, registerAsNewKey) { + const inspectable = this; + const target = this.target; + if (!this.parent) { + let value = target[key]; + if (typeof value === "function") { + target[key] = async (...args) => await this.proxy[key]({ [fromInspectable]: true, value }, ...args); + } else { + try { + Object.defineProperty(target, key, { + get: () => value, + set: function(val) { + value = val; + inspectable.proxy[key] = { [isProxy]: this[isProxy], [fromInspectable]: true, value: val }; + }, + enumerable: true, + configurable: true + }); + } catch (e) { + console.error(`Could not reassign ${key} to a top-level setter...`); + } + } + } + if (registerAsNewKey) + this.newKeys.add(key); + this.create(key, target, void 0, true); +} +var define_default = define; + +// src/inspectable/handlers.ts +var functions = function() { + const inspectable = this; + return { + apply: async function(target, thisArg, argumentsList) { + try { + let foo = target; + const isFromInspectable = argumentsList[0]?.[fromInspectable]; + if (isFromInspectable) { + foo = argumentsList[0].value; + argumentsList = argumentsList.slice(1); + } + let listeners2 = inspectable.listeners.functions; + const pathStr = inspectable.path.join(inspectable.options.keySeparator); + const toActivate = listeners2 ? listeners2[pathStr] : void 0; + let output, executionInfo = {}; + if (toActivate) { + executionInfo = functionExecution(thisArg, toActivate, foo, argumentsList); + output = executionInfo.output; + } else { + output = foo.apply(thisArg, argumentsList); + executionInfo = inspectable?.state?.[pathStr]?.value ?? {}; + } + const callback = inspectable.options.callback; + runCallback(callback, pathStr, executionInfo, output); + return output; + } catch (e) { + console.warn(`Function failed:`, e, inspectable.path); + } + } + }; +}; +var objects = function() { + const inspectable = this; + return { + get(target, prop, receiver) { + if (prop === isProxy) + return true; + return Reflect.get(target, prop, receiver); + }, + set(target, prop, newVal, receiver) { + if (prop === isProxy) + return true; + const pathStr = [...inspectable.path, prop].join(inspectable.options.keySeparator); + const isFromProxy = newVal?.[isProxy]; + const isFromInspectable = newVal?.[fromInspectable]; + if (isFromInspectable) + newVal = newVal.value; + const listeners2 = inspectable.listeners.setters; + const desc = Object.getOwnPropertyDescriptor(target, prop); + const createListener = desc && !desc.get && !desc.set; + if (createListener) { + if (typeof inspectable.options.globalCallback === "function") { + const id = inspectable.path[0]; + define_default.call(inspectable, prop, true); + set("setters", pathStr, newVal, inspectable.options.globalCallback, { [id]: inspectable.root }, inspectable.listeners, inspectable.options); + } + } + if (newVal) { + const newProxy = inspectable.create(prop, target, newVal); + if (newProxy) + newVal = newProxy; + } + const toActivate = !isFromProxy; + if (listeners2 && toActivate && !inspectable.newKeys.has(prop)) { + const toActivate2 = listeners2[pathStr]; + if (toActivate2) + setterExecution(toActivate2, newVal); + } + const callback = inspectable.options.callback; + const info2 = inspectable?.state?.[pathStr]?.value ?? {}; + runCallback(callback, pathStr, info2, newVal); + if (isFromInspectable || !toActivate) + return true; + else + return Reflect.set(target, prop, newVal, receiver); + } + }; +}; + +// src/inspectable/index.ts +var canCreate = (parent, key, val) => { + try { + if (val === void 0) + val = parent[key]; + } catch (e) { + return e; + } + const alreadyIs = parent[key] && parent[key][isProxy]; + if (alreadyIs) + return false; + const type = typeof val; + const isObject = type === "object"; + const isFunction = type == "function"; + const notObjOrFunc = !val || !(isObject || isFunction); + if (notObjOrFunc) + return false; + if (val instanceof Element) + return false; + if (val instanceof EventTarget) + return false; + const isESM = isObject && esm(val); + if (isFunction) + return true; + else { + const desc = Object.getOwnPropertyDescriptor(parent, key); + if (desc && (desc.value && desc.writable || desc.set)) { + if (!isESM) + return true; + } else if (!parent.hasOwnProperty(key)) + return true; + } + return false; +}; +var Inspectable = class { + constructor(target = {}, opts = {}, name, parent) { + this.path = []; + this.listeners = {}; + this.newKeys = /* @__PURE__ */ new Set(); + this.state = {}; + this.set = (path, info2, update) => { + this.state[path] = { + output: update, + value: info2 + }; + setFromPath(path, update, this.proxy, { create: true }); + }; + this.check = canCreate; + this.create = (key, parent, val, set2 = false) => { + const create = this.check(parent, key, val); + if (val === void 0) + val = parent[key]; + if (create && !(create instanceof Error)) { + parent[key] = new Inspectable(val, this.options, key, this); + return parent[key]; + } + if (set2) { + try { + this.proxy[key] = val ?? parent[key]; + } catch (e) { + const isESM = esm(parent); + const path = [...this.path, key]; + console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM ? " because the parent is an ESM." : ""}`, isESM ? "" : e); + } + } + return; + }; + if (!opts.pathFormat) + opts.pathFormat = "relative"; + if (!opts.keySeparator) + opts.keySeparator = keySeparator; + if (target.__proxy) + this.proxy = target.__proxy; + else if (target[isProxy]) + this.proxy = target; + else { + this.target = target; + this.options = opts; + this.parent = parent; + if (this.parent) { + this.root = this.parent.root; + this.path = [...this.parent.path]; + this.state = this.parent.state ?? {}; + } else + this.root = target; + if (name) + this.path.push(name); + if (this.options.listeners) + this.listeners = this.options.listeners; + if (this.options.path) { + if (this.options.path instanceof Function) + this.path = this.options.path(this.path); + else if (Array.isArray(this.options.path)) + this.path = this.options.path; + else + console.log("Invalid path", this.options.path); + } + if (this.path) + this.path = this.path.filter((str) => typeof str === "string"); + if (!this.options.keySeparator) + this.options.keySeparator = keySeparator; + let type = this.options.type; + if (type != "object") + type = typeof target === "function" ? "function" : "object"; + const handler2 = handlers_exports[`${type}s`].call(this); + this.proxy = new Proxy(target, handler2); + Object.defineProperty(target, "__proxy", { value: this.proxy, enumerable: false }); + Object.defineProperty(target, "__esInspectable", { value: this, enumerable: false }); + for (let key in target) + define_default.call(this, key); + } + return this.proxy; + } +}; + +// src/optionsHelpers.ts +var setFromOptions = (path, value, baseOptions, opts) => { + const ref = opts.reference; + const id = Array.isArray(path) ? path[0] : typeof path === "string" ? path.split(baseOptions.keySeparator)[0] : path; + let isDynamic = opts.hasOwnProperty("static") ? !opts.static : false; + if (isDynamic && !globalThis.Proxy) { + isDynamic = false; + console.warn("Falling back to using function interception and setters..."); + } + if (isDynamic) { + value = new Inspectable(value, { + pathFormat: baseOptions.pathFormat, + keySeparator: baseOptions.keySeparator, + listeners: opts.listeners, + path: (path2) => path2.filter((str) => !baseOptions.fallbacks || !baseOptions.fallbacks.includes(str)) + }, id); + } + let options = { keySeparator: baseOptions.keySeparator, ...opts }; + setFromPath(path, value, ref, options); + return value; +}; + +// src/listeners.ts +var info = (id, callback, path, originalValue, base, listeners2, options, refShortcut = {}) => { + if (typeof path === "string") + path = path.split(options.keySeparator); + const relativePath = path.join(options.keySeparator); + const refs = base; + const shortcutRef = refShortcut.ref; + const shortcutPath = refShortcut.path; + const get3 = (path2) => { + const thisBase = shortcutRef ?? base; + const res = getFromPath(thisBase, path2, { + keySeparator: options.keySeparator, + fallbacks: options.fallbacks + }); + return res; + }; + const set2 = (path2, value) => { + const thisBase = shortcutRef ?? base; + setFromOptions(path2, value, options, { + reference: thisBase, + listeners: listeners2 + }); + }; + let onUpdate = options.onUpdate; + let infoToOutput = {}; + if (onUpdate && typeof onUpdate === "object" && onUpdate.callback instanceof Function) { + infoToOutput = onUpdate.info ?? {}; + onUpdate = onUpdate.callback; + } + const absolute = [id, ...path]; + let pathInfo = { + absolute, + relative: relativePath.split(options.keySeparator), + parent: absolute.slice(0, -1) + }; + pathInfo.output = pathInfo[options.pathFormat]; + const completePathInfo = pathInfo; + const info2 = { + id, + path: completePathInfo, + keySeparator: options.keySeparator, + infoToOutput, + callback: (...args) => { + const output = callback(...args); + if (onUpdate instanceof Function) + onUpdate(...args); + return output; + }, + get current() { + return get3(shortcutPath ?? info2.path.absolute); + }, + set current(val) { + set2(shortcutPath ?? info2.path.absolute, val); + }, + get parent() { + return get3(shortcutPath ? shortcutPath?.slice(0, -1) : info2.path.parent); + }, + get reference() { + return refs[id]; + }, + set reference(val) { + refs[id] = val; + }, + original: originalValue, + history: typeof originalValue === "object" ? Object.assign({}, originalValue) : originalValue, + sub: Symbol("subscription"), + last: path.slice(-1)[0] + }; + return info2; +}; +var registerInLookup = (name, sub, lookups) => { + if (lookups) { + const id = Math.random(); + lookups.symbol[sub] = { + name, + id + }; + if (!lookups.name[name]) + lookups.name[name] = {}; + lookups.name[name][id] = sub; + } +}; +var register = (info2, collection, lookups) => { + const absolute = getPath("absolute", info2); + if (!collection[absolute]) + collection[absolute] = {}; + collection[absolute][info2.sub] = info2; + registerInLookup(absolute, info2.sub, lookups); + return true; +}; +var listeners = { + functions: functions2, + setters +}; +var set = (type, absPath, value, callback, base, allListeners, options) => { + const { id, path } = getPathInfo(absPath, options); + const fullInfo = info(id, callback, path, value, base, listeners, options); + if (listeners[type]) + listeners[type](fullInfo, allListeners[type], allListeners.lookup); + else { + const path2 = getPath("absolute", fullInfo); + allListeners[type][path2][fullInfo.sub] = fullInfo; + if (allListeners.lookup) + registerInLookup(path2, fullInfo.sub, allListeners.lookup); + } +}; +var get2 = (info2, collection) => collection[getPath("absolute", info2)]; +var handler = (info2, collection, subscribeCallback, lookups) => { + let success = !!get2(info2, collection); + if (!success) { + let parent = info2.parent; + let val = parent?.[info2.last]; + success = subscribeCallback(val, parent); + } + return register(info2, collection, lookups); +}; +var setterExecution = (listeners2, value) => { + return iterateSymbols(listeners2, (_, o) => { + const path = getPath("output", o); + runCallback(o.callback, path, {}, value); + }); +}; +function setters(info2, collection, lookups) { + const thisValue = this; + return handler(info2, collection["setters"], (value, parent) => { + let val = value; + if (!parent) + return; + if (!parent[isProxy]) { + let redefine = true; + try { + delete parent[info2.last]; + } catch (e) { + console.error("Unable to redeclare setters. May already be a dynamic object..."); + redefine = false; + } + if (redefine) { + const isGraphScriptProperty = info2.last.slice(0, 2) === "__"; + try { + Object.defineProperty(parent, info2.last, { + get: () => val, + set: async (v) => { + const isFunction = typeof val === "function"; + val = v; + if (!isFunction) { + const listeners2 = Object.assign({}, collection["setters"][getPath("absolute", info2)]); + setterExecution(listeners2, v); + } else + val = getProxyFunction.call(thisValue, info2, collection, val); + }, + enumerable: isGraphScriptProperty, + configurable: true + }); + } catch (e) { + throw e; + } + } + } + }, lookups); +} +function getProxyFunction(info2, collection, fn) { + return function(...args) { + const listeners2 = collection["functions"][getPath("absolute", info2)]; + return functionExecution(this, listeners2, fn ?? info2.original, args); + }; +} +var functionExecution = (context, listeners2, func, args) => { + listeners2 = Object.assign({}, listeners2); + const keys = Object.getOwnPropertySymbols(listeners2); + const infoTemplate = listeners2[keys[0]] ?? {}; + const executionInfo = get((...args2) => func.call(context, ...args2), args, infoTemplate.infoToOutput); + iterateSymbols(listeners2, (_, o) => { + const path = getPath("output", o); + runCallback(o.callback, path, executionInfo.value, executionInfo.output); + }); + return executionInfo; +}; +function functions2(info2, collection, lookups) { + return handler(info2, collection["functions"], (_, parent) => { + if (!parent[isProxy]) { + parent[info2.last] = getProxyFunction.call(this, info2, collection); + return setters(info2, collection, lookups); + } + }, lookups); +} + +// ../common/drill.js +var drillSimple = (obj, callback, options) => { + let accumulator = options.accumulator; + if (!accumulator) + accumulator = options.accumulator = {}; + const ignore = options.ignore || []; + const path = options.path || []; + const condition = options.condition || true; + const seen = []; + const fromSeen = []; + let drill = (obj2, acc = {}, globalInfo) => { + for (let key in obj2) { + if (ignore.includes(key)) + continue; + const val = obj2[key]; + const newPath = [...globalInfo.path, key]; + const info2 = { + typeof: typeof val, + name: val?.constructor?.name, + simple: true, + object: val && typeof val === "object", + path: newPath + }; + if (info2.object) { + const name = info2.name; + const isESM = esm(val); + if (isESM || name === "Object" || name === "Array") { + info2.simple = true; + const idx = seen.indexOf(val); + if (idx !== -1) + acc[key] = fromSeen[idx]; + else { + seen.push(val); + const pass = condition instanceof Function ? condition(key, val, info2) : condition; + info2.pass = pass; + acc[key] = callback(key, val, info2); + if (pass) { + fromSeen.push(acc[key]); + acc[key] = drill(val, acc[key], { ...globalInfo, path: newPath }); + } + } + } else { + info2.simple = false; + acc[key] = callback(key, val, info2); + } + } else + acc[key] = callback(key, val, info2); + } + return acc; + }; + return drill(obj, accumulator, { path }); +}; + +// src/Monitor.ts +var createLookup = () => { + return { symbol: {}, name: {} }; +}; +var Monitor = class { + constructor(opts = {}) { + this.poller = new Poller(); + this.options = { + pathFormat: "relative", + keySeparator + }; + this.listeners = { + polling: this.poller.listeners, + functions: {}, + setters: {}, + lookup: createLookup() + }; + this.references = {}; + this.get = (path, output, reference = this.references, throwError = true) => { + return getFromPath(reference, path, { + keySeparator: this.options.keySeparator, + fallbacks: this.options.fallbacks, + output + }, throwError); + }; + this.set = (path, value, opts = {}) => { + const optsCopy = { ...opts }; + if (!optsCopy.reference) + optsCopy.reference = this.references; + if (!optsCopy.listeners) + optsCopy.listeners = this.listeners; + return setFromOptions(path, value, this.options, optsCopy); + }; + this.on = (absPath, callback) => { + const info2 = getPathInfo(absPath, this.options); + return this.listen(info2.id, callback, info2.path); + }; + this.getInfo = (label, callback, path, original) => { + const info2 = info(label, callback, path, original, this.references, this.listeners, this.options); + const id = Math.random(); + const lookups = this.listeners.lookup; + const name = getPath("absolute", info2); + lookups.symbol[info2.sub] = { + name, + id + }; + if (!lookups.name[name]) + lookups.name[name] = {}; + lookups.name[name][id] = info2.sub; + return info2; + }; + this.listen = (id, callback, path = [], __internal = {}) => { + if (typeof path === "string") + path = path.split(this.options.keySeparator); + else if (typeof path === "symbol") + path = [path]; + const arrayPath = path; + let baseRef = this.get(id); + if (!baseRef) { + console.error(`Reference does not exist.`, id); + return; + } + if (!__internal.poll) + __internal.poll = esm(baseRef); + if (!__internal.seen) + __internal.seen = []; + const __internalComplete = __internal; + const thisPath = [id, ...arrayPath]; + const ref = this.get(thisPath); + const toMonitorInternally = (val, allowArrays = false) => { + const first = val && typeof val === "object"; + if (!first) + return false; + const isEl = val instanceof Element; + if (isEl) + return false; + if (allowArrays) + return true; + else + return !Array.isArray(val); + }; + let subs = {}; + const subscribeAll = toMonitorInternally(ref, true); + if (subscribeAll) { + if (ref.__esInspectable) + ref.__esInspectable.options.globalCallback = callback; + drillSimple(ref, (_, __, drillInfo) => { + if (drillInfo.pass) + return; + else { + const fullPath = [...arrayPath, ...drillInfo.path]; + const internalSubs = this.listen(id, callback, fullPath, __internalComplete); + Object.assign(subs, internalSubs); + } + }, { + condition: (_, val) => toMonitorInternally(val) + }); + } + let info2; + let success = false; + try { + info2 = this.getInfo(id, callback, arrayPath, ref); + if (info2) { + if (__internalComplete.poll) + success = this.poller.add(info2); + else { + let type = "setters"; + if (typeof ref === "function") + type = "functions"; + success = this.add(type, info2); + } + } + } catch (e) { + console.error("Fallback to polling:", path, e); + success = this.poller.add(info2); + } + if (success) { + subs[getPath("absolute", info2)] = info2.sub; + if (this.options.onInit instanceof Function) { + const executionInfo = {}; + for (let key in info2.infoToOutput) + executionInfo[key] = void 0; + this.options.onInit(getPath("output", info2), executionInfo); + } + return subs; + } else { + console.error("Failed to subscribe to:", path); + return; + } + }; + this.add = (type, info2) => { + if (listeners_exports[type]) + return listeners_exports[type](info2, this.listeners, this.listeners.lookup); + else { + this.listeners[type][getPath("absolute", info2)][info2.sub] = info2; + return true; + } + }; + this.remove = (subs) => { + if (!subs) { + subs = { + ...this.listeners.functions, + ...this.listeners.setters, + ...this.listeners.polling + }; + } + if (typeof subs !== "object") + subs = { sub: subs }; + for (let key in subs) { + let innerSub = subs[key]; + const handleUnsubscribe = (sub) => { + const res = this.unsubscribe(sub); + if (res === false) + console.warn(`Subscription for ${key} does not exist.`, sub); + }; + if (typeof innerSub !== "symbol") + iterateSymbols(innerSub, handleUnsubscribe); + else + handleUnsubscribe(innerSub); + } + return true; + }; + this.unsubscribe = (sub) => { + const info2 = this.listeners.lookup.symbol[sub]; + const absPath = info2.name; + const polling = this.poller.get(sub); + const funcs = this.listeners.functions[absPath]; + const func = funcs?.[sub]; + const setters2 = this.listeners.setters[absPath]; + const setter = setters2?.[sub]; + if (polling) + this.poller.remove(sub); + else if (func) { + delete funcs[sub]; + if (!Object.getOwnPropertySymbols(funcs).length) { + Object.defineProperty(func.parent, func.last, { + value: func.original, + writable: true + }); + delete this.listeners.functions[absPath]; + } + } else if (setter) { + delete setters2[sub]; + if (!Object.getOwnPropertySymbols(setters2).length) { + const parent = setter.parent; + if (parent) { + const last = setter.last; + const value = parent[last]; + Object.defineProperty(parent, last, { value, writable: true }); + } + delete this.listeners.setters[absPath]; + } + } else + return false; + delete this.listeners.lookup.symbol[sub]; + const nameLookup = this.listeners.lookup.name[info2.name]; + delete nameLookup[info2.id]; + if (!Object.getOwnPropertyNames(nameLookup).length) + delete this.listeners.lookup.name[info2.name]; + }; + Object.defineProperty(this.listeners, "lookup", { + value: createLookup(), + enumerable: false, + configurable: false + }); + Object.assign(this.options, opts); + this.poller.setOptions(opts.polling); + } +}; + +// src/index.ts +var src_default = Monitor; +export { + src_default as default +}; +//# sourceMappingURL=index.esm.js.map diff --git a/src/loaders/html/DOMElement.d.ts b/core/loaders/html/DOMElement.d.ts similarity index 97% rename from src/loaders/html/DOMElement.d.ts rename to core/loaders/html/DOMElement.d.ts index 19fddeb3..538004c8 100644 --- a/src/loaders/html/DOMElement.d.ts +++ b/core/loaders/html/DOMElement.d.ts @@ -1,6 +1,5 @@ //todo: make this the permanent version so I can stop copying manually each build -export function html(strings,...args): any; export function addCustomElement(cls: any, tag: any, extend?: any): void; export function randomId(tag?: string): string; export function parseFunctionFromText(method: any): any; diff --git a/src/loaders/html/DOMElement.js b/core/loaders/html/DOMElement.js similarity index 82% rename from src/loaders/html/DOMElement.js rename to core/loaders/html/DOMElement.js index b7761d33..e829101b 100644 --- a/src/loaders/html/DOMElement.js +++ b/core/loaders/html/DOMElement.js @@ -1,31 +1,41 @@ -import { html } from "./html"; -let dummy = html``; - -//from 'fragelement' on npm by Joshua Brewster (LGPL v3.0) +//from 'fragelement' on npm by Joshua Brewster (AGPL v3.0) export class DOMElement extends HTMLElement { - // template = function(self=this, props){ //return a string or html node - // return `
Custom Fragment Props: ${JSON.stringify(props)}
` - // }; //override the default template string by extending the class, or use options.template if calling the base class - // props = {}; + template = function(self=this, props){ //return a string or html node + return `
Custom Fragment Props: ${JSON.stringify(props)}
` + }; //override the default template string by extending the class, or use options.template if calling the base class + props = {}; useShadow = false; //can set to attach a shadow DOM instead (local styles) - // styles; //can set a style sheet which will toggle the shadow dom by default + styles; //can set a style sheet which will toggle the shadow dom by default // NOTE: Referencing this inside one of these events will give you the GraphNode - // oncreate; //(self,props) => {} fires on element creation (e.g. to set up logic) - // onresize; //(self,props) => {} fires on window resize - // ondelete; //(self,props) => {} fires after element is deleted - // onchanged; //(props) => {} fires when props change - //renderonchanged=false; //(self,props) => {} fires after rerendering on props change + oncreate; //(self,props) => {} fires on element creation (e.g. to set up logic) + onresize; //(self,props) => {} fires on window resize + ondelete; //(self,props) => {} fires after element is deleted + onchanged; //(props) => {} fires when props change + renderonchanged=false; //(self,props) => {} fires after rerendering on props change FRAGMENT; STYLE; attachedShadow = false; - static get tag(){return this.name.toLowerCase()+'-'} //tagName, default 'classname-'. Set as a static variable for the internal addElement to reference - obsAttributes=["props","options","onchanged","onresize","ondelete","oncreate","template"] - props = {}; + get observedAttributes() { + return this.obsAttributes; + } + + get obsAttributes() { + return this.obsAttributes; + } + + set obsAttributes(att) { + if(typeof att === 'string') { + this.obsAttributes.push(att); + } else if (Array.isArray(att)) this.obsAttributes=att; + } + + static get tag(){return this.name.toLowerCase()+'-'} //tagName, default 'classname-'. Set as a static variable for the internal addElement to reference + //add self or a specified class to the window which can be used via html like //will default be the classname with a '-' at the end if no tag supplied static addElement(tag=this.tag,cls=this,extend=undefined) { @@ -237,28 +247,20 @@ export class DOMElement extends HTMLElement { render = (props=this.props) => { - const t = document.createElement('template'); - - let usingHTMLFunction = this.template.prototype?.constructor?.name == dummy.prototype.constructor.name; - if(typeof this.template === 'function') { - if(usingHTMLFunction) { //html function - this.template(t.content); - } - else this.templateResult = this.template(this, props); - } //can pass a function + if(typeof this.template === 'function') this.templateResult = this.template(this, props); //can pass a function else this.templateResult = this.template; if(this.styles) this.templateResult = `${this.templateResult}`; //this.innerHTML = this.templateResult; - if(!usingHTMLFunction) { - if(typeof this.templateResult === 'string') t.innerHTML = this.templateResult; - else if(this.templateResult instanceof HTMLElement || this.templateResult instanceof DocumentFragment) { - if(this.templateResult.parentNode) { - this.templateResult.parentNode.removeChild(this.templateResult); //swap to the new component - } - t.content.appendChild(this.templateResult); + const t = document.createElement('template'); + + if(typeof this.templateResult === 'string') t.innerHTML = this.templateResult; + else if(this.templateResult instanceof HTMLElement) { + if(this.templateResult.parentNode) { + this.templateResult.parentNode.removeChild(this.templateResult); //swap to the new component } + t.appendChild(this.templateResult); } const fragment = t.content; @@ -357,6 +359,95 @@ export class DOMElement extends HTMLElement { } } + get props() { + return this.props; + } + + set props(newProps={}) { + this.setAttribute('props',newProps); + } + + get template() { + return this.template; + } + + set template(template) { + this.setAttribute('template',template); + } + + get render() { + return this.render; + } + + get delete() { + return this.delete; + } + + get state() { + return this.state; + } + + //past tense just so it can't conflict with onchange + get onchanged() { + return this.onchanged; + } + + set onchanged(onchanged) { + this.setAttribute('onchanged',onchanged); + } + + get styles() { + return this.styles + } + + set styles(templateStr) { + + this.styles = templateStr; + + if(this.querySelector('style')) { //get the top style + // if(!this.useShadow) { + // this.useShadow = true; + // this.render() + // } else + this.querySelector('style').innerHTML = templateStr; + + } else { + //this.useShadow = true; + this.render(); + } + } + + get renderonchanged() { + return this.renderonchanged; + } + + set renderonchanged(onchanged) { + this.setAttribute('renderonchanged',onchanged); + } + + get onresize() { + return this.props; + } + + set onresize(onresize) { + this.setAttribute('onresize',onresize); + } + + get ondelete() { + return this.props; + } + + set ondelete(ondelete) { + this.setAttribute('ondelete',ondelete); + } + + get oncreate() { + return this.oncreate; + } + + set oncreate(oncreate) { + this.setAttribute('oncreated',oncreate); + } } //extend the DOMElement class with an new name, this name determines the element name (always lower case in the html regardless of class name cases) diff --git a/core/loaders/html/html.loader.ts b/core/loaders/html/html.loader.ts new file mode 100644 index 00000000..ebb27ac9 --- /dev/null +++ b/core/loaders/html/html.loader.ts @@ -0,0 +1,155 @@ + +import {GraphNode, GraphNodeProperties,Graph} from '../../Graph2' +import {DOMElement} from './DOMElement' + + +export type HTMLNodeProperties = GraphNodeProperties & { + __props?:HTMLElement, + __onresize?:(elm:HTMLElement) => void, + __onremove?:(elm:HTMLElement) => void, + __onrender?:(elm:HTMLElement) => void, + tagName?:string, //can provide this instead of an element or html template string + parentNode?:string, //can define a specific parentNode, else a parent graph node with an HTMLElement as __props will be selected, else graph.parentNode if defined, else document.body + style?:Partial, //supply an object with style properties for this element's inline styles + //applies to custom webcomponent only: + __template?:string, + __renderonchanged?:(elm:HTMLElement) => void, + useShadow?:boolean, + __css?:string, //stylesheet template string for use with web components (just prepends a `; delete node.__css; + } + + if (node.__template) { + + if(typeof node.__renderonchanged === 'function') { + let renderonchanged = node.__renderonchanged; + node.__renderonchanged = (element:DOMElement) => { + renderonchanged.call((element as any).node, element); + } + } + + class CustomElement extends DOMElement { + props = node.props; + styles = node.__css; + useShadow = node.useShadow; + template = node.__template as any; + oncreate = node.__onrender; + onresize = node.__onresize; + ondelete = node.__onremove; + renderonchanged = node.__renderonchanged as any; + } + + if(node.__element) node.tagName = node.__element; + if(!node.tagName) node.tagName = `element${Math.floor(Math.random()*1000000000000000)}-`; + + CustomElement.addElement(node.tagName); + + node.__props = document.createElement(node.tagName); + node.__props.node = node; + + let keys = Object.getOwnPropertyNames(properties); + for(const k of keys) { + if(k === 'style' && typeof properties[k] === 'object') {Object.assign(node.__props.style,properties[k]);} + else node.__props[k] = properties[k]; + } + + } else if(node.__props instanceof HTMLElement) { + + if(node.__onresize) + window.addEventListener('resize', node.__onresize as EventListener); + + } + + if(node.__attributes && node.__props instanceof HTMLElement) { + for(const k in node.__attributes) { + if(k === 'style' && typeof node.__attribute[k] === 'object') {Object.assign(node.__props.style,node.__attribute[k]);} + node.__props[k] = node.__attributes[k]; + } + } + + if(node.__props instanceof HTMLElement) { + node.__props.id = key; + + node.__addOnconnected((n) => { + if(n.__props.parentNode) (n.__props as HTMLElement).remove(); + if(n.parentNode) { + if(typeof n.parentNode === 'string' && document.getElementById(n.parentNode)) document.getElementById(n.parentNode).appendChild(n.__props); + else if (n.parentNode instanceof HTMLElement) n.parentNode.appendChild(n.__props); + } else if(parent.__props instanceof HTMLElement) { + parent.__props.appendChild(node.__props); + } else if (typeof graph.parentNode === 'string' && document.getElementById(n.parentNode)) { + document.getElementById(n.parentNode).appendChild(graph.__props); + } else if(graph.parentNode instanceof HTMLElement) { + graph.parentNode.appendChild(node.__props); + } else if(!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement)) document.body.appendChild(node.__props); + + //add slight delay for sizing etc to kick in correctly + if(node.__onrender && !node.__template) setTimeout(()=>{node.__onrender(node.__props)},0.01); + + }); + + node.__addOndisconnected((n) => { + (n.__props as HTMLElement).remove(); + + if(typeof n.__onremove === 'function') { + n.__onremove(n.__props) + } + + if(n.__onresize) { + window.removeEventListener('resize', n.__onresize); + } + }); + } + + +} \ No newline at end of file diff --git a/src/loaders/index.ts b/core/loaders/index.ts similarity index 63% rename from src/loaders/index.ts rename to core/loaders/index.ts index 16b4a0c3..6a78279e 100644 --- a/src/loaders/index.ts +++ b/core/loaders/index.ts @@ -1,4 +1,4 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; +import { GraphNode, Graph, GraphNodeProperties } from "../Graph2"; //loaders are triggered just after graphnode creation, after oncreate() is called @@ -7,14 +7,7 @@ import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; */ export const backprop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { - if(node.__node.backward && parent instanceof GraphNode) { - - graph.setListeners({ - [parent.__node.tag]:{ - [node.__node.tag]:parent - } - }) - } + if(node.__node.backward && parent instanceof GraphNode) graph.subscribe(parent.__node.tag, node.__node.tag) } @@ -34,34 +27,43 @@ export const backprop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { * * */ + + +// NOTE (GF): Must return something to propagate changes through the graph export const loop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph)=>{ - if( - node.__operator - //&& !node.__node.looperSet //not using this allows multiple loops to run, just set looping=false and wait for all to finish otherwise - ) { - let loopId = Math.random(); - if(!node.__node.loops) node.__node.loops = {}; + + + if(node.__operator && !node.__node.looperSet) { + + node.__node.looperSet = true; if(typeof node.__node.delay === 'number') { let fn = node.__operator; - node.__setOperator((...args:any[]) => { + const delay = (...args:any[]) => { + return new Promise((res,rej) => { - node.__node.loops[loopId] = setTimeout(async ()=>{ + setTimeout(async ()=>{ res(await fn(...args));},node.__node.delay); }); - }); + } + node.__operator = delay; + } else if (node.__node.frame === true) { let fn = node.__operator; - node.__setOperator((...args:any[]) => { + const frame = (...args:any[]) => { return new Promise((res,rej) => { - node.__node.loops[loopId] = requestAnimationFrame(async ()=>{res(await fn(...args));}); + requestAnimationFrame(async ()=>{res(await fn(...args));}); }); - }); + } + + node.__operator = frame; + } if(typeof node.__node.repeat === 'number' || typeof node.__node.recursive === 'number') { let fn = node.__operator; - node.__setOperator(async (...args:any[]) => { + const repeat = async (...args:any[]) => { + let i = node.__node.repeat ? node.__node.repeat : node.__node.recursive; let result; let repeater = async (tick,...inp:any[]) => { @@ -81,41 +83,34 @@ export const loop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph)=>{ } await repeater(i,...args); return result; - }); + } + + node.__operator = repeat } + if(node.__node.loop && typeof node.__node.loop === 'number') { - - //node.__node.looperSet = true; - let fn = node.__operator; - let time = node.__node.loop; - node.__setOperator((...args) => { + + let ogFunction = node.__operator; + const looper = function (...args) { if(!('looping' in node.__node)) node.__node.looping = true; if(node.__node.looping) { - let last = performance.now(); - fn(...args); - node.__node.loops[loopId] = setTimeout( - ()=>{ - let now = performance.now(); - let overshoot = (now - last) - node.__node.loop; - if(overshoot > 0) time = node.__node.loop - overshoot; - else time = node.__node.loop; - if(time <= 0) time = node.__node.loop; - node.__operator(...args); - // - }, - time - ); + const res = ogFunction.call(node, ...args); + setTimeout(()=> { + node.__operator(...args) + },node.__node.loop); + return res } - }); - if(node.__node.looping) node.__operator(); + } + + node.__operator = looper + + node.__addOnconnected((node) => { + if (node.__node.looping) node.__operator(); + }) let ondelete = (node) => { if(node.__node.looping) node.__node.looping = false; - if(node.__node.loops[loopId]) { - clearTimeout(node.__node.loops[loopId]); - cancelAnimationFrame(node.__node.loops[loopId]); - } } node.__addOndisconnected(ondelete); @@ -135,65 +130,63 @@ export const loop = (node:GraphNode,parent:GraphNode|Graph,graph:Graph)=>{ */ export const animate = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { if(node.__node.animate === true || node.__animation) { - let fn = node.__operator; + let fn = node.__operator; + + const animate = (...args) => { - node.__setOperator((...args) => { - if(!('animating' in node.__node)) node.__node.animating = true; - if(node.__node.animating) { - if(typeof node.__animation === 'function') node.__animation(...args); - else fn(...args); - node.__node.animationFrame = requestAnimationFrame(()=>{node.__operator(...args);}); + if(!('animating' in node.__node)) node. + __node.animating = true; + if(node.__node.animating) { + if(typeof node.__animation === 'function') node.__animation(...args); + else fn.call(node, ...args); + requestAnimationFrame(()=>{node.__operator(...args);}); + } + + return true } - }); - if(node.__node.animating || ((!('animating' in node.__node) || node.__node.animating) && node.__animation)) - setTimeout(()=>{ - node.__node.animationFrame = requestAnimationFrame(node.__operator) - },10); - - let ondelete = (node) => { - if(node.__node.animating) node.__node.animating = false; - if(node.__node.animationFrame) cancelAnimationFrame(node.__node.animationFrame); - } + node.__operator = animate; - node.__addOndisconnected(ondelete); + node.__addOnconnected((node) => { + if(node.__node.animating || ((!('animating' in node.__node) || node.__node.animating) && node.__animation)) setTimeout(()=>{requestAnimationFrame(node.__operator)},10); + }) + + node.__addOndisconnected((node) => { + if(node.__node.animating) node.__node.animating = false; + }); } } /** Branching operations * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} * * nodeA.__listeners['nodeB.x'] = { * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } + * branch:{if:Function|any, then:Function|any|GraphNode} * } * */ export const branching = (node:GraphNode,parent:GraphNode|Graph,graph:Graph) => { - if(typeof node.__branch === 'object' && node.__operator && !node.__branchApplied) { + if(typeof node.__node.branch === 'object' && node.__operator && !node.__node.branchApplied) { let fn = node.__operator; - node.__branchApplied = true; + node.__node.branchApplied = true; node.__operator = ((...args:any[]) => { let result = fn(...args); - for(const key in node.__branch) { //run branching operations + for(const key in node.__node.branch) { //run branching operations let triggered = () => { - if(typeof node.__branch[key].then === 'function') { - node.__branch[key].then(result); //trigger a callback - } else if(node.__branch[key].then instanceof GraphNode && node.__branch[key].then.__operator) { - node.__branch[key].then.__operator(result); //run a node - } else result = node.__branch[key].then; //just replace the result in this case + if(typeof node.__node.branch[key].then === 'function') { + node.__node.branch[key].then(result); //trigger a callback + } else if(node.__node.branch[key].then instanceof GraphNode && node.__node.branch[key].then.__operator) { + node.__node.branch[key].then.__operator(result); //run a node + } else result = node.__node.branch[key].then; //just replace the result in this case } - if(typeof node.__branch[key].if === 'function') { - if(node.__branch[key].if(result) == true) { + if(typeof node.__node.branch[key].if === 'function') { + if(node.__node.branch[key].if(result)) { triggered(); } - } else if(node.__branch[key].if === result) { + } else if(node.__node.branch[key].if === result) { triggered(); } } @@ -247,7 +240,7 @@ export const triggerListenerOncreate = (node:GraphNode,parent:GraphNode|Graph,gr } } -/** Bind listeners to a specific object instead of the node that owns it +/** Trigger listeners oncreate with specific arguments * * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } * @@ -291,12 +284,16 @@ export const transformListenerResult = (node:GraphNode,parent:GraphNode|Graph,gr export const substitute__operator = (node:GraphNode & GraphNodeProperties, parent:GraphNode|Graph,graph:Graph) => { //console.log('route', r) if(node.post && !node.__operator) { - node.__setOperator(node.post); - } else if (!node.__operator && typeof node.get == 'function') { - node.__setOperator(node.get); + node.__operator = node.post + } + + else if (!node.__operator && typeof node.get == 'function') { + node.__operator = node.get } if(!node.get && node.__operator) { - //node.get = node.__operator; - } if(node.aliases) { + node.get = node.__operator; + } + + if(node.aliases) { node.aliases.forEach((a) => { graph.set(a,node); let ondelete = (node) => { @@ -306,7 +303,7 @@ export const substitute__operator = (node:GraphNode & GraphNodeProperties, paren node.__addOndisconnected(ondelete); }) } - if(typeof graph.__node.roots?.[node.__node.tag] === 'object' && node.get) graph.__node.roots[node.__node.tag].get = node.get; + if(typeof graph.__node.tree[node.__node.tag] === 'object' && node.get) graph.__node.tree[node.__node.tag].get = node.get; } //standard loaders with flow logic for operators and listeners diff --git a/core/loaders/props/props.loader.ts b/core/loaders/props/props.loader.ts new file mode 100644 index 00000000..3d14278b --- /dev/null +++ b/core/loaders/props/props.loader.ts @@ -0,0 +1,7 @@ +import { Graph, GraphNode, GraphNodeProperties } from "../../Graph2" + +export default ( + node:GraphNode, +) => { + if (node.__properties.__props) node.____apply(node.__properties.__props, true) +} \ No newline at end of file diff --git a/core/utils/EventHandler.ts b/core/utils/EventHandler.ts new file mode 100644 index 00000000..a4b8425f --- /dev/null +++ b/core/utils/EventHandler.ts @@ -0,0 +1,73 @@ +//mini state event handler for arbitrary data event callback handling +//Graph.ts has its own copy of this + +//a graph representing a callstack of nodes which can be arranged arbitrarily with forward and backprop or propagation to wherever +export class EventHandler { + + pushToState={} + data={} + triggers={} + + constructor(data?:{[key:string]:any}) { if(typeof data === 'object') this.data = data; } + + setState = (updateObj:{[key:string]:any}) => { + Object.assign(this.data, updateObj); + for (const prop of Object.getOwnPropertyNames(updateObj)) { + if (this.triggers[prop]) this.triggers[prop].forEach((obj) => obj.onchange(this.data[prop])); + } + return this.data; + } + setValue = (key, value) => { + this.data[key] = value; + if(this.triggers[key]) this.triggers[key].forEach((obj) => obj.onchange(this.data[key])); + } + subscribeTrigger = (key:string,onchange:(res:any)=>void) => { + + if(key) { + if(!this.triggers[key]) { + this.triggers[key] = []; + } + let l = this.triggers[key].length; + + this.triggers[key].push({sub:l, onchange}); + return this.triggers[key].length-1; + } else return undefined; + } + unsubscribeTrigger = (key:string,sub?:number) => { + let triggers = this.triggers[key] + if (triggers){ + if(!sub) delete this.triggers[key]; + else { + let sub = undefined; + let obj = triggers.find((o,i)=>{ + if(o.sub===sub) { + sub = i; + return true; + } + }); + + if(obj) triggers.splice(sub,1); + + if(this.onRemoved) this.onRemoved(obj); + return true; + } + } + } + subscribeTriggerOnce = (key:string,onchange:(res:any)=>void) => { + let sub; + + let changed = (value) => { + onchange(value); + this.unsubscribeTrigger(key,sub); + } + sub = this.subscribeTrigger(key,changed); + } + getTrigger = (key,sub) => { + for(const s in this.triggers[key]) { + if(this.triggers[key][s].sub === sub) return this.triggers[key][s]; + } + } + onRemoved; +} + + diff --git a/_old/FunctionTree.ts b/core/utils/FunctionTree.ts similarity index 80% rename from _old/FunctionTree.ts rename to core/utils/FunctionTree.ts index 31fd577f..4bfbd577 100644 --- a/_old/FunctionTree.ts +++ b/core/utils/FunctionTree.ts @@ -1,4 +1,4 @@ -import { EventHandler } from "../services/EventHandler"; +import { EventHandler } from "./EventHandler"; export type FunctionNode = { @@ -27,8 +27,8 @@ export class FunctionTree { if(options.state) this.state = options.state; } - load = ( - roots:FunctionTreeProps, + setTree = ( + tree:FunctionTreeProps, transform?:(node:FunctionNode, key:string, parent:{[key:string]:FunctionNode|Function}|FunctionNode,tree:FunctionTreeProps)=>Function|FunctionNode //we could run a callback with each route (or a callback that calls a series of callbacks :P) for additional setup powers ) => { const setRoute = (rt:any,key:string,parent:{[key:string]:FunctionNode|Function}|FunctionNode) => { @@ -45,7 +45,7 @@ export class FunctionTree { rt.tag = parent.tag+'.'+key; } if(transform) { - let r = transform(rt,key,parent,roots); //run some callback on the route + let r = transform(rt,key,parent,tree); //run some callback on the route if(r) rt = r; //can replace the route if it returns something } this.nodes.set(rt.tag,rt); @@ -54,7 +54,7 @@ export class FunctionTree { } else { if(transform) { - let r = transform(rt,key,parent,roots); //run some callback on the route + let r = transform(rt,key,parent,tree); //run some callback on the route if(r) rt = r; //can replace the route if it returns something } @@ -68,14 +68,14 @@ export class FunctionTree { } } if(typeof rt === 'object') { - if(typeof rt.__operator === 'string') { - rt.__operator = this.nodes.get(rt.operator); - if(typeof rt.__operater === 'object') rt.__operator = rt.__operator.__operator; - } if(typeof rt.__operator === 'function') { - rt.__operator.bind(rt); //bind non-arrow functions to the object's 'this' context + if(typeof rt.operator === 'string') { + rt.operator = this.nodes.get(rt.operator); + if(typeof rt.operater === 'object') rt.operator = rt.operator.operator; + } if(typeof rt.operator === 'function') { + rt.operator.bind(rt); //bind non-arrow functions to the object's 'this' context if(!rt.tag) { - if(typeof parent.tag === 'string') rt.tag = parent.tag+'.'+(rt.__operator as Function).name; - else rt.tag = (rt.__operator as Function).name; + if(typeof parent.tag === 'string') rt.tag = parent.tag+'.'+(rt.operator as Function).name; + else rt.tag = (rt.operator as Function).name; } } else if(rt.tag) { @@ -87,7 +87,7 @@ export class FunctionTree { else rt.tag = key; } - if(typeof rt?.__children === 'object') { + if(typeof rt?.children === 'object') { for(const key in rt.children) { setRoute(rt.children[key],key,parent); } @@ -98,8 +98,8 @@ export class FunctionTree { } } - for(const nm in roots) { - setRoute(roots[nm],nm,roots); + for(const nm in tree) { + setRoute(tree[nm],nm,tree); } } @@ -135,18 +135,18 @@ export class FunctionTree { else return r; } } else if(typeof fn === 'object') { - if(typeof fn?.__operator === 'function') { - let r = fn.__operator(...args); + if(typeof fn?.operator === 'function') { + let r = fn.operator(...args); if(r instanceof Promise) { return new Promise((res) => { r.then((rr) => { - if((fn as FunctionNode).__children) { - for(const key in (fn as FunctionNode).__children) { - this.run(((fn as FunctionNode).__children as any)[key] as Function|FunctionNode, rr); + if((fn as FunctionNode).children) { + for(const key in (fn as FunctionNode).children) { + this.run(((fn as FunctionNode).children as any)[key] as Function|FunctionNode, rr); } } if(this.state && (fn as FunctionNode).tag) {this.state.setState({[(fn as FunctionNode).tag]:rr})} - else if(this.state && ((fn as FunctionNode)._operator as Function).name) {this.state.setState({[((fn as FunctionNode).__operator as Function).name]:rr})} + else if(this.state && ((fn as FunctionNode).operator as Function).name) {this.state.setState({[((fn as FunctionNode).operator as Function).name]:rr})} if(this._returnServiceMessage) res({route:(fn as Function).name, args:rr}); else res(rr); @@ -154,15 +154,15 @@ export class FunctionTree { }); } else { - if(fn.__children) { - for(const key in fn.__children) { - this.run(fn.__children[key] as Function|FunctionNode, r); + if(fn.children) { + for(const key in fn.children) { + this.run(fn.children[key] as Function|FunctionNode, r); } if(this.state && (fn as FunctionNode).tag) {this.state.setState({[(fn as FunctionNode).tag]:r});} - else if(this.state && ((fn as FunctionNode).__operator as Function).name) {this.state.setState({[((fn as FunctionNode).__operator as Function).name]:r});} + else if(this.state && ((fn as FunctionNode).operator as Function).name) {this.state.setState({[((fn as FunctionNode).operator as Function).name]:r});} } } - if(this._returnServiceMessage) return {route:fn.__operator.name, args:r}; + if(this._returnServiceMessage) return {route:fn.operator.name, args:r}; return r; } } @@ -171,14 +171,14 @@ export class FunctionTree { subscribe = (node:string,callback:(res:any)=>void|string) => { if(!this.state) return; if(typeof callback === 'string' && this.nodes.get(callback)) { - return this.state.subscribeEvent(node, (r)=>{ this.run(callback,r); }) + return this.state.subscribeTrigger(node, (r)=>{ this.run(callback,r); }) } - else if(typeof callback === 'function') return this.state.subscribeEvent(node,callback); + else if(typeof callback === 'function') return this.state.subscribeTrigger(node,callback); } unsubscribe =(node:string,sub:number) => { if(!this.state) return; - this.state.unsubscribeEvent(node,sub); + this.state.unsubscribeTrigger(node,sub); } } @@ -191,8 +191,8 @@ let t = new FunctionTree({ 'add':(a=3,b=2)=>{return a+b;} 'multiply':(a=3,b=2)=>{return a*b}, 'sequence:{ - __operator:'multiply', - __children:{ + operator:'multiply', + children:{ 'add':true } } diff --git a/dist/Graph.d.ts b/dist/Graph.d.ts new file mode 100644 index 00000000..8128de4d --- /dev/null +++ b/dist/Graph.d.ts @@ -0,0 +1,108 @@ +import { EventHandler } from "./services/EventHandler"; +export declare const state: EventHandler; +export declare type GraphNodeProperties = { + __props?: Function | GraphNodeProperties; + __operator?: ((...args: any[]) => any) | string; + __children?: { + [key: string]: GraphNodeProperties; + }; + __listeners?: { + [key: string]: true | string | ((result: any) => void) | { + __callback: string | ((result: any) => void) | true; + subInput?: boolean; + [key: string]: any; + }; + } | { + [key: string]: ((result: any) => void) | true | string; + }; + __onconnected?: ((node: any) => void | ((node: any) => void)[]); + __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); + __node?: { + tag?: string; + state?: EventHandler; + inputState?: boolean; + [key: string]: any; + }; + [key: string]: any; +}; +export declare type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, tree: any, properties: GraphNodeProperties, key: string) => void; +export declare type GraphOptions = { + tree?: { + [key: string]: any; + }; + loaders?: { + [key: string]: Loader | { + init?: Loader; + connected?: (node: any) => void; + disconnected?: (node: any) => void; + }; + }; + state?: EventHandler; + mapGraphs?: false; + [key: string]: any; +}; +export declare class GraphNode { + __node: { + [key: string]: any; + }; + __children?: any; + __operator?: any; + __listeners?: any; + __props?: any; + [key: string]: any; + constructor(properties: any, parent?: { + [key: string]: any; + }, graph?: Graph); + __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, bound?: string, target?: string) => any; + __unsubscribe: (sub?: number, key?: string, subInput?: boolean) => any; + __setOperator: (fn: (...args: any[]) => any) => any; + __addLocalState(props?: { + [key: string]: any; + }): void; + __proxyObject: (obj: any) => void; + __addOnconnected(callback: (node: any) => void): void; + __addOndisconnected(callback: (node: any) => void): void; + __callConnected(node?: this): void; + __callDisconnected(node?: this): void; +} +export declare class Graph { + [key: string]: any; + __node: { + tag: string; + state: EventHandler; + nodes: Map; + [key: string]: any; + }; + constructor(options?: GraphOptions); + init: (options: GraphOptions) => void; + setTree: (tree: { + [key: string]: any; + }) => { + [key: string]: any; + }; + setLoaders: (loaders: { + [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, tree: any, props: any, key: string) => void; + }, replace?: boolean) => any; + add: (properties: any, parent?: GraphNode | string) => any; + recursiveSet: (t: any, parent: any, listeners: {}, origin: any) => {}; + remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; + run: (node: string | GraphNode, ...args: any[]) => any; + setListeners: (listeners: { + [key: string]: { + [key: string]: any; + }; + }) => void; + clearListeners: (node: GraphNode | string, listener?: string) => void; + get: (tag: string) => any; + set: (tag: string, node: GraphNode) => Map; + delete: (tag: string) => boolean; + getProps: (node: GraphNode | string, getInitial?: boolean) => void; + subscribe: (node: GraphNode | string, callback: string | GraphNode | ((res: any) => void), key?: string | undefined, subInput?: boolean, target?: string, bound?: string) => any; + unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; + setState: (update: { + [key: string]: any; + }) => void; +} +export declare function getAllProperties(obj: any): any[]; +export declare function instanceObject(obj: any): {}; +export declare function isNativeClass(thing: any): boolean; diff --git a/src/extras/dist/loaders/index.d.ts b/dist/Loaders.d.ts similarity index 78% rename from src/extras/dist/loaders/index.d.ts rename to dist/Loaders.d.ts index 229b9ec7..c91cf5c1 100644 --- a/src/extras/dist/loaders/index.d.ts +++ b/dist/Loaders.d.ts @@ -1,4 +1,4 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; +import { GraphNode, Graph, GraphNodeProperties } from "./Graph"; /** * setting nodeA.__node.backward:true propagates operator results to parent */ @@ -21,25 +21,17 @@ export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, grap export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; /** Animations * - * nodeA.__node.animate = true; - * then __operator becomes a requestAnimationFrame function - * start with a call the __operator or by setting node.__node.animating = true; - * - * or node.__animation = (...args) => {} + * nodeA.__node.animate = true | () => void, to run the operator or a specified animation function on loop * */ export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; /** Branching operations * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} * * nodeA.__listeners['nodeB.x'] = { * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } + * branch:{if:Function|any, then:Function|any|GraphNode} * } * */ @@ -50,7 +42,7 @@ export declare const branching: (node: GraphNode, parent: GraphNode | Graph, gra * */ export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Bind listeners to a specific object instead of the node that owns it +/** Trigger listeners oncreate with specific arguments * * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } * diff --git a/dist/index.core.d.ts b/dist/index.core.d.ts index b1cd8270..af2f3371 100644 --- a/dist/index.core.d.ts +++ b/dist/index.core.d.ts @@ -1,3 +1,2 @@ -export * from './src/core/Graph'; -export * from './src/core/EventHandler'; -export * from './src/loaders'; +export * from './Graph'; +export * from './loaders'; diff --git a/dist/index.core.esm.js b/dist/index.core.esm.js index d8e31763..6a057244 100644 --- a/dist/index.core.esm.js +++ b/dist/index.core.esm.js @@ -1 +1 @@ -var x=class{data={};triggers={};ctr=0;constructor(e){typeof e=="object"&&(this.data=e)}setState=e=>{Object.assign(this.data,e);let t=Object.getOwnPropertyNames(e);for(let n of t)this.triggerEvent(n,this.data[n]);if(this.triggers[G]){let n=s=>{s(e)},i=this.triggers[G].length;for(let s=i-1;s>=0;s--)n(this.triggers[G][s].onchange)}return this.data};setValue=(e,t)=>{this.data[e]=t,this.triggerEvent(e,t)};triggerEvent=(e,t)=>{if(this.triggers[e]){let n=s=>{s.onchange(t)},i=this.triggers[e].length;for(let s=i-1;s>=0;s--)n(this.triggers[e][s])}};subscribeState=e=>this.subscribeEvent(G,e);unsubscribeState=e=>this.unsubscribeEvent(G,e);subscribeEvent=(e,t,n,i)=>{if(e){n&&i&&!this.triggers[e]&&Object.defineProperty(this.data,e,{get:()=>n[i],set:r=>{n[i]=r},enumerable:!0,configurable:!0}),this.triggers[e]||(this.triggers[e]=[]);let s=this.ctr;return this.ctr++,this.triggers[e].push({sub:s,onchange:t}),s}else return};unsubscribeEvent=(e,t)=>{let n=this.triggers[e];if(n)if(t===void 0)delete this.triggers[e],delete this.data[e];else{let i,s=n.find((r,o)=>{if(r.sub===t)return i=o,!0});return s&&n.splice(i,1),Object.keys(n).length===0&&(delete this.triggers[e],delete this.data[e]),this.onRemoved&&this.onRemoved(s),!0}};subscribeEventOnce=(e,t)=>{let n,i=s=>{t(s),this.unsubscribeEvent(e,n)};return n=this.subscribeEvent(e,i),n};getEvent=(e,t)=>{if(typeof t!="number")return this.triggers[e];for(let n in this.triggers[e])if(this.triggers[e][n].sub===t)return this.triggers[e][n]};getSnapshot=()=>{let e={};for(let t in this.data)e[t]=this.data[t]};onRemoved},G="*s";var F=new x,w=class extends Function{__bound;__call;constructor(){return super("return this.__bound.__call.apply(this.__bound, arguments)"),this.__bound=this.bind(this),this.__bound}},p=class _{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state:F};__children;__parent;__operator;__listeners;__props;__args;constructor(e,t,n){if(this.__setProperties(e,t,n),typeof e=="function"||e?.__callable){let i=new w;i.__call=(...r)=>this.__operator(...r);let s=new Proxy(i,{get:(r,o,l)=>Reflect.has(this,o)?Reflect.get(this,o,l):Reflect.get(r,o,l),set:(r,o,l,f)=>Reflect.has(this,o)?Reflect.set(this,o,l,f):Reflect.set(r,o,l,f)});return Object.setPrototypeOf(s,this),s}}get __graph(){return this.__node?.graph}set __graph(e){this.__node.graph=e}__setProperties=(e,t,n)=>{if((()=>{let s=e;typeof e=="function"?P(e)?e=new e:e={__operator:e,__node:{forward:!0,tag:e.name}}:typeof e=="string"&&n?.get(e)&&(e=n.get(e)),"__node"in e||(e.__node={}),e.__node.initial||(e.__node.initial=s)})(),typeof e=="object"){let s=()=>{e.__node?.state?this.__node.state=e.__node.state:n&&(e.__node.state=n.__node.state)},r=()=>{e.__props&&(typeof e.__props=="function"&&(e.__props=new e.__props),typeof e.__props=="object"&&this.__proxyObject(e.__props))},o=()=>{e.__node.tag||(e.__operator?.name?e.__node.tag=e.__operator.name:e.__node.tag=`node${Math.floor(Math.random()*1e15)}`)},l=()=>{typeof e.__node=="string"?n?.get(e.__node.tag)?e=n.get(e.__node.tag):e.__node={}:e.__node||(e.__node={}),n&&(e.__node.graph=n),e instanceof y&&(e.__node.source=e)},f=()=>{if(!e.__parent&&t&&(e.__parent=t),t?.__node&&!(t instanceof y||e instanceof y)&&(e.__node.tag=t.__node.tag+"."+e.__node.tag),t instanceof y&&e instanceof y&&(e.__node.loaders&&Object.assign(t.__node.loaders?t.__node.loaders:{},e.__node.loaders),t.__node.mapGraphs)){e.__node.nodes.forEach(h=>{t.set(e.__node.tag+"."+h.__node.tag,h)});let u=()=>{e.__node.nodes.forEach(h=>{t.__node.nodes.delete(e.__node.tag+"."+h.__node.tag)})};this.__addOndisconnected(u)}},a=()=>{if(typeof e.default=="function"&&!e.__operator&&(e.__operator=e.default),e.__operator){if(typeof e.__operator=="string"&&n){let u=n.get(e.__operator);u&&(e.__operator=u.__operator),!e.__node.tag&&e.__operator.name&&(e.__node.tag=e.__operator.name)}typeof e.__operator=="function"&&(e.__operator=this.__setOperator(e.__operator)),e.default&&(e.default=e.__operator)}},d=()=>{e.__node=Object.assign(this.__node,e.__node);let u=Object.getOwnPropertyNames(e).filter(h=>{if(!O[h])return!0});for(let h of u)h in e&&h!=="name"&&(this[h]=e[h])},c=()=>{this.__onconnected&&(typeof this.__onconnected=="function"?this.__onconnected=this.__onconnected.bind(this):Array.isArray(this.__onconnected)&&(this.__onconnected=this.__onconnected.map(u=>u.bind(this))),typeof this.__ondisconnected=="function"?this.__ondisconnected=this.__ondisconnected.bind(this):Array.isArray(this.__ondisconnected)&&(this.__ondisconnected=this.__ondisconnected.map(u=>u.bind(this))))};s(),o(),r(),l(),f(),d(),c(),a()}};__subscribe=(e,t,n,i,s,r,o)=>{let l=(a,d=(u,h)=>h||u,c=e)=>{let u;if(r){let b=A(c,r,this.__node.graph);c=b.__callback,u=b.__args}let h=this.__node.state.subscribeEvent(a,c,this,t),g=this.__node.state.getEvent(a,h);return this.__listeners||(this.__listeners={}),this.__listeners[a]=this.__node.state.triggers[a],g&&(g.source=this.__node.tag,t&&(g.key=t),g.target=d(e,i),s&&(g.tkey=s),n&&(g.subInput=n),r&&(g.arguments=u,g.__args=r),o&&(g.__callback=o),g.node=this,g.graph=this.__node.graph),h},f=a=>{let d=this.__node.graph.get(a);if(!d&&a.includes(".")){i=a.substring(0,a.lastIndexOf("."));let c=this.__node.graph.get(a.substring(0,i));s=a.lastIndexOf(".")+1,c&&typeof c[t]=="function"&&(a=(...u)=>c[s](...u))}else d.__operator&&(a=d.__operator,s="__operator");return a};if(t){if((!this.__node.localState||!this.__node.localState[t])&&this.__addLocalState(this,t),typeof e=="string"){if(o=this.__node.tag+"."+e,s=e,i){if(this.__node.graph?.get(i)){let c=this.__node.graph?.get(i);if(typeof c[e]=="function"){let u=c[e];e=(...h)=>{u(...h)}}else{let u=e;e=g=>{c[u]=g}}}}else if(typeof this[e]=="function"){let c=this[e];e=(...u)=>{c(...u)}}else this.__node.graph?.get(e)&&(e=f(e));if(typeof e!="function")return}let a,d=n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}else{if(typeof e=="string"&&(o=e,i||(i=e),this.__node.graph.get(e)&&(e=this.__node.graph.get(e)),s="__operator",typeof e!="object"))return;let a,d=n?this.__node.unique+"input":this.__node.unique;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}};__unsubscribe=(e,t,n)=>t?this.__node.state.unsubscribeEvent(n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t,e):this.__node.state.unsubscribeEvent(n?this.__node.unique+"input":this.__node.unique,e);__setOperator=e=>{e=e.bind(this),this.__args&&this.__node.graph&&(e=A(e,this.__args,this.__node.graph).__callback);let t=`${this.__node.unique}input`;if(this.__operator=(...n)=>{this.__node.state.triggers[t]&&this.__node.state.setValue(t,n);let i=e(...n);return this.__node.state.triggers[this.__node.unique]&&(typeof i?.then=="function"?i.then(s=>{s!==void 0&&this.__node.state.setValue(this.__node.unique,s)}).catch(console.error):i!==void 0&&this.__node.state.setValue(this.__node.unique,i)),i},this.__parent instanceof _&&!this.__subscribedToParent&&this.__parent.__operator){let n=this.__parent.__subscribe(this),i=()=>{this.__parent?.__unsubscribe(n),delete this.__subscribedToParent};this.__addOndisconnected(i),this.__subscribedToParent=!0}return this.__operator};__addLocalState=(e,t)=>{if(!e)return;this.__node.localState||(this.__node.localState={});let n=this.__node.localState,i=(s,r)=>{let o=this.__node.unique+"."+r,l=`${o}input`,f,a,d,c;if(typeof s[r]=="function"&&r!=="__operator")this.__props?.[r]?d=this.__props:d=n,f=()=>d[r],a=u=>{this.__props?.[r]||(u=u.bind(this)),d[r]=(...h)=>{this.__node.state.triggers[l]&&this.__node.state.setValue(l,h);let g=u(...h);return this.__node.state.triggers[o]&&(typeof g?.then=="function"?g.then(b=>{this.__node.state.triggerEvent(o,b)}).catch(console.error):this.__node.state.triggerEvent(o,g)),g}},n[r]=s[r].bind(this),c={get:f,set:a,enumerable:!0,configurable:!0};else if(r!=="__graph"){let u,h,g;this.__props?.[r]?g=this.__props:g=n,u=()=>g[r],h=b=>{g[r]=b,this.__node.state.triggers[o]&&this.__node.state.triggerEvent(o,b)},n[r]=s[r],c={get:u,set:h,enumerable:!0,configurable:!0}}if(Object.defineProperty(s,r,c),typeof this.__node.initial=="object"){let u=Object.getOwnPropertyDescriptor(this.__node.initial,r);(u===void 0||u?.configurable)&&Object.defineProperty(this.__node.initial,r,c)}};if(t)i(e,t);else for(let s in e)i(e,s)};__proxyObject=e=>{let t=q(e);for(let n of t){let i={get:()=>e[n],set:s=>{e[n]=s},enumerable:!0,configurable:!0};if(Object.defineProperty(this,n,i),typeof this.__node.initial=="object"){let s=Object.getOwnPropertyDescriptor(this.__node.initial,n);(s===void 0||s?.configurable)&&Object.defineProperty(this.__node.initial,n,i)}}};__addOnconnected(e){e=e.bind(this),Array.isArray(this.__onconnected)?this.__onconnected.push(e):typeof this.__onconnected=="function"?this.__onconnected=[e,this.__onconnected]:this.__onconnected=e}__addOndisconnected(e){e=e.bind(this),Array.isArray(this.__ondisconnected)?this.__ondisconnected.push(e):typeof this.__ondisconnected=="function"?this.__ondisconnected=[e,this.__ondisconnected]:this.__ondisconnected=e}__callConnected(e=this){if(typeof this.__onconnected=="function")this.__onconnected(this);else if(Array.isArray(this.__onconnected)){let t=n=>{n(this)};this.__onconnected.forEach(t)}}__callDisconnected(e=this){if(typeof this.__ondisconnected=="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let t=n=>{n(this)};this.__ondisconnected.forEach(t)}}},y=class _{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state:F,roots:{}};constructor(e){this.init(e)}init=e=>{if(e){let t=Object.assign({},e);delete t.roots,N(this.__node,t),e.roots&&this.load(e.roots)}};load=(e,t=!1)=>{function n(r,o,l=!0,f=!0){if(f){r||(r={});for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=o[a],o[a]?.__children&&n({},o[a].__children,!1,!1)):typeof o[a]=="function"&&(r[a]=o[a]);n(r,o,!0,!1)}else if(o?.__children&&!l)o.__children?.constructor.name==="Object"?r.__children?.constructor.name==="Object"?r.__children=n(r.__children,o.__children,!0,!1):r.__children=n({},o.__children,!0,!1):r.__children=o.__children;else if(l)for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=Object.assign({},o[a]),o[a]?.__children&&(r[a].__children=n({},o[a].__children,!1,!1))):typeof o[a]=="function"&&(r[a]=o[a]);return r}this.__node.roots=n(this.__node.roots?this.__node.roots:{},e);let i=Object.assign({},e);i.__node&&delete i.__node;let s=this.recursiveSet(i,this,void 0,e,t);if(e.__node){if(!e.__node.tag)e.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(e.__node.tag)){let r=new p(e,this,this);this.set(r.__node.tag,r),this.runLoaders(r,this,e,e.__node.tag),r.__listeners&&(s[r.__node.tag]=r.__listeners)}}else e.__listeners&&this.setListeners(e.__listeners);return this.setListeners(s),i};setLoaders=(e,t)=>(t?this.__node.loaders=e:Object.assign(this.__node.loaders,e),this.__node.loaders);runLoaders=(e,t,n,i)=>{for(let s in this.__node.loaders)typeof this.__node.loaders[s]=="object"?(this.__node.loaders[s].init&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i),this.__node.loaders[s].connected&&e.__addOnconnected(this.__node.loaders[s].connect),this.__node.loaders[s].disconnected&&e.__addOndisconnected(this.__node.loaders[s].disconnect)):typeof this.__node.loaders[s]=="function"&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i)};add=(e,t,n=!0)=>{let i={};typeof t=="string"&&(t=this.get(t));let s;if(typeof e=="function"?P(e)?e.prototype instanceof p?(e=e.prototype.constructor(e,t,this),s=!0):e=new e:e={__operator:e,__callable:!0}:typeof e=="string"&&(e=this.__node.roots[e]),!e)return;if(!s){let l=Object.getOwnPropertyNames(e),f=Object.getOwnPropertyNames(Object.getPrototypeOf(e));l.push(...f),l=l.filter(d=>!O.includes(d));let a={};for(let d of l)a[d]=e[d];e=a}if(e.__node||(e.__node={}),e.__node.initial=e,typeof e=="object"&&this.get(e.__node.tag))if(n)this.remove(e.__node.tag,!0);else return;else if(e.__node.tag&&this.get(e.__node.tag))return this.get(e.__node.tag);let r,o=N({},e,2);if(s?r=e:r=new p(e,t,this),this.set(r.__node.tag,r),this.runLoaders(r,t,e,r.__node.tag),this.__node.roots[r.__node.tag]=o,r.__children&&(r.__children=Object.assign({},r.__children),this.recursiveSet(r.__children,r,i,r.__children)),r.__listeners){i[r.__node.tag]=Object.assign({},r.__listeners);for(let l in r.__listeners){let f=r.__listeners[l];r[l]&&(delete i[r.__node.tag][l],i[r.__node.tag][r.__node.tag+"."+l]=f),typeof f=="string"&&(r.__children?.[f]?i[r.__node.tag][l]=r.__node.tag+"."+f:t instanceof p&&(t.__node.tag===f||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===f)&&(i[r.__node.tag][l]=t.__node.tag))}}return this.setListeners(i),r.__callConnected(),r};recursiveSet=(e,t,n={},i,s=!1)=>{let r=Object.getOwnPropertyNames(i).filter(l=>!O.includes(l)),o=Object.getOwnPropertyNames(Object.getPrototypeOf(i)).filter(l=>!O.includes(l));r.push(...o);for(let l of r){if(l.includes("__"))continue;let f=i[l];if(Array.isArray(f))continue;let a;if(typeof f=="function"?P(f)?(f=new f,f instanceof p&&(f=f.prototype.constructor(f,t,this),a=!0)):f={__operator:f,__callable:!0}:typeof f=="string"?this.__node.nodes.get(f)?f=this.__node.nodes.get(f):f=this.__node.roots[f]:typeof f=="boolean"&&(this.__node.nodes.get(l)?f=this.__node.nodes.get(l):f=this.__node.roots[l]),f&&typeof f=="object"){if(!a&&!(f instanceof p)){let h=Object.getOwnPropertyNames(f).filter(m=>!O.includes(m)),g=Object.getOwnPropertyNames(Object.getPrototypeOf(f)).filter(m=>!O.includes(m));g.splice(g.indexOf("constructor"),1),h.push(...g);let b={};for(let m of h)b[m]=f[m];f=b}if(f.__node||(f.__node={}),f.__node.tag||(f.__node.tag=l),f.__node.initial||(f.__node.initial=e[l]),s&&this.get(f.__node.tag))this.remove(f.__node.tag,!0);else if(this.get(f.__node.tag)&&!(!(t instanceof _)&&t?.__node)||t?.__node&&this.get(t.__node.tag+"."+f.__node.tag))continue;let d,c=!1,u=N({},f,2);if(a||f instanceof p?d=f:(d=new p(f,t,this),c=!0),!c&&f instanceof p&&!a&&t instanceof p){let h=this.subscribe(t.__node.tag,d.__node.tag),g=b=>{this.unsubscribe(t.__node.tag,h)};d.__addOndisconnected(g)}else if(d){if(this.set(d.__node.tag,d),this.runLoaders(d,t,e[l],l),e[l]=d,this.__node.roots[d.__node.tag]=u,d.__children&&(d.__children=Object.assign({},d.__children),this.recursiveSet(d.__children,d,n,d.__children)),d.__listeners){n[d.__node.tag]=Object.assign({},d.__listeners);for(let h in d.__listeners){let g=d.__listeners[h],b=h;d[h]&&(delete n[d.__node.tag][h],b=d.__node.tag+"."+h,n[d.__node.tag][b]=g),typeof g=="string"&&(d.__children?.[g]?n[d.__node.tag][b]=d.__node.tag+"."+g:t instanceof p&&(t.__node.tag===g||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===g)&&(n[d.__node.tag][b]=t.__node.tag))}}d.__callConnected()}}}return n};remove=(e,t=!0)=>{if(this.unsubscribe(e),typeof e=="string"&&(e=this.get(e)),e instanceof p){this.delete(e.__node.tag),delete this.__node.roots[e.__node.tag],t&&this.clearListeners(e),e.__callDisconnected();let n=i=>{for(let s in i)this.unsubscribe(i[s]),this.delete(i[s].__node.tag),delete this.__node.roots[i[s].__node.tag],this.delete(s),delete this.__node.roots[s],i[s].__node.tag=i[s].__node.tag.substring(i[s].__node.tag.lastIndexOf(".")+1),t&&this.clearListeners(i[s]),i[s].__callDisconnected(),i[s].__children&&n(i[s].__children)};e.__children&&n(e.__children)}return e?.__node.tag&&e?.__parent&&(delete e?.__parent,e.__node.tag=e.__node.tag.substring(e.__node.tag.indexOf(".")+1)),e?.__node.graph&&(e.__node.graph=void 0),e};run=(e,...t)=>{if(typeof e=="string"){let n=this.get(e);if(!n&&e.includes(".")){if(n=this.get(e.substring(0,e.lastIndexOf("."))),typeof n?.[e.substring(e.lastIndexOf(".")+1)]=="function")return n[e.substring(e.lastIndexOf(".")+1)](...t)}else if(n?.__operator)return n.__operator(...t)}if(e?.__operator)return e?.__operator(...t)};setListeners=e=>{for(let t in e){let n=this.get(t);if(typeof e[t]=="object")for(let i in e[t]){let s=this.get(i),r;if(typeof e[t][i]!="object")e[t][i]={__callback:e[t][i]};else if(!e[t][i].__callback)for(let o in e[t][i]){typeof e[t][i][o]!="object"&&(e[t][i][o]={__callback:e[t][i][o]},n.__operator&&(e[t][i][o].__callback===!0||typeof e[t][i][o].__callback>"u")&&(e[t][i][o].__callback=n.__operator));let l=this.get(o);if(l)r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,void 0,e[t][i][o].subInput,t);else{let f=i.substring(0,i.lastIndexOf("."));if(l=this.get(f),l){let a=i.substring(i.lastIndexOf(".")+1);r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,a,e[t][i][o].subInput,t)}}}if("__callback"in e[t][i])if(n&&((e[t][i].__callback===!0||typeof e[t][i].__callback>"u")&&(e[t][i].__callback=n.__operator),typeof e[t][i].__callback=="function"&&(e[t][i].__callback=e[t][i].__callback.bind(n))),s)r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,void 0,e[t][i].subInput,t);else{let o=i.substring(0,i.lastIndexOf("."));s=this.get(o),s&&(r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,i.substring(i.lastIndexOf(".")+1),e[t][i].subInput,t))}}}};clearListeners=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e?.__listeners)for(let n in e.__listeners){if(t&&n!==t||typeof e.__listeners[n]?.sub!="number")continue;let i=this.get(n);if(i)if(typeof!e.__listeners[n]?.__callback=="number")for(let s in e.__listeners[n])e.__listeners[n][s]?.sub&&(this.unsubscribe(i,e.__listeners[n][s].sub,void 0,e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,void 0,e.__listeners[n].subInput),e.__listeners[n].sub=void 0);else if(i=this.get(n.substring(0,n.lastIndexOf("."))),i)if(typeof e.__listeners[n]=="object"&&!e.__listeners[n]?.__callback)for(let s in e.__listeners[n])typeof e.__listeners[n][s]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n][s].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n].subInput),e.__listeners[n].sub=void 0)}};get=e=>this.__node.nodes.get(e);getByUnique=e=>Array.from(this.__node.nodes.values()).find(t=>{if(t.__node.unique===e)return!0});set=(e,t)=>this.__node.nodes.set(e,t);delete=e=>this.__node.nodes.delete(e);list=()=>Array.from(this.__node.nodes.keys());getListener=(e,t,n)=>{let i=this.get(e);if(i){let s=i.__node.unique;return t&&(s+="."+t),this.__node.state.getEvent(s,n)}};getProps=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e instanceof p){let n;if(t)n=Object.assign({},this.__node.roots[e.__node.tag]);else{n=Object.assign({},e);for(let i in n)i.includes("__")&&delete n[i]}}};subscribe=(e,t,n,i,s,r,o)=>{let l=e;typeof e=="string"&&(l=this.get(e),!l&&e.includes(".")&&(l=this.get(e.substring(0,e.lastIndexOf("."))),i=e.substring(e.lastIndexOf(".")+1))),r instanceof p&&(r=r.__node.tag);let f;if(typeof t=="string"){f=t;let d=c=>{if(this.get(c)?.__operator){let u=this.get(c);r=c,c=function(...h){return u.__operator(...h)}}else if(c.includes(".")){r=c.substring(0,c.lastIndexOf("."));let u=this.get(r),h=c.substring(c.lastIndexOf(".")+1);o=h,typeof u[h]=="function"?u[h]instanceof p?c=u[h]:c=function(...g){return u[h](...g)}:c=function(g){return u[h]=g,u[h]}}return c};if(r){let c=this.get(r);typeof c?.[t]=="function"?(o=t,t=function(...u){return c[i](...u)}):c?.[i]?(o=i,c[i]instanceof p?t=c[i]:t=function(u){return c[i]=u,c[i]}):t=d(t)}else t=d(t)}let a;if(l instanceof p){let d=()=>{a=l.__subscribe(t,i,s,r,o,n,f);let c=()=>{a!==void 0&&l.__unsubscribe(a,i,s),a=void 0};l.__addOndisconnected(()=>{c(),l.__addOnconnected(()=>{a===void 0&&l.__node.graph.__node.tag===this.__node.tag&&d()})}),typeof t=="string"&&this.get(t)&&(t=this.get(t)),t instanceof p&&t.__addOndisconnected(()=>{c()})};d()}else if(typeof e=="string"){let d=this.get(e);if(d){if(t instanceof p&&t.__operator){let c=()=>{a=d.__subscribe(t.__operator,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s)};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),t.__addOndisconnected(u)};c()}else if(typeof t=="function"||typeof t=="string"){let c=()=>{a=d.__subscribe(t,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s),a=void 0};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),typeof t=="string"&&this.get(t)&&this.get(t).__addOndisconnected(u)};c()}}else typeof t=="string"&&(t=this.__node.nodes.get(t).__operator),typeof t=="function"&&!t?.__node&&(a=this.__node.state.subscribeEvent(e,t))}return a};unsubscribe=(e,t,n,i)=>e instanceof p?e.__unsubscribe(t,n,i):this.get(e)?.__unsubscribe(t,n,i);setState=e=>{this.__node.state.setState(e)}};function N(_,e,t=1/0,n=0){for(let i in e)e[i]?.constructor.name==="Object"&&n{if(e.get(_)?.__operator){let t=e.get(_);return(...n)=>{t.__operator(...n)}}else if(_.includes(".")){let t=_.split("."),n=t.pop(),i=t.join("."),s=e.get(i);return typeof e.get(i)?.[n]=="function"?(...r)=>s[n](...r):()=>s[n]}else if(e.get(_)){let t=e.get(_);return()=>t}else{let t=_;return()=>t}},A=(_,e,t)=>{let n=[],i=(r,o)=>{if(r==="__output"||r==="__input"||r==="__callback")n[o]={__callback:l=>l,__args:void 0,idx:o};else if(typeof r=="string")n[o]={__callback:j(r,t),__args:void 0,idx:o};else if(typeof r=="function"){let l=r;n[o]={__callback:(...f)=>l(...f),__args:void 0,idx:o}}else if(typeof r=="object"&&(r.__input||r.__callback)){let l=function(f){let a=f.__input?f.__input:f.__callback;if(typeof f.__input=="string"&&(a={__callback:j(f.__input,t),__args:void 0,idx:o}),f.__args){let d=A(a,f.__args,t);a={__callback:d.__callback,__args:d.__args,idx:o}}else a={__callback:a,__args:void 0,idx:o};if(f.__output){let d=f.__output;if(typeof f.__output=="string"?d={__callback:j(d,t),__args:void 0,idx:o}:typeof r.__output=="object"&&(d=l(d)),typeof d?.__callback=="function"){let c=a.__callback,u=d.__callback;a={__callback:(...h)=>u(c(...h)),__args:d.__args,idx:o}}}return a};n[o]=l(r)}else{let l=r;n[o]={__callback:()=>l,__args:void 0,idx:o}}};e.forEach(i),typeof _=="string"&&(_={__callback:j(_,t),__args:void 0});let s=typeof _=="function"?_:_.__callback;return _=function(...r){let o=f=>f.__callback(...r);return s(...n.map(o))},{__callback:_,__args:n}},O=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var S=(_,e,t)=>{_.__node.backward&&e instanceof p&&t.setListeners({[e.__node.tag]:{[_.__node.tag]:e}})},I=(_,e,t)=>{if(_.__operator){let n=Math.random();if(_.__node.loops||(_.__node.loops={}),typeof _.__node.delay=="number"){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=setTimeout(async()=>{r(await i(...s))},_.__node.delay)}))}else if(_.__node.frame===!0){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=requestAnimationFrame(async()=>{r(await i(...s))})}))}if(typeof _.__node.repeat=="number"||typeof _.__node.recursive=="number"){let i=_.__operator;_.__setOperator(async(...s)=>{let r=_.__node.repeat?_.__node.repeat:_.__node.recursive,o,l=async(f,...a)=>{for(;f>0;){if(_.__node.delay||_.__node.frame){i(...a).then(async d=>{_.__node.recursive?await l(f,d):await l(f,...a)});break}else o=await i(...s);f--}};return await l(r,...s),o})}if(_.__node.loop&&typeof _.__node.loop=="number"){let i=_.__operator,s=_.__node.loop;_.__setOperator((...o)=>{if("looping"in _.__node||(_.__node.looping=!0),_.__node.looping){let l=performance.now();i(...o),_.__node.loops[n]=setTimeout(()=>{let a=performance.now()-l-_.__node.loop;a>0?s=_.__node.loop-a:s=_.__node.loop,s<=0&&(s=_.__node.loop),_.__operator(...o)},s)}}),_.__node.looping&&_.__operator();let r=o=>{o.__node.looping&&(o.__node.looping=!1),o.__node.loops[n]&&(clearTimeout(o.__node.loops[n]),cancelAnimationFrame(o.__node.loops[n]))};_.__addOndisconnected(r)}}},v=(_,e,t)=>{if(_.__node.animate===!0||_.__animation){let n=_.__operator;_.__setOperator((...s)=>{"animating"in _.__node||(_.__node.animating=!0),_.__node.animating&&(typeof _.__animation=="function"?_.__animation(...s):n(...s),_.__node.animationFrame=requestAnimationFrame(()=>{_.__operator(...s)}))}),(_.__node.animating||(!("animating"in _.__node)||_.__node.animating)&&_.__animation)&&setTimeout(()=>{_.__node.animationFrame=requestAnimationFrame(_.__operator)},10);let i=s=>{s.__node.animating&&(s.__node.animating=!1),s.__node.animationFrame&&cancelAnimationFrame(s.__node.animationFrame)};_.__addOndisconnected(i)}},M=(_,e,t)=>{if(typeof _.__branch=="object"&&_.__operator&&!_.__branchApplied){let n=_.__operator;_.__branchApplied=!0,_.__operator=(...i)=>{let s=n(...i);for(let r in _.__branch){let o=()=>{typeof _.__branch[r].then=="function"?_.__branch[r].then(s):_.__branch[r].then instanceof p&&_.__branch[r].then.__operator?_.__branch[r].then.__operator(s):s=_.__branch[r].then};typeof _.__branch[r].if=="function"?_.__branch[r].if(s)==!0&&o():_.__branch[r].if===s&&o()}return s}}if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&_.__listeners[n].branch&&!_.__listeners[n].branchApplied){let i=_.__listeners[n].callback;_.__listeners[n].branchApplied=!0,_.__listeners.callback=s=>{let r=()=>{typeof _.__listeners[n].branch.then=="function"?s=_.__listeners[n].branch.then(s):_.__listeners[n].branch.then instanceof p&&_.__listeners[n].branch.then.__operator?s=_.__listeners[n].branch.then.__operator(s):s=_.__listeners[n].branch.then};return typeof _.__listeners[n].branch.if=="function"?_.__listeners[n].branch.if(s)&&r():_.__listeners[n].branch.if===s&&r(),i(s)}}}},R=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&_.__listeners[n].oncreate&&_.__listeners[n].callback(_.__listeners[n].oncreate)},T=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].binding=="object"&&(_.__listeners.callback=_.__listeners.callback.bind(_.__listeners[n].binding))},$=(_,e,t)=>{if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].transform=="function"&&!_.__listeners[n].transformApplied){let i=_.__listeners[n].callback;_.__listeners[n].transformApplied=!0,_.__listeners.callback=s=>(s=_.__listeners[n].transform(s),i(s))}}},C=(_,e,t)=>{_.post&&!_.__operator?_.__setOperator(_.post):!_.__operator&&typeof _.get=="function"&&_.__setOperator(_.get),!_.get&&_.__operator,_.aliases&&_.aliases.forEach(n=>{t.set(n,_);let i=s=>{t.__node.nodes.delete(n)};_.__addOndisconnected(i)}),typeof t.__node.roots?.[_.__node.tag]=="object"&&_.get&&(t.__node.roots[_.__node.tag].get=_.get)},J={backprop:S,loop:I,animate:v,branching:M,triggerListenerOncreate:R,bindListener:T,transformListenerResult:$,substitute__operator:C};export{w as Callable,x as EventHandler,y as Graph,p as GraphNode,v as animate,S as backprop,T as bindListener,M as branching,q as getAllProperties,j as getCallbackFromString,W as instanceObject,L as isFunction,P as isNativeClass,J as loaders,I as loop,F as state,C as substitute__operator,$ as transformListenerResult,R as triggerListenerOncreate,A as wrapArgs}; +var g=class{constructor(e){this.pushToState={};this.data={};this.triggers={};this.setState=e=>{Object.assign(this.data,e);for(let _ of Object.getOwnPropertyNames(e))this.triggers[_]&&this.triggers[_].forEach(t=>t.onchange(this.data[_]));return this.data};this.setValue=(e,_)=>{this.data[e]=_,this.triggers[e]&&this.triggers[e].forEach(t=>t.onchange(this.data[e]))};this.subscribeTrigger=(e,_)=>{if(e){this.triggers[e]||(this.triggers[e]=[]);let t=this.triggers[e].length;return this.triggers[e].push({sub:t,onchange:_}),this.triggers[e].length-1}else return};this.unsubscribeTrigger=(e,_)=>{let t=this.triggers[e];if(t)if(!_)delete this.triggers[e];else{let i,s=t.find((r,o)=>{if(r.sub===i)return i=o,!0});return s&&t.splice(i,1),this.onRemoved&&this.onRemoved(s),!0}};this.subscribeTriggerOnce=(e,_)=>{let t,i=s=>{_(s),this.unsubscribeTrigger(e,t)};t=this.subscribeTrigger(e,i)};this.getTrigger=(e,_)=>{for(let t in this.triggers[e])if(this.triggers[e][t].sub===_)return this.triggers[e][t]};typeof e=="object"&&(this.data=e)}};var p=new g,d=class{constructor(e,_,t){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state:p};this.__subscribe=(e,_,t,i,s)=>{let r=(a,f=(c,u)=>c,h=e)=>{let c=this.__node.state.subscribeTrigger(a,h),u=this.__node.state.getTrigger(a,c);return u.source=this.__node.tag,_&&(u.key=_),u.target=f(e),i&&(u.bound=i),c},o=a=>{if(!this.__node.graph.get(a)&&a.includes(".")){let h=this.__node.graph.get(a.substring(0,a.lastIndexOf("."))),c=a.substring(a.lastIndexOf(".")+1);h&&typeof h[c]=="function"&&(a=(...u)=>h[c](...u))}};if(_){this.__node.localState||this.__addLocalState(this),typeof e=="string"&&(typeof this[e]=="function"?e=this[e]:this.__node.graph&&o(e));let a,f=t?this.__node.unique+"."+_+"input":this.__node.unique+"."+_;return typeof e=="function"?a=r(f):e?.__node&&(a=r(f,(h,c)=>c||h.__node.unique,h=>{e.__operator&&e.__operator(h)})),a}else{typeof e=="string"&&(this.__node.graph?e=this.__node.graph.get(e):e=this.__node.graph.nodes.get(e));let a,f=t?this.__node.unique+"input":this.__node.unique;return typeof e=="function"?a=r(f):e?.__node&&(a=r(f,(h,c)=>c||h.__node.unique,h=>{e.__operator&&e.__operator(h)})),a}};this.__unsubscribe=(e,_,t)=>_?this.__node.state.unsubscribeTrigger(t?this.__node.unique+"."+_+"input":this.__node.unique+"."+_,e):this.__node.state.unsubscribeTrigger(t?this.__node.unique+"input":this.__node.unique,e);this.__setOperator=e=>{if(e=e.bind(this),this.__operator=(..._)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"input",_);let t=e(..._);return this.__node.state.triggers[this.__node.unique]&&(typeof t?.then=="function"?t.then(i=>{i!==void 0&&this.__node.state.setValue(this.__node.unique,i)}).catch(console.error):t!==void 0&&this.__node.state.setValue(this.__node.unique,t)),t},!this.__subscribedToParent&&this.__parent instanceof d&&this.__parent.__operator){let _=this.__parent.__subscribe(this),t=()=>{this.__parent?.__unsubscribe(_),delete this.__subscribedToParent};this.__addOndisconnected(t),this.__subscribedToParent=!0}return this.__operator};this.__proxyObject=e=>{let _=O(e);for(let t of _)typeof this[t]>"u"&&(typeof e[t]=="function"?this[t]=(...i)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"."+t+"input",i);let s=e[t](...i);return this.__node.state.triggers[this.__node.unique+"."+t]&&(typeof s?.then=="function"?s.then(r=>{this.__node.state.setValue(this.__node.unique+"."+t,r)}).catch(console.error):this.__node.state.setValue(this.__node.unique+"."+t,s)),s}:Object.defineProperty(this,t,{get:()=>e[t],set:s=>{e[t]=s,this.__node.state.triggers[this.__node.unique+"."+t]&&this.__node.state.setValue(this.__node.unique+"."+t,s)},enumerable:!0,configurable:!0}))};let i=e;if(typeof e=="function"?b(e)?(console.log(e),e=new e):e={__operator:e,__node:{forward:!0,tag:e.name}}:typeof e=="string"&&t?.get(e)&&(e=t.get(e)),e.__node.initial||(e.__node.initial=i),typeof e=="object"){if(e.__props&&(typeof e.__props=="function"&&(e.__props=new e.__props),typeof e.__props=="object"&&this.__proxyObject(e.__props)),typeof e.__node=="string"?t?.get(e.__node.tag)?e=t.get(e.__node.tag):e.__node={}:e.__node||(e.__node={}),t&&(e.__node.graph=t),e.__operator){if(typeof e.__operator=="string"&&t){let r=t.get(e.__operator);r&&(e.__operator=r.__operator),!e.__node.tag&&e.__operator.name&&(e.__node.tag=e.__operator.name)}typeof e.__operator=="function"&&(e.__operator=this.__setOperator(e.__operator))}if(e.__node.tag||(e.__operator?.name?e.__node.tag=e.__operator.name:e.__node.tag=`node${Math.floor(Math.random()*1e15)}`),!e.__parent&&_&&(e.__parent=_),_?.__node&&!(_ instanceof l||e instanceof l)&&(e.__node.tag=_.__node.tag+"."+e.__node.tag),_ instanceof l&&e instanceof l&&(e.__node.loaders&&Object.assign(_.__node.loaders?_.__node.loaders:{},e.__node.loaders),_.__node.mapGraphs)){e.__node.nodes.forEach(o=>{_.set(e.__node.tag+"."+o.__node.tag,o)});let r=()=>{e.__node.nodes.forEach(o=>{_.__node.nodes.delete(e.__node.tag+"."+o.__node.tag)})};this.__addOndisconnected(r)}e.__node=Object.assign(this.__node,e.__node);let s=Object.getOwnPropertyNames(e);for(let r of s)this[r]=e[r];if(typeof e.default=="function"&&!e.__operator){let r=e.default.bind(this);this.default=(...o)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"input",o);let a=r(...o);return typeof a?.then=="function"?a.then(f=>{f!==void 0&&this.__node.state.setValue(this.__node.unique,f)}).catch(console.error):a!==void 0&&this.__node.state.setValue(this.__node.unique,a),a},e.default=this.default}e instanceof l&&(this.__node.source=e)}}__addLocalState(e){if(!e)return;this.__node.localState||(this.__node.localState={});let _=this.__node.localState;for(let t in e)if(!(this.__props&&this.__props[t]))if(typeof e[t]=="function"){if(!t.startsWith("_")){let i=e[t].bind(this);e[t]=(...s)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"."+t+"input",s);let r=i(...s);return typeof r?.then=="function"?this.__node.state.triggers[this.__node.unique+"."+t]&&r.then(o=>{this.__node.state.setValue(this.__node.unique+"."+t,o)}).catch(console.error):this.__node.state.triggers[this.__node.unique+"."+t]&&this.__node.state.setValue(this.__node.unique+"."+t,r),r},this[t]=e[t]}}else{_[t]=e[t];let i={get:()=>_[t],set:s=>{_[t]=s,this.__node.state.triggers[this.__node.unique+"."+t]&&this.__node.state.setValue(this.__node.unique+"."+t,s)},enumerable:!0,configurable:!0};if(Object.defineProperty(this,t,i),typeof this.__node.initial=="object"){let s=Object.getOwnPropertyDescriptor(this.__node.initial,t);(s===void 0||s?.configurable)&&Object.defineProperty(this.__node.initial,t,i)}}}__addOnconnected(e){Array.isArray(this.__ondisconnected)?this.__onconnected.push(e):typeof this.__onconnected=="function"?this.__onconnected=[e,this.__onconnected]:this.__onconnected=e}__addOndisconnected(e){Array.isArray(this.__ondisconnected)?this.__ondisconnected.push(e):typeof this.__ondisconnected=="function"?this.__ondisconnected=[e,this.__ondisconnected]:this.__ondisconnected=e}__callConnected(e=this){typeof this.__onconnected=="function"?this.__onconnected(this):Array.isArray(this.__onconnected)&&this.__onconnected.forEach(_=>{_(this)})}__callDisconnected(e=this){typeof this.__ondisconnected=="function"?this.__ondisconnected(this):Array.isArray(this.__ondisconnected)&&this.__ondisconnected.forEach(_=>{_(this)})}},l=class{constructor(e){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state:p};this.init=e=>{e&&(y(this.__node,e),e.tree&&this.setTree(e.tree))};this.setTree=e=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},e);let _=Object.assign({},e);_.__node&&delete _.__node;let t=this.recursiveSet(_,this,void 0,e);if(e.__node){if(!e.__node.tag)e.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(e.__node.tag)){let i=new d(e,this,this);this.set(i.__node.tag,i);for(let s in this.__node.loaders)typeof this.__node.loaders[s]=="object"?(this.__node.loaders[s].init&&this.__node.loaders[s](i,parent,this,this.__node.tree,e),this.__node.loaders[s].connected&&i.__addOnconnected(this.__node.loaders[s].connect),this.__node.loaders[s].disconnected&&i.__addOndisconnected(this.__node.loaders[s].disconnect)):typeof this.__node.loaders=="function"&&this.__node.loaders[s](i,this,this,e,e,e.__node.tag);i.__listeners&&(t[i.__node.tag]=i.__listeners)}}else e.__listeners&&this.setListeners(e.__listeners);return this.setListeners(t),_};this.setLoaders=(e,_)=>(_?this.__node.loaders=e:Object.assign(this.__node.loaders,e),this.__node.loaders);this.add=(e,_)=>{let t={};typeof _=="string"&&(_=this.get(_));let i;if(typeof e=="function"?b(e)?e.prototype instanceof d?(e=e.prototype.constructor(e,_,this),i=!0):e=new e:e={__operator:e}:typeof e=="string"&&(e=this.__node.tree[e]),i||(e=Object.assign({},e)),e.__node||(e.__node={}),e.__node.initial=e,typeof e=="object"&&(!e?.__node?.tag||!this.get(e.__node.tag))){let s;i?s=e:s=new d(e,_,this),this.set(s.__node.tag,s);for(let r in this.__node.loaders)typeof this.__node.loaders[r]=="object"?(this.__node.loaders[r].init&&this.__node.loaders[r](s,_,this,this.__node.tree,e,s.__node.tag),this.__node.loaders[r].connected&&s.__addOnconnected(this.__node.loaders[r].connect),this.__node.loaders[r].disconnected&&s.__addOndisconnected(this.__node.loaders[r].disconnect)):typeof this.__node.loaders=="function"&&this.__node.loaders[r](s,_,this,this.__node.tree,e,s.__node.tag);return this.__node.tree[s.__node.tag]=e,s.__listeners&&(t[s.__node.tag]=s.__listeners),s.__children&&(s.__children=Object.assign({},s.__children),this.recursiveSet(s.__children,s,t,s.__children)),this.setListeners(t),s.__callConnected(),s}};this.recursiveSet=(e,_,t={},i)=>{let s=Object.getOwnPropertyNames(i);for(let r of s){if(r.includes("__"))continue;let o=i[r];if(Array.isArray(o))continue;let a;if(typeof o=="function"?b(o)?(o=new o,o instanceof d&&(o=o.prototype.constructor(o,_,this),a=!0)):o={__operator:o}:typeof o=="string"?o=this.__node.tree[o]:typeof o=="boolean"&&(o=this.__node.tree[r]),typeof o=="object"){if(a||(o=Object.assign({},o)),o.__node||(o.__node={}),o.__node.tag||(o.__node.tag=r),o.__node.initial=e[r],this.get(o.__node.tag)&&!(_?.__node&&this.get(_.__node.tag+"."+o.__node.tag))||_?.__node&&this.get(_.__node.tag+"."+o.__node.tag))continue;let f;a?f=o:f=new d(o,_,this),this.set(f.__node.tag,f);for(let h in this.__node.loaders)this.__node.loaders[h](f,_,this,e,e[r],r);e[r]=f,this.__node.tree[f.__node.tag]=o,f.__listeners&&(t[f.__node.tag]=f.__listeners),f.__children&&(f.__children=Object.assign({},f.__children),this.recursiveSet(f.__children,f,t,f.__children)),f.__callConnected()}}return t};this.remove=(e,_=!0)=>{if(this.unsubscribe(e),typeof e=="string"&&(e=this.get(e)),e instanceof d){this.delete(e.__node.tag),delete this.__node.tree[e.__node.tag],_&&this.clearListeners(e),e.__callDisconnected();let t=i=>{for(let s in i)this.unsubscribe(i[s]),this.delete(i[s].__node.tag),delete this.__node.tree[i[s].__node.tag],this.delete(s),delete this.__node.tree[s],i[s].__node.tag=i[s].__node.tag.substring(i[s].__node.tag.lastIndexOf(".")+1),_&&this.clearListeners(i[s]),i[s].__callDisconnected(),i[s].__children&&t(i[s].__children)};e.__children&&t(e.__children)}return e?.__node.tag&&e?.__parent&&(delete e?.__parent,e.__node.tag=e.__node.tag.substring(e.__node.tag.indexOf(".")+1)),e};this.run=(e,..._)=>{if(typeof e=="string"){let t=this.get(e);if(!t&&e.includes(".")){if(t=this.get(e.substring(0,e.lastIndexOf("."))),typeof t?.[e.substring(e.lastIndexOf(".")+1)]=="function")return t[e.substring(e.lastIndexOf(".")+1)](..._)}else if(t?.__operator)return t.__operator(..._)}if(e?.__operator)return e?.__operator(..._)};this.setListeners=e=>{for(let _ in e){let t=this.get(_);if(typeof e[_]=="object")for(let i in e[_]){let s=this.get(i),r;if(typeof e[_][i]!="object")e[_][i]={__callback:e[_][i]};else if(!e[_][i].__callback)for(let o in e[_][i]){typeof e[_][i][o]!="object"&&(e[_][i][o]={__callback:e[_][i][o]},e[_][i][o].__callback===!0&&(e[_][i][o].__callback=t.__operator));let a=this.get(o);if(a)if(a)r=this.subscribe(a,e[_][i][o].__callback,void 0,e[_][i].inputState,_,i),typeof t.__listeners[i][o]!="object"&&(t.__listeners[i][o]={__callback:e[_][i][o].__callback,inputState:e[_][i][o]?.inputState}),t.__listeners[i][o].sub=r;else{let f=i.substring(0,i.lastIndexOf("."));a=this.get(f),s&&(r=this.subscribe(a,e[_][i][o].__callback,i.substring(i.lastIndexOf(".")+1),e[_][i][o].inputState,_,i),typeof t.__listeners[i][o]!="object"&&(t.__listeners[i][o]={__callback:e[_][i][o].__callback,inputState:e[_][i][o]?.inputState}),t.__listeners[i][o].sub=r)}}if(e[_][i].__callback)if(e[_][i].__callback===!0&&(e[_][i].__callback=t.__operator),typeof e[_][i].__callback=="function"&&(e[_][i].__callback=e[_][i].__callback.bind(t)),typeof t.__listeners!="object"&&(t.__listeners={}),s)r=this.subscribe(s,e[_][i].__callback,void 0,e[_][i].inputState,_,i),typeof t.__listeners[i]!="object"&&(t.__listeners[i]={__callback:e[_][i].__callback,inputState:e[_][i]?.inputState}),t.__listeners[i].sub=r;else{let o=i.substring(0,i.lastIndexOf("."));s=this.get(o),s&&(r=this.subscribe(s,e[_][i].__callback,i.substring(i.lastIndexOf(".")+1),e[_][i].inputState,_,i),typeof t.__listeners[i]!="object"&&(t.__listeners[i]={__callback:e[_][i].__callback,inputState:e[_][i]?.inputState}),t.__listeners[i].sub=r)}}}};this.clearListeners=(e,_)=>{if(typeof e=="string"&&(e=this.get(e)),e?.__listeners)for(let t in e.__listeners){if(_&&t!==_||typeof e.__listeners[t].sub!="number")continue;let i=this.get(t);if(i)if(e.__listeners[t].__callback)this.unsubscribe(i,e.__listeners[t].sub,void 0,e.__listeners[t].inputState);else for(let s in e.__listeners[t])this.unsubscribe(i,e.__listeners[t][s].sub,void 0,e.__listeners[t][s].inputState);else if(i=this.get(t.substring(0,t.lastIndexOf("."))),i)if(e.__listeners[t].__callback)this.unsubscribe(i,e.__listeners[t].sub,t.substring(t.lastIndexOf(".")+1),e.__listeners[t].inputState);else for(let s in e.__listeners[t])this.unsubscribe(i,e.__listeners[t][s].sub,t.substring(t.lastIndexOf(".")+1),e.__listeners[t][s].inputState);delete e.__listeners[t]}};this.get=e=>this.__node.nodes.get(e);this.set=(e,_)=>this.__node.nodes.set(e,_);this.delete=e=>this.__node.nodes.delete(e);this.getProps=(e,_)=>{if(typeof e=="string"&&(e=this.get(e)),e instanceof d){let t;_?t=Object.assign({},this.__node.tree[e.__node.tag]):(t=Object.assign({},e),delete t.__unsubscribe,delete t.__setOperator,delete t.__node,delete t.__subscribeState,delete t.__subscribe)}};this.subscribe=(e,_,t,i,s,r)=>{let o=e;e instanceof d||(o=this.get(e));let a;if(typeof _=="string")if(s){let f=this.get(s)?.[_];typeof f=="function"&&(_=f)}else _=this.get(_)?.__operator;if(o instanceof d){a=o.__subscribe(_,t,i,s,r);let f=()=>{o.__unsubscribe(a,t,i)};o.__addOndisconnected(f)}else if(typeof e=="string")if(this.get(e))if(_ instanceof d&&_.__operator){a=this.get(e).__subscribe(_.__operator,t,i,s,r);let f=()=>{this.get(e).__unsubscribe(a)};_.__addOndisconnected(f)}else(typeof _=="function"||typeof _=="string")&&(a=this.get(e).__subscribe(_,t,i,s,r),this.__node.state.getTrigger(this.get(e).__node.unique,a).source=e);else typeof _=="string"&&(_=this.__node.nodes.get(_).__operator),typeof _=="function"&&(a=this.__node.state.subscribeTrigger(e,_));return a};this.unsubscribe=(e,_,t,i)=>e instanceof d?e.__unsubscribe(_,t,i):this.get(e)?.__unsubscribe(_,t,i);this.setState=e=>{this.__node.state.setState(e)};this.init(e)}};function y(n,e){for(let _ in e)e[_]?.constructor.name==="Object"&&!Array.isArray(e[_])?n[_]?.constructor.name==="Object"&&!Array.isArray(n[_])?y(n[_],e[_]):n[_]=y({},e[_]):n[_]=e[_];return n}function O(n){var e=[],_=n;do{var t=Object.getOwnPropertyNames(_);t.forEach(function(i){e.indexOf(i)===-1&&e.push(i)})}while(_=Object.getPrototypeOf(_));return e}function A(n){let e=O(n),_={};for(let t of e)_[t]=n[t];return _}function b(n){return typeof n=="function"&&n.hasOwnProperty("prototype")&&!n.hasOwnProperty("arguments")}var G=(n,e,_)=>{n.__node.backward&&e instanceof d&&_.setListeners({[e.__node.tag]:{[n.__node.tag]:e}})},m=(n,e,_)=>{if(n.__operator&&!n.__node.looperSet){if(n.__node.looperSet=!0,typeof n.__node.delay=="number"){let t=n.__operator;n.__setOperator((...i)=>new Promise((s,r)=>{setTimeout(async()=>{s(await t(...i))},n.__node.delay)}))}else if(n.__node.frame===!0){let t=n.__operator;n.__setOperator((...i)=>new Promise((s,r)=>{requestAnimationFrame(async()=>{s(await t(...i))})}))}if(typeof n.__node.repeat=="number"||typeof n.__node.recursive=="number"){let t=n.__operator;n.__setOperator(async(...i)=>{let s=n.__node.repeat?n.__node.repeat:n.__node.recursive,r,o=async(a,...f)=>{for(;a>0;){if(n.__node.delay||n.__node.frame){t(...f).then(async h=>{n.__node.recursive?await o(a,h):await o(a,...f)});break}else r=await t(...i);a--}};return await o(s,...i),r})}if(n.__node.loop&&typeof n.__node.loop=="number"){let t=n.__operator;n.__setOperator((...s)=>{"looping"in n.__node||(n.__node.looping=!0),n.__node.looping&&(t(...s),setTimeout(()=>{n.__operator(...s)},n.__node.loop))}),n.__node.looping&&n.__operator();let i=s=>{s.__node.looping&&(s.__node.looping=!1)};n.__addOndisconnected(i)}}},N=(n,e,_)=>{if(n.__node.animate===!0||n.__animation){let t=n.__operator;n.__setOperator((...s)=>{"animating"in n.__node||(n.__node.animating=!0),n.__node.animating&&(typeof n.__animation=="function"?n.__animation(...s):t(...s),requestAnimationFrame(()=>{n.__operator(...s)}))}),(n.__node.animating||(!("animating"in n.__node)||n.__node.animating)&&n.__animation)&&setTimeout(()=>{requestAnimationFrame(n.__operator)},10);let i=s=>{s.__node.animating&&(s.__node.animating=!1)};n.__addOndisconnected(i)}},j=(n,e,_)=>{if(typeof n.__node.branch=="object"&&n.__operator&&!n.__node.branchApplied){let t=n.__operator;n.__node.branchApplied=!0,n.__operator=(...i)=>{let s=t(...i);for(let r in n.__node.branch){let o=()=>{typeof n.__node.branch[r].then=="function"?n.__node.branch[r].then(s):n.__node.branch[r].then instanceof d&&n.__node.branch[r].then.__operator?n.__node.branch[r].then.__operator(s):s=n.__node.branch[r].then};typeof n.__node.branch[r].if=="function"?n.__node.branch[r].if(s)&&o():n.__node.branch[r].if===s&&o()}return s}}if(n.__listeners){for(let t in n.__listeners)if(typeof n.__listeners[t]=="object"&&n.__listeners[t].branch&&!n.__listeners[t].branchApplied){let i=n.__listeners[t].callback;n.__listeners[t].branchApplied=!0,n.__listeners.callback=s=>{let r=()=>{typeof n.__listeners[t].branch.then=="function"?s=n.__listeners[t].branch.then(s):n.__listeners[t].branch.then instanceof d&&n.__listeners[t].branch.then.__operator?s=n.__listeners[t].branch.then.__operator(s):s=n.__listeners[t].branch.then};return typeof n.__listeners[t].branch.if=="function"?n.__listeners[t].branch.if(s)&&r():n.__listeners[t].branch.if===s&&r(),i(s)}}}},S=(n,e,_)=>{if(n.__listeners)for(let t in n.__listeners)typeof n.__listeners[t]=="object"&&n.__listeners[t].oncreate&&n.__listeners[t].callback(n.__listeners[t].oncreate)},x=(n,e,_)=>{if(n.__listeners)for(let t in n.__listeners)typeof n.__listeners[t]=="object"&&typeof n.__listeners[t].binding=="object"&&(n.__listeners.callback=n.__listeners.callback.bind(n.__listeners[t].binding))},q=(n,e,_)=>{if(n.__listeners){for(let t in n.__listeners)if(typeof n.__listeners[t]=="object"&&typeof n.__listeners[t].transform=="function"&&!n.__listeners[t].transformApplied){let i=n.__listeners[t].callback;n.__listeners[t].transformApplied=!0,n.__listeners.callback=s=>(s=n.__listeners[t].transform(s),i(s))}}},v=(n,e,_)=>{n.post&&!n.__operator?n.__setOperator(n.post):!n.__operator&&typeof n.get=="function"&&n.__setOperator(n.get),!n.get&&n.__operator&&(n.get=n.__operator),n.aliases&&n.aliases.forEach(t=>{_.set(t,n);let i=s=>{_.__node.nodes.delete(t)};n.__addOndisconnected(i)}),typeof _.__node.tree[n.__node.tag]=="object"&&n.get&&(_.__node.tree[n.__node.tag].get=n.get)},E={backprop:G,loop:m,animate:N,branching:j,triggerListenerOncreate:S,bindListener:x,transformListenerResult:q,substitute__operator:v};export{l as Graph,d as GraphNode,N as animate,G as backprop,x as bindListener,j as branching,O as getAllProperties,A as instanceObject,b as isNativeClass,E as loaders,m as loop,p as state,v as substitute__operator,q as transformListenerResult,S as triggerListenerOncreate}; diff --git a/dist/index.core.js b/dist/index.core.js index e2031152..543dbd00 100644 --- a/dist/index.core.js +++ b/dist/index.core.js @@ -1 +1 @@ -(()=>{var x=class{data={};triggers={};ctr=0;constructor(e){typeof e=="object"&&(this.data=e)}setState=e=>{Object.assign(this.data,e);let t=Object.getOwnPropertyNames(e);for(let n of t)this.triggerEvent(n,this.data[n]);if(this.triggers[G]){let n=s=>{s(e)},i=this.triggers[G].length;for(let s=i-1;s>=0;s--)n(this.triggers[G][s].onchange)}return this.data};setValue=(e,t)=>{this.data[e]=t,this.triggerEvent(e,t)};triggerEvent=(e,t)=>{if(this.triggers[e]){let n=s=>{s.onchange(t)},i=this.triggers[e].length;for(let s=i-1;s>=0;s--)n(this.triggers[e][s])}};subscribeState=e=>this.subscribeEvent(G,e);unsubscribeState=e=>this.unsubscribeEvent(G,e);subscribeEvent=(e,t,n,i)=>{if(e){n&&i&&!this.triggers[e]&&Object.defineProperty(this.data,e,{get:()=>n[i],set:r=>{n[i]=r},enumerable:!0,configurable:!0}),this.triggers[e]||(this.triggers[e]=[]);let s=this.ctr;return this.ctr++,this.triggers[e].push({sub:s,onchange:t}),s}else return};unsubscribeEvent=(e,t)=>{let n=this.triggers[e];if(n)if(t===void 0)delete this.triggers[e],delete this.data[e];else{let i,s=n.find((r,o)=>{if(r.sub===t)return i=o,!0});return s&&n.splice(i,1),Object.keys(n).length===0&&(delete this.triggers[e],delete this.data[e]),this.onRemoved&&this.onRemoved(s),!0}};subscribeEventOnce=(e,t)=>{let n,i=s=>{t(s),this.unsubscribeEvent(e,n)};return n=this.subscribeEvent(e,i),n};getEvent=(e,t)=>{if(typeof t!="number")return this.triggers[e];for(let n in this.triggers[e])if(this.triggers[e][n].sub===t)return this.triggers[e][n]};getSnapshot=()=>{let e={};for(let t in this.data)e[t]=this.data[t]};onRemoved},G="*s";var F=new x,w=class extends Function{__bound;__call;constructor(){return super("return this.__bound.__call.apply(this.__bound, arguments)"),this.__bound=this.bind(this),this.__bound}},p=class _{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state:F};__children;__parent;__operator;__listeners;__props;__args;constructor(e,t,n){if(this.__setProperties(e,t,n),typeof e=="function"||e?.__callable){let i=new w;i.__call=(...r)=>this.__operator(...r);let s=new Proxy(i,{get:(r,o,l)=>Reflect.has(this,o)?Reflect.get(this,o,l):Reflect.get(r,o,l),set:(r,o,l,f)=>Reflect.has(this,o)?Reflect.set(this,o,l,f):Reflect.set(r,o,l,f)});return Object.setPrototypeOf(s,this),s}}get __graph(){return this.__node?.graph}set __graph(e){this.__node.graph=e}__setProperties=(e,t,n)=>{if((()=>{let s=e;typeof e=="function"?P(e)?e=new e:e={__operator:e,__node:{forward:!0,tag:e.name}}:typeof e=="string"&&n?.get(e)&&(e=n.get(e)),"__node"in e||(e.__node={}),e.__node.initial||(e.__node.initial=s)})(),typeof e=="object"){let s=()=>{e.__node?.state?this.__node.state=e.__node.state:n&&(e.__node.state=n.__node.state)},r=()=>{e.__props&&(typeof e.__props=="function"&&(e.__props=new e.__props),typeof e.__props=="object"&&this.__proxyObject(e.__props))},o=()=>{e.__node.tag||(e.__operator?.name?e.__node.tag=e.__operator.name:e.__node.tag=`node${Math.floor(Math.random()*1e15)}`)},l=()=>{typeof e.__node=="string"?n?.get(e.__node.tag)?e=n.get(e.__node.tag):e.__node={}:e.__node||(e.__node={}),n&&(e.__node.graph=n),e instanceof y&&(e.__node.source=e)},f=()=>{if(!e.__parent&&t&&(e.__parent=t),t?.__node&&!(t instanceof y||e instanceof y)&&(e.__node.tag=t.__node.tag+"."+e.__node.tag),t instanceof y&&e instanceof y&&(e.__node.loaders&&Object.assign(t.__node.loaders?t.__node.loaders:{},e.__node.loaders),t.__node.mapGraphs)){e.__node.nodes.forEach(h=>{t.set(e.__node.tag+"."+h.__node.tag,h)});let u=()=>{e.__node.nodes.forEach(h=>{t.__node.nodes.delete(e.__node.tag+"."+h.__node.tag)})};this.__addOndisconnected(u)}},a=()=>{if(typeof e.default=="function"&&!e.__operator&&(e.__operator=e.default),e.__operator){if(typeof e.__operator=="string"&&n){let u=n.get(e.__operator);u&&(e.__operator=u.__operator),!e.__node.tag&&e.__operator.name&&(e.__node.tag=e.__operator.name)}typeof e.__operator=="function"&&(e.__operator=this.__setOperator(e.__operator)),e.default&&(e.default=e.__operator)}},d=()=>{e.__node=Object.assign(this.__node,e.__node);let u=Object.getOwnPropertyNames(e).filter(h=>{if(!O[h])return!0});for(let h of u)h in e&&h!=="name"&&(this[h]=e[h])},c=()=>{this.__onconnected&&(typeof this.__onconnected=="function"?this.__onconnected=this.__onconnected.bind(this):Array.isArray(this.__onconnected)&&(this.__onconnected=this.__onconnected.map(u=>u.bind(this))),typeof this.__ondisconnected=="function"?this.__ondisconnected=this.__ondisconnected.bind(this):Array.isArray(this.__ondisconnected)&&(this.__ondisconnected=this.__ondisconnected.map(u=>u.bind(this))))};s(),o(),r(),l(),f(),d(),c(),a()}};__subscribe=(e,t,n,i,s,r,o)=>{let l=(a,d=(u,h)=>h||u,c=e)=>{let u;if(r){let b=A(c,r,this.__node.graph);c=b.__callback,u=b.__args}let h=this.__node.state.subscribeEvent(a,c,this,t),g=this.__node.state.getEvent(a,h);return this.__listeners||(this.__listeners={}),this.__listeners[a]=this.__node.state.triggers[a],g&&(g.source=this.__node.tag,t&&(g.key=t),g.target=d(e,i),s&&(g.tkey=s),n&&(g.subInput=n),r&&(g.arguments=u,g.__args=r),o&&(g.__callback=o),g.node=this,g.graph=this.__node.graph),h},f=a=>{let d=this.__node.graph.get(a);if(!d&&a.includes(".")){i=a.substring(0,a.lastIndexOf("."));let c=this.__node.graph.get(a.substring(0,i));s=a.lastIndexOf(".")+1,c&&typeof c[t]=="function"&&(a=(...u)=>c[s](...u))}else d.__operator&&(a=d.__operator,s="__operator");return a};if(t){if((!this.__node.localState||!this.__node.localState[t])&&this.__addLocalState(this,t),typeof e=="string"){if(o=this.__node.tag+"."+e,s=e,i){if(this.__node.graph?.get(i)){let c=this.__node.graph?.get(i);if(typeof c[e]=="function"){let u=c[e];e=(...h)=>{u(...h)}}else{let u=e;e=g=>{c[u]=g}}}}else if(typeof this[e]=="function"){let c=this[e];e=(...u)=>{c(...u)}}else this.__node.graph?.get(e)&&(e=f(e));if(typeof e!="function")return}let a,d=n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}else{if(typeof e=="string"&&(o=e,i||(i=e),this.__node.graph.get(e)&&(e=this.__node.graph.get(e)),s="__operator",typeof e!="object"))return;let a,d=n?this.__node.unique+"input":this.__node.unique;return typeof e=="function"&&!e?.__node?a=l(d,(c,u)=>u||c,e):e?.__node&&(a=l(d,(c,u)=>u||c.__node.unique,(...c)=>{e.__operator&&e.__operator(...c)})),a}};__unsubscribe=(e,t,n)=>t?this.__node.state.unsubscribeEvent(n?this.__node.unique+"."+t+"input":this.__node.unique+"."+t,e):this.__node.state.unsubscribeEvent(n?this.__node.unique+"input":this.__node.unique,e);__setOperator=e=>{e=e.bind(this),this.__args&&this.__node.graph&&(e=A(e,this.__args,this.__node.graph).__callback);let t=`${this.__node.unique}input`;if(this.__operator=(...n)=>{this.__node.state.triggers[t]&&this.__node.state.setValue(t,n);let i=e(...n);return this.__node.state.triggers[this.__node.unique]&&(typeof i?.then=="function"?i.then(s=>{s!==void 0&&this.__node.state.setValue(this.__node.unique,s)}).catch(console.error):i!==void 0&&this.__node.state.setValue(this.__node.unique,i)),i},this.__parent instanceof _&&!this.__subscribedToParent&&this.__parent.__operator){let n=this.__parent.__subscribe(this),i=()=>{this.__parent?.__unsubscribe(n),delete this.__subscribedToParent};this.__addOndisconnected(i),this.__subscribedToParent=!0}return this.__operator};__addLocalState=(e,t)=>{if(!e)return;this.__node.localState||(this.__node.localState={});let n=this.__node.localState,i=(s,r)=>{let o=this.__node.unique+"."+r,l=`${o}input`,f,a,d,c;if(typeof s[r]=="function"&&r!=="__operator")this.__props?.[r]?d=this.__props:d=n,f=()=>d[r],a=u=>{this.__props?.[r]||(u=u.bind(this)),d[r]=(...h)=>{this.__node.state.triggers[l]&&this.__node.state.setValue(l,h);let g=u(...h);return this.__node.state.triggers[o]&&(typeof g?.then=="function"?g.then(b=>{this.__node.state.triggerEvent(o,b)}).catch(console.error):this.__node.state.triggerEvent(o,g)),g}},n[r]=s[r].bind(this),c={get:f,set:a,enumerable:!0,configurable:!0};else if(r!=="__graph"){let u,h,g;this.__props?.[r]?g=this.__props:g=n,u=()=>g[r],h=b=>{g[r]=b,this.__node.state.triggers[o]&&this.__node.state.triggerEvent(o,b)},n[r]=s[r],c={get:u,set:h,enumerable:!0,configurable:!0}}if(Object.defineProperty(s,r,c),typeof this.__node.initial=="object"){let u=Object.getOwnPropertyDescriptor(this.__node.initial,r);(u===void 0||u?.configurable)&&Object.defineProperty(this.__node.initial,r,c)}};if(t)i(e,t);else for(let s in e)i(e,s)};__proxyObject=e=>{let t=q(e);for(let n of t){let i={get:()=>e[n],set:s=>{e[n]=s},enumerable:!0,configurable:!0};if(Object.defineProperty(this,n,i),typeof this.__node.initial=="object"){let s=Object.getOwnPropertyDescriptor(this.__node.initial,n);(s===void 0||s?.configurable)&&Object.defineProperty(this.__node.initial,n,i)}}};__addOnconnected(e){e=e.bind(this),Array.isArray(this.__onconnected)?this.__onconnected.push(e):typeof this.__onconnected=="function"?this.__onconnected=[e,this.__onconnected]:this.__onconnected=e}__addOndisconnected(e){e=e.bind(this),Array.isArray(this.__ondisconnected)?this.__ondisconnected.push(e):typeof this.__ondisconnected=="function"?this.__ondisconnected=[e,this.__ondisconnected]:this.__ondisconnected=e}__callConnected(e=this){if(typeof this.__onconnected=="function")this.__onconnected(this);else if(Array.isArray(this.__onconnected)){let t=n=>{n(this)};this.__onconnected.forEach(t)}}__callDisconnected(e=this){if(typeof this.__ondisconnected=="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let t=n=>{n(this)};this.__ondisconnected.forEach(t)}}},y=class _{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state:F,roots:{}};constructor(e){this.init(e)}init=e=>{if(e){let t=Object.assign({},e);delete t.roots,N(this.__node,t),e.roots&&this.load(e.roots)}};load=(e,t=!1)=>{function n(r,o,l=!0,f=!0){if(f){r||(r={});for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=o[a],o[a]?.__children&&n({},o[a].__children,!1,!1)):typeof o[a]=="function"&&(r[a]=o[a]);n(r,o,!0,!1)}else if(o?.__children&&!l)o.__children?.constructor.name==="Object"?r.__children?.constructor.name==="Object"?r.__children=n(r.__children,o.__children,!0,!1):r.__children=n({},o.__children,!0,!1):r.__children=o.__children;else if(l)for(let a in o)!a.startsWith("__")&&o[a]&&typeof o[a]=="object"?(r[a]=Object.assign({},o[a]),o[a]?.__children&&(r[a].__children=n({},o[a].__children,!1,!1))):typeof o[a]=="function"&&(r[a]=o[a]);return r}this.__node.roots=n(this.__node.roots?this.__node.roots:{},e);let i=Object.assign({},e);i.__node&&delete i.__node;let s=this.recursiveSet(i,this,void 0,e,t);if(e.__node){if(!e.__node.tag)e.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(e.__node.tag)){let r=new p(e,this,this);this.set(r.__node.tag,r),this.runLoaders(r,this,e,e.__node.tag),r.__listeners&&(s[r.__node.tag]=r.__listeners)}}else e.__listeners&&this.setListeners(e.__listeners);return this.setListeners(s),i};setLoaders=(e,t)=>(t?this.__node.loaders=e:Object.assign(this.__node.loaders,e),this.__node.loaders);runLoaders=(e,t,n,i)=>{for(let s in this.__node.loaders)typeof this.__node.loaders[s]=="object"?(this.__node.loaders[s].init&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i),this.__node.loaders[s].connected&&e.__addOnconnected(this.__node.loaders[s].connect),this.__node.loaders[s].disconnected&&e.__addOndisconnected(this.__node.loaders[s].disconnect)):typeof this.__node.loaders[s]=="function"&&this.__node.loaders[s](e,t,this,this.__node.roots,n,i)};add=(e,t,n=!0)=>{let i={};typeof t=="string"&&(t=this.get(t));let s;if(typeof e=="function"?P(e)?e.prototype instanceof p?(e=e.prototype.constructor(e,t,this),s=!0):e=new e:e={__operator:e,__callable:!0}:typeof e=="string"&&(e=this.__node.roots[e]),!e)return;if(!s){let l=Object.getOwnPropertyNames(e),f=Object.getOwnPropertyNames(Object.getPrototypeOf(e));l.push(...f),l=l.filter(d=>!O.includes(d));let a={};for(let d of l)a[d]=e[d];e=a}if(e.__node||(e.__node={}),e.__node.initial=e,typeof e=="object"&&this.get(e.__node.tag))if(n)this.remove(e.__node.tag,!0);else return;else if(e.__node.tag&&this.get(e.__node.tag))return this.get(e.__node.tag);let r,o=N({},e,2);if(s?r=e:r=new p(e,t,this),this.set(r.__node.tag,r),this.runLoaders(r,t,e,r.__node.tag),this.__node.roots[r.__node.tag]=o,r.__children&&(r.__children=Object.assign({},r.__children),this.recursiveSet(r.__children,r,i,r.__children)),r.__listeners){i[r.__node.tag]=Object.assign({},r.__listeners);for(let l in r.__listeners){let f=r.__listeners[l];r[l]&&(delete i[r.__node.tag][l],i[r.__node.tag][r.__node.tag+"."+l]=f),typeof f=="string"&&(r.__children?.[f]?i[r.__node.tag][l]=r.__node.tag+"."+f:t instanceof p&&(t.__node.tag===f||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===f)&&(i[r.__node.tag][l]=t.__node.tag))}}return this.setListeners(i),r.__callConnected(),r};recursiveSet=(e,t,n={},i,s=!1)=>{let r=Object.getOwnPropertyNames(i).filter(l=>!O.includes(l)),o=Object.getOwnPropertyNames(Object.getPrototypeOf(i)).filter(l=>!O.includes(l));r.push(...o);for(let l of r){if(l.includes("__"))continue;let f=i[l];if(Array.isArray(f))continue;let a;if(typeof f=="function"?P(f)?(f=new f,f instanceof p&&(f=f.prototype.constructor(f,t,this),a=!0)):f={__operator:f,__callable:!0}:typeof f=="string"?this.__node.nodes.get(f)?f=this.__node.nodes.get(f):f=this.__node.roots[f]:typeof f=="boolean"&&(this.__node.nodes.get(l)?f=this.__node.nodes.get(l):f=this.__node.roots[l]),f&&typeof f=="object"){if(!a&&!(f instanceof p)){let h=Object.getOwnPropertyNames(f).filter(m=>!O.includes(m)),g=Object.getOwnPropertyNames(Object.getPrototypeOf(f)).filter(m=>!O.includes(m));g.splice(g.indexOf("constructor"),1),h.push(...g);let b={};for(let m of h)b[m]=f[m];f=b}if(f.__node||(f.__node={}),f.__node.tag||(f.__node.tag=l),f.__node.initial||(f.__node.initial=e[l]),s&&this.get(f.__node.tag))this.remove(f.__node.tag,!0);else if(this.get(f.__node.tag)&&!(!(t instanceof _)&&t?.__node)||t?.__node&&this.get(t.__node.tag+"."+f.__node.tag))continue;let d,c=!1,u=N({},f,2);if(a||f instanceof p?d=f:(d=new p(f,t,this),c=!0),!c&&f instanceof p&&!a&&t instanceof p){let h=this.subscribe(t.__node.tag,d.__node.tag),g=b=>{this.unsubscribe(t.__node.tag,h)};d.__addOndisconnected(g)}else if(d){if(this.set(d.__node.tag,d),this.runLoaders(d,t,e[l],l),e[l]=d,this.__node.roots[d.__node.tag]=u,d.__children&&(d.__children=Object.assign({},d.__children),this.recursiveSet(d.__children,d,n,d.__children)),d.__listeners){n[d.__node.tag]=Object.assign({},d.__listeners);for(let h in d.__listeners){let g=d.__listeners[h],b=h;d[h]&&(delete n[d.__node.tag][h],b=d.__node.tag+"."+h,n[d.__node.tag][b]=g),typeof g=="string"&&(d.__children?.[g]?n[d.__node.tag][b]=d.__node.tag+"."+g:t instanceof p&&(t.__node.tag===g||t.__node.tag.includes(".")&&t.__node.tag.split(".").pop()===g)&&(n[d.__node.tag][b]=t.__node.tag))}}d.__callConnected()}}}return n};remove=(e,t=!0)=>{if(this.unsubscribe(e),typeof e=="string"&&(e=this.get(e)),e instanceof p){this.delete(e.__node.tag),delete this.__node.roots[e.__node.tag],t&&this.clearListeners(e),e.__callDisconnected();let n=i=>{for(let s in i)this.unsubscribe(i[s]),this.delete(i[s].__node.tag),delete this.__node.roots[i[s].__node.tag],this.delete(s),delete this.__node.roots[s],i[s].__node.tag=i[s].__node.tag.substring(i[s].__node.tag.lastIndexOf(".")+1),t&&this.clearListeners(i[s]),i[s].__callDisconnected(),i[s].__children&&n(i[s].__children)};e.__children&&n(e.__children)}return e?.__node.tag&&e?.__parent&&(delete e?.__parent,e.__node.tag=e.__node.tag.substring(e.__node.tag.indexOf(".")+1)),e?.__node.graph&&(e.__node.graph=void 0),e};run=(e,...t)=>{if(typeof e=="string"){let n=this.get(e);if(!n&&e.includes(".")){if(n=this.get(e.substring(0,e.lastIndexOf("."))),typeof n?.[e.substring(e.lastIndexOf(".")+1)]=="function")return n[e.substring(e.lastIndexOf(".")+1)](...t)}else if(n?.__operator)return n.__operator(...t)}if(e?.__operator)return e?.__operator(...t)};setListeners=e=>{for(let t in e){let n=this.get(t);if(typeof e[t]=="object")for(let i in e[t]){let s=this.get(i),r;if(typeof e[t][i]!="object")e[t][i]={__callback:e[t][i]};else if(!e[t][i].__callback)for(let o in e[t][i]){typeof e[t][i][o]!="object"&&(e[t][i][o]={__callback:e[t][i][o]},n.__operator&&(e[t][i][o].__callback===!0||typeof e[t][i][o].__callback>"u")&&(e[t][i][o].__callback=n.__operator));let l=this.get(o);if(l)r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,void 0,e[t][i][o].subInput,t);else{let f=i.substring(0,i.lastIndexOf("."));if(l=this.get(f),l){let a=i.substring(i.lastIndexOf(".")+1);r=this.subscribe(l,e[t][i][o].__callback,e[t][i][o].__args,a,e[t][i][o].subInput,t)}}}if("__callback"in e[t][i])if(n&&((e[t][i].__callback===!0||typeof e[t][i].__callback>"u")&&(e[t][i].__callback=n.__operator),typeof e[t][i].__callback=="function"&&(e[t][i].__callback=e[t][i].__callback.bind(n))),s)r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,void 0,e[t][i].subInput,t);else{let o=i.substring(0,i.lastIndexOf("."));s=this.get(o),s&&(r=this.subscribe(s,e[t][i].__callback,e[t][i].__args,i.substring(i.lastIndexOf(".")+1),e[t][i].subInput,t))}}}};clearListeners=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e?.__listeners)for(let n in e.__listeners){if(t&&n!==t||typeof e.__listeners[n]?.sub!="number")continue;let i=this.get(n);if(i)if(typeof!e.__listeners[n]?.__callback=="number")for(let s in e.__listeners[n])e.__listeners[n][s]?.sub&&(this.unsubscribe(i,e.__listeners[n][s].sub,void 0,e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,void 0,e.__listeners[n].subInput),e.__listeners[n].sub=void 0);else if(i=this.get(n.substring(0,n.lastIndexOf("."))),i)if(typeof e.__listeners[n]=="object"&&!e.__listeners[n]?.__callback)for(let s in e.__listeners[n])typeof e.__listeners[n][s]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n][s].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n][s].subInput),e.__listeners[n][s].sub=void 0);else typeof e.__listeners[n]?.sub=="number"&&(this.unsubscribe(i,e.__listeners[n].sub,n.substring(n.lastIndexOf(".")+1),e.__listeners[n].subInput),e.__listeners[n].sub=void 0)}};get=e=>this.__node.nodes.get(e);getByUnique=e=>Array.from(this.__node.nodes.values()).find(t=>{if(t.__node.unique===e)return!0});set=(e,t)=>this.__node.nodes.set(e,t);delete=e=>this.__node.nodes.delete(e);list=()=>Array.from(this.__node.nodes.keys());getListener=(e,t,n)=>{let i=this.get(e);if(i){let s=i.__node.unique;return t&&(s+="."+t),this.__node.state.getEvent(s,n)}};getProps=(e,t)=>{if(typeof e=="string"&&(e=this.get(e)),e instanceof p){let n;if(t)n=Object.assign({},this.__node.roots[e.__node.tag]);else{n=Object.assign({},e);for(let i in n)i.includes("__")&&delete n[i]}}};subscribe=(e,t,n,i,s,r,o)=>{let l=e;typeof e=="string"&&(l=this.get(e),!l&&e.includes(".")&&(l=this.get(e.substring(0,e.lastIndexOf("."))),i=e.substring(e.lastIndexOf(".")+1))),r instanceof p&&(r=r.__node.tag);let f;if(typeof t=="string"){f=t;let d=c=>{if(this.get(c)?.__operator){let u=this.get(c);r=c,c=function(...h){return u.__operator(...h)}}else if(c.includes(".")){r=c.substring(0,c.lastIndexOf("."));let u=this.get(r),h=c.substring(c.lastIndexOf(".")+1);o=h,typeof u[h]=="function"?u[h]instanceof p?c=u[h]:c=function(...g){return u[h](...g)}:c=function(g){return u[h]=g,u[h]}}return c};if(r){let c=this.get(r);typeof c?.[t]=="function"?(o=t,t=function(...u){return c[i](...u)}):c?.[i]?(o=i,c[i]instanceof p?t=c[i]:t=function(u){return c[i]=u,c[i]}):t=d(t)}else t=d(t)}let a;if(l instanceof p){let d=()=>{a=l.__subscribe(t,i,s,r,o,n,f);let c=()=>{a!==void 0&&l.__unsubscribe(a,i,s),a=void 0};l.__addOndisconnected(()=>{c(),l.__addOnconnected(()=>{a===void 0&&l.__node.graph.__node.tag===this.__node.tag&&d()})}),typeof t=="string"&&this.get(t)&&(t=this.get(t)),t instanceof p&&t.__addOndisconnected(()=>{c()})};d()}else if(typeof e=="string"){let d=this.get(e);if(d){if(t instanceof p&&t.__operator){let c=()=>{a=d.__subscribe(t.__operator,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s)};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),t.__addOndisconnected(u)};c()}else if(typeof t=="function"||typeof t=="string"){let c=()=>{a=d.__subscribe(t,i,s,r,o,n,f);let u=()=>{a!==void 0&&d.__unsubscribe(a,i,s),a=void 0};d.__addOndisconnected(()=>{u(),d.__addOnconnected(()=>{a===void 0&&d.__node.graph.__node.tag===this.__node.tag&&c()})}),typeof t=="string"&&this.get(t)&&this.get(t).__addOndisconnected(u)};c()}}else typeof t=="string"&&(t=this.__node.nodes.get(t).__operator),typeof t=="function"&&!t?.__node&&(a=this.__node.state.subscribeEvent(e,t))}return a};unsubscribe=(e,t,n,i)=>e instanceof p?e.__unsubscribe(t,n,i):this.get(e)?.__unsubscribe(t,n,i);setState=e=>{this.__node.state.setState(e)}};function N(_,e,t=1/0,n=0){for(let i in e)e[i]?.constructor.name==="Object"&&n{if(e.get(_)?.__operator){let t=e.get(_);return(...n)=>{t.__operator(...n)}}else if(_.includes(".")){let t=_.split("."),n=t.pop(),i=t.join("."),s=e.get(i);return typeof e.get(i)?.[n]=="function"?(...r)=>s[n](...r):()=>s[n]}else if(e.get(_)){let t=e.get(_);return()=>t}else{let t=_;return()=>t}},A=(_,e,t)=>{let n=[],i=(r,o)=>{if(r==="__output"||r==="__input"||r==="__callback")n[o]={__callback:l=>l,__args:void 0,idx:o};else if(typeof r=="string")n[o]={__callback:j(r,t),__args:void 0,idx:o};else if(typeof r=="function"){let l=r;n[o]={__callback:(...f)=>l(...f),__args:void 0,idx:o}}else if(typeof r=="object"&&(r.__input||r.__callback)){let l=function(f){let a=f.__input?f.__input:f.__callback;if(typeof f.__input=="string"&&(a={__callback:j(f.__input,t),__args:void 0,idx:o}),f.__args){let d=A(a,f.__args,t);a={__callback:d.__callback,__args:d.__args,idx:o}}else a={__callback:a,__args:void 0,idx:o};if(f.__output){let d=f.__output;if(typeof f.__output=="string"?d={__callback:j(d,t),__args:void 0,idx:o}:typeof r.__output=="object"&&(d=l(d)),typeof d?.__callback=="function"){let c=a.__callback,u=d.__callback;a={__callback:(...h)=>u(c(...h)),__args:d.__args,idx:o}}}return a};n[o]=l(r)}else{let l=r;n[o]={__callback:()=>l,__args:void 0,idx:o}}};e.forEach(i),typeof _=="string"&&(_={__callback:j(_,t),__args:void 0});let s=typeof _=="function"?_:_.__callback;return _=function(...r){let o=f=>f.__callback(...r);return s(...n.map(o))},{__callback:_,__args:n}},O=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var S=(_,e,t)=>{_.__node.backward&&e instanceof p&&t.setListeners({[e.__node.tag]:{[_.__node.tag]:e}})},I=(_,e,t)=>{if(_.__operator){let n=Math.random();if(_.__node.loops||(_.__node.loops={}),typeof _.__node.delay=="number"){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=setTimeout(async()=>{r(await i(...s))},_.__node.delay)}))}else if(_.__node.frame===!0){let i=_.__operator;_.__setOperator((...s)=>new Promise((r,o)=>{_.__node.loops[n]=requestAnimationFrame(async()=>{r(await i(...s))})}))}if(typeof _.__node.repeat=="number"||typeof _.__node.recursive=="number"){let i=_.__operator;_.__setOperator(async(...s)=>{let r=_.__node.repeat?_.__node.repeat:_.__node.recursive,o,l=async(f,...a)=>{for(;f>0;){if(_.__node.delay||_.__node.frame){i(...a).then(async d=>{_.__node.recursive?await l(f,d):await l(f,...a)});break}else o=await i(...s);f--}};return await l(r,...s),o})}if(_.__node.loop&&typeof _.__node.loop=="number"){let i=_.__operator,s=_.__node.loop;_.__setOperator((...o)=>{if("looping"in _.__node||(_.__node.looping=!0),_.__node.looping){let l=performance.now();i(...o),_.__node.loops[n]=setTimeout(()=>{let a=performance.now()-l-_.__node.loop;a>0?s=_.__node.loop-a:s=_.__node.loop,s<=0&&(s=_.__node.loop),_.__operator(...o)},s)}}),_.__node.looping&&_.__operator();let r=o=>{o.__node.looping&&(o.__node.looping=!1),o.__node.loops[n]&&(clearTimeout(o.__node.loops[n]),cancelAnimationFrame(o.__node.loops[n]))};_.__addOndisconnected(r)}}},v=(_,e,t)=>{if(_.__node.animate===!0||_.__animation){let n=_.__operator;_.__setOperator((...s)=>{"animating"in _.__node||(_.__node.animating=!0),_.__node.animating&&(typeof _.__animation=="function"?_.__animation(...s):n(...s),_.__node.animationFrame=requestAnimationFrame(()=>{_.__operator(...s)}))}),(_.__node.animating||(!("animating"in _.__node)||_.__node.animating)&&_.__animation)&&setTimeout(()=>{_.__node.animationFrame=requestAnimationFrame(_.__operator)},10);let i=s=>{s.__node.animating&&(s.__node.animating=!1),s.__node.animationFrame&&cancelAnimationFrame(s.__node.animationFrame)};_.__addOndisconnected(i)}},M=(_,e,t)=>{if(typeof _.__branch=="object"&&_.__operator&&!_.__branchApplied){let n=_.__operator;_.__branchApplied=!0,_.__operator=(...i)=>{let s=n(...i);for(let r in _.__branch){let o=()=>{typeof _.__branch[r].then=="function"?_.__branch[r].then(s):_.__branch[r].then instanceof p&&_.__branch[r].then.__operator?_.__branch[r].then.__operator(s):s=_.__branch[r].then};typeof _.__branch[r].if=="function"?_.__branch[r].if(s)==!0&&o():_.__branch[r].if===s&&o()}return s}}if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&_.__listeners[n].branch&&!_.__listeners[n].branchApplied){let i=_.__listeners[n].callback;_.__listeners[n].branchApplied=!0,_.__listeners.callback=s=>{let r=()=>{typeof _.__listeners[n].branch.then=="function"?s=_.__listeners[n].branch.then(s):_.__listeners[n].branch.then instanceof p&&_.__listeners[n].branch.then.__operator?s=_.__listeners[n].branch.then.__operator(s):s=_.__listeners[n].branch.then};return typeof _.__listeners[n].branch.if=="function"?_.__listeners[n].branch.if(s)&&r():_.__listeners[n].branch.if===s&&r(),i(s)}}}},R=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&_.__listeners[n].oncreate&&_.__listeners[n].callback(_.__listeners[n].oncreate)},T=(_,e,t)=>{if(_.__listeners)for(let n in _.__listeners)typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].binding=="object"&&(_.__listeners.callback=_.__listeners.callback.bind(_.__listeners[n].binding))},$=(_,e,t)=>{if(_.__listeners){for(let n in _.__listeners)if(typeof _.__listeners[n]=="object"&&typeof _.__listeners[n].transform=="function"&&!_.__listeners[n].transformApplied){let i=_.__listeners[n].callback;_.__listeners[n].transformApplied=!0,_.__listeners.callback=s=>(s=_.__listeners[n].transform(s),i(s))}}},C=(_,e,t)=>{_.post&&!_.__operator?_.__setOperator(_.post):!_.__operator&&typeof _.get=="function"&&_.__setOperator(_.get),!_.get&&_.__operator,_.aliases&&_.aliases.forEach(n=>{t.set(n,_);let i=s=>{t.__node.nodes.delete(n)};_.__addOndisconnected(i)}),typeof t.__node.roots?.[_.__node.tag]=="object"&&_.get&&(t.__node.roots[_.__node.tag].get=_.get)},J={backprop:S,loop:I,animate:v,branching:M,triggerListenerOncreate:R,bindListener:T,transformListenerResult:$,substitute__operator:C};})(); +(()=>{var g=class{constructor(e){this.pushToState={};this.data={};this.triggers={};this.setState=e=>{Object.assign(this.data,e);for(let _ of Object.getOwnPropertyNames(e))this.triggers[_]&&this.triggers[_].forEach(t=>t.onchange(this.data[_]));return this.data};this.setValue=(e,_)=>{this.data[e]=_,this.triggers[e]&&this.triggers[e].forEach(t=>t.onchange(this.data[e]))};this.subscribeTrigger=(e,_)=>{if(e){this.triggers[e]||(this.triggers[e]=[]);let t=this.triggers[e].length;return this.triggers[e].push({sub:t,onchange:_}),this.triggers[e].length-1}else return};this.unsubscribeTrigger=(e,_)=>{let t=this.triggers[e];if(t)if(!_)delete this.triggers[e];else{let i,s=t.find((r,o)=>{if(r.sub===i)return i=o,!0});return s&&t.splice(i,1),this.onRemoved&&this.onRemoved(s),!0}};this.subscribeTriggerOnce=(e,_)=>{let t,i=s=>{_(s),this.unsubscribeTrigger(e,t)};t=this.subscribeTrigger(e,i)};this.getTrigger=(e,_)=>{for(let t in this.triggers[e])if(this.triggers[e][t].sub===_)return this.triggers[e][t]};typeof e=="object"&&(this.data=e)}};var p=new g,d=class{constructor(e,_,t){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state:p};this.__subscribe=(e,_,t,i,s)=>{let r=(a,f=(c,u)=>c,h=e)=>{let c=this.__node.state.subscribeTrigger(a,h),u=this.__node.state.getTrigger(a,c);return u.source=this.__node.tag,_&&(u.key=_),u.target=f(e),i&&(u.bound=i),c},o=a=>{if(!this.__node.graph.get(a)&&a.includes(".")){let h=this.__node.graph.get(a.substring(0,a.lastIndexOf("."))),c=a.substring(a.lastIndexOf(".")+1);h&&typeof h[c]=="function"&&(a=(...u)=>h[c](...u))}};if(_){this.__node.localState||this.__addLocalState(this),typeof e=="string"&&(typeof this[e]=="function"?e=this[e]:this.__node.graph&&o(e));let a,f=t?this.__node.unique+"."+_+"input":this.__node.unique+"."+_;return typeof e=="function"?a=r(f):e?.__node&&(a=r(f,(h,c)=>c||h.__node.unique,h=>{e.__operator&&e.__operator(h)})),a}else{typeof e=="string"&&(this.__node.graph?e=this.__node.graph.get(e):e=this.__node.graph.nodes.get(e));let a,f=t?this.__node.unique+"input":this.__node.unique;return typeof e=="function"?a=r(f):e?.__node&&(a=r(f,(h,c)=>c||h.__node.unique,h=>{e.__operator&&e.__operator(h)})),a}};this.__unsubscribe=(e,_,t)=>_?this.__node.state.unsubscribeTrigger(t?this.__node.unique+"."+_+"input":this.__node.unique+"."+_,e):this.__node.state.unsubscribeTrigger(t?this.__node.unique+"input":this.__node.unique,e);this.__setOperator=e=>{if(e=e.bind(this),this.__operator=(..._)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"input",_);let t=e(..._);return this.__node.state.triggers[this.__node.unique]&&(typeof t?.then=="function"?t.then(i=>{i!==void 0&&this.__node.state.setValue(this.__node.unique,i)}).catch(console.error):t!==void 0&&this.__node.state.setValue(this.__node.unique,t)),t},!this.__subscribedToParent&&this.__parent instanceof d&&this.__parent.__operator){let _=this.__parent.__subscribe(this),t=()=>{this.__parent?.__unsubscribe(_),delete this.__subscribedToParent};this.__addOndisconnected(t),this.__subscribedToParent=!0}return this.__operator};this.__proxyObject=e=>{let _=O(e);for(let t of _)typeof this[t]>"u"&&(typeof e[t]=="function"?this[t]=(...i)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"."+t+"input",i);let s=e[t](...i);return this.__node.state.triggers[this.__node.unique+"."+t]&&(typeof s?.then=="function"?s.then(r=>{this.__node.state.setValue(this.__node.unique+"."+t,r)}).catch(console.error):this.__node.state.setValue(this.__node.unique+"."+t,s)),s}:Object.defineProperty(this,t,{get:()=>e[t],set:s=>{e[t]=s,this.__node.state.triggers[this.__node.unique+"."+t]&&this.__node.state.setValue(this.__node.unique+"."+t,s)},enumerable:!0,configurable:!0}))};let i=e;if(typeof e=="function"?b(e)?(console.log(e),e=new e):e={__operator:e,__node:{forward:!0,tag:e.name}}:typeof e=="string"&&t?.get(e)&&(e=t.get(e)),e.__node.initial||(e.__node.initial=i),typeof e=="object"){if(e.__props&&(typeof e.__props=="function"&&(e.__props=new e.__props),typeof e.__props=="object"&&this.__proxyObject(e.__props)),typeof e.__node=="string"?t?.get(e.__node.tag)?e=t.get(e.__node.tag):e.__node={}:e.__node||(e.__node={}),t&&(e.__node.graph=t),e.__operator){if(typeof e.__operator=="string"&&t){let r=t.get(e.__operator);r&&(e.__operator=r.__operator),!e.__node.tag&&e.__operator.name&&(e.__node.tag=e.__operator.name)}typeof e.__operator=="function"&&(e.__operator=this.__setOperator(e.__operator))}if(e.__node.tag||(e.__operator?.name?e.__node.tag=e.__operator.name:e.__node.tag=`node${Math.floor(Math.random()*1e15)}`),!e.__parent&&_&&(e.__parent=_),_?.__node&&!(_ instanceof l||e instanceof l)&&(e.__node.tag=_.__node.tag+"."+e.__node.tag),_ instanceof l&&e instanceof l&&(e.__node.loaders&&Object.assign(_.__node.loaders?_.__node.loaders:{},e.__node.loaders),_.__node.mapGraphs)){e.__node.nodes.forEach(o=>{_.set(e.__node.tag+"."+o.__node.tag,o)});let r=()=>{e.__node.nodes.forEach(o=>{_.__node.nodes.delete(e.__node.tag+"."+o.__node.tag)})};this.__addOndisconnected(r)}e.__node=Object.assign(this.__node,e.__node);let s=Object.getOwnPropertyNames(e);for(let r of s)this[r]=e[r];if(typeof e.default=="function"&&!e.__operator){let r=e.default.bind(this);this.default=(...o)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"input",o);let a=r(...o);return typeof a?.then=="function"?a.then(f=>{f!==void 0&&this.__node.state.setValue(this.__node.unique,f)}).catch(console.error):a!==void 0&&this.__node.state.setValue(this.__node.unique,a),a},e.default=this.default}e instanceof l&&(this.__node.source=e)}}__addLocalState(e){if(!e)return;this.__node.localState||(this.__node.localState={});let _=this.__node.localState;for(let t in e)if(!(this.__props&&this.__props[t]))if(typeof e[t]=="function"){if(!t.startsWith("_")){let i=e[t].bind(this);e[t]=(...s)=>{this.__node.inputState&&this.__node.state.setValue(this.__node.unique+"."+t+"input",s);let r=i(...s);return typeof r?.then=="function"?this.__node.state.triggers[this.__node.unique+"."+t]&&r.then(o=>{this.__node.state.setValue(this.__node.unique+"."+t,o)}).catch(console.error):this.__node.state.triggers[this.__node.unique+"."+t]&&this.__node.state.setValue(this.__node.unique+"."+t,r),r},this[t]=e[t]}}else{_[t]=e[t];let i={get:()=>_[t],set:s=>{_[t]=s,this.__node.state.triggers[this.__node.unique+"."+t]&&this.__node.state.setValue(this.__node.unique+"."+t,s)},enumerable:!0,configurable:!0};if(Object.defineProperty(this,t,i),typeof this.__node.initial=="object"){let s=Object.getOwnPropertyDescriptor(this.__node.initial,t);(s===void 0||s?.configurable)&&Object.defineProperty(this.__node.initial,t,i)}}}__addOnconnected(e){Array.isArray(this.__ondisconnected)?this.__onconnected.push(e):typeof this.__onconnected=="function"?this.__onconnected=[e,this.__onconnected]:this.__onconnected=e}__addOndisconnected(e){Array.isArray(this.__ondisconnected)?this.__ondisconnected.push(e):typeof this.__ondisconnected=="function"?this.__ondisconnected=[e,this.__ondisconnected]:this.__ondisconnected=e}__callConnected(e=this){typeof this.__onconnected=="function"?this.__onconnected(this):Array.isArray(this.__onconnected)&&this.__onconnected.forEach(_=>{_(this)})}__callDisconnected(e=this){typeof this.__ondisconnected=="function"?this.__ondisconnected(this):Array.isArray(this.__ondisconnected)&&this.__ondisconnected.forEach(_=>{_(this)})}},l=class{constructor(e){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state:p};this.init=e=>{e&&(y(this.__node,e),e.tree&&this.setTree(e.tree))};this.setTree=e=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},e);let _=Object.assign({},e);_.__node&&delete _.__node;let t=this.recursiveSet(_,this,void 0,e);if(e.__node){if(!e.__node.tag)e.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(e.__node.tag)){let i=new d(e,this,this);this.set(i.__node.tag,i);for(let s in this.__node.loaders)typeof this.__node.loaders[s]=="object"?(this.__node.loaders[s].init&&this.__node.loaders[s](i,parent,this,this.__node.tree,e),this.__node.loaders[s].connected&&i.__addOnconnected(this.__node.loaders[s].connect),this.__node.loaders[s].disconnected&&i.__addOndisconnected(this.__node.loaders[s].disconnect)):typeof this.__node.loaders=="function"&&this.__node.loaders[s](i,this,this,e,e,e.__node.tag);i.__listeners&&(t[i.__node.tag]=i.__listeners)}}else e.__listeners&&this.setListeners(e.__listeners);return this.setListeners(t),_};this.setLoaders=(e,_)=>(_?this.__node.loaders=e:Object.assign(this.__node.loaders,e),this.__node.loaders);this.add=(e,_)=>{let t={};typeof _=="string"&&(_=this.get(_));let i;if(typeof e=="function"?b(e)?e.prototype instanceof d?(e=e.prototype.constructor(e,_,this),i=!0):e=new e:e={__operator:e}:typeof e=="string"&&(e=this.__node.tree[e]),i||(e=Object.assign({},e)),e.__node||(e.__node={}),e.__node.initial=e,typeof e=="object"&&(!e?.__node?.tag||!this.get(e.__node.tag))){let s;i?s=e:s=new d(e,_,this),this.set(s.__node.tag,s);for(let r in this.__node.loaders)typeof this.__node.loaders[r]=="object"?(this.__node.loaders[r].init&&this.__node.loaders[r](s,_,this,this.__node.tree,e,s.__node.tag),this.__node.loaders[r].connected&&s.__addOnconnected(this.__node.loaders[r].connect),this.__node.loaders[r].disconnected&&s.__addOndisconnected(this.__node.loaders[r].disconnect)):typeof this.__node.loaders=="function"&&this.__node.loaders[r](s,_,this,this.__node.tree,e,s.__node.tag);return this.__node.tree[s.__node.tag]=e,s.__listeners&&(t[s.__node.tag]=s.__listeners),s.__children&&(s.__children=Object.assign({},s.__children),this.recursiveSet(s.__children,s,t,s.__children)),this.setListeners(t),s.__callConnected(),s}};this.recursiveSet=(e,_,t={},i)=>{let s=Object.getOwnPropertyNames(i);for(let r of s){if(r.includes("__"))continue;let o=i[r];if(Array.isArray(o))continue;let a;if(typeof o=="function"?b(o)?(o=new o,o instanceof d&&(o=o.prototype.constructor(o,_,this),a=!0)):o={__operator:o}:typeof o=="string"?o=this.__node.tree[o]:typeof o=="boolean"&&(o=this.__node.tree[r]),typeof o=="object"){if(a||(o=Object.assign({},o)),o.__node||(o.__node={}),o.__node.tag||(o.__node.tag=r),o.__node.initial=e[r],this.get(o.__node.tag)&&!(_?.__node&&this.get(_.__node.tag+"."+o.__node.tag))||_?.__node&&this.get(_.__node.tag+"."+o.__node.tag))continue;let f;a?f=o:f=new d(o,_,this),this.set(f.__node.tag,f);for(let h in this.__node.loaders)this.__node.loaders[h](f,_,this,e,e[r],r);e[r]=f,this.__node.tree[f.__node.tag]=o,f.__listeners&&(t[f.__node.tag]=f.__listeners),f.__children&&(f.__children=Object.assign({},f.__children),this.recursiveSet(f.__children,f,t,f.__children)),f.__callConnected()}}return t};this.remove=(e,_=!0)=>{if(this.unsubscribe(e),typeof e=="string"&&(e=this.get(e)),e instanceof d){this.delete(e.__node.tag),delete this.__node.tree[e.__node.tag],_&&this.clearListeners(e),e.__callDisconnected();let t=i=>{for(let s in i)this.unsubscribe(i[s]),this.delete(i[s].__node.tag),delete this.__node.tree[i[s].__node.tag],this.delete(s),delete this.__node.tree[s],i[s].__node.tag=i[s].__node.tag.substring(i[s].__node.tag.lastIndexOf(".")+1),_&&this.clearListeners(i[s]),i[s].__callDisconnected(),i[s].__children&&t(i[s].__children)};e.__children&&t(e.__children)}return e?.__node.tag&&e?.__parent&&(delete e?.__parent,e.__node.tag=e.__node.tag.substring(e.__node.tag.indexOf(".")+1)),e};this.run=(e,..._)=>{if(typeof e=="string"){let t=this.get(e);if(!t&&e.includes(".")){if(t=this.get(e.substring(0,e.lastIndexOf("."))),typeof t?.[e.substring(e.lastIndexOf(".")+1)]=="function")return t[e.substring(e.lastIndexOf(".")+1)](..._)}else if(t?.__operator)return t.__operator(..._)}if(e?.__operator)return e?.__operator(..._)};this.setListeners=e=>{for(let _ in e){let t=this.get(_);if(typeof e[_]=="object")for(let i in e[_]){let s=this.get(i),r;if(typeof e[_][i]!="object")e[_][i]={__callback:e[_][i]};else if(!e[_][i].__callback)for(let o in e[_][i]){typeof e[_][i][o]!="object"&&(e[_][i][o]={__callback:e[_][i][o]},e[_][i][o].__callback===!0&&(e[_][i][o].__callback=t.__operator));let a=this.get(o);if(a)if(a)r=this.subscribe(a,e[_][i][o].__callback,void 0,e[_][i].inputState,_,i),typeof t.__listeners[i][o]!="object"&&(t.__listeners[i][o]={__callback:e[_][i][o].__callback,inputState:e[_][i][o]?.inputState}),t.__listeners[i][o].sub=r;else{let f=i.substring(0,i.lastIndexOf("."));a=this.get(f),s&&(r=this.subscribe(a,e[_][i][o].__callback,i.substring(i.lastIndexOf(".")+1),e[_][i][o].inputState,_,i),typeof t.__listeners[i][o]!="object"&&(t.__listeners[i][o]={__callback:e[_][i][o].__callback,inputState:e[_][i][o]?.inputState}),t.__listeners[i][o].sub=r)}}if(e[_][i].__callback)if(e[_][i].__callback===!0&&(e[_][i].__callback=t.__operator),typeof e[_][i].__callback=="function"&&(e[_][i].__callback=e[_][i].__callback.bind(t)),typeof t.__listeners!="object"&&(t.__listeners={}),s)r=this.subscribe(s,e[_][i].__callback,void 0,e[_][i].inputState,_,i),typeof t.__listeners[i]!="object"&&(t.__listeners[i]={__callback:e[_][i].__callback,inputState:e[_][i]?.inputState}),t.__listeners[i].sub=r;else{let o=i.substring(0,i.lastIndexOf("."));s=this.get(o),s&&(r=this.subscribe(s,e[_][i].__callback,i.substring(i.lastIndexOf(".")+1),e[_][i].inputState,_,i),typeof t.__listeners[i]!="object"&&(t.__listeners[i]={__callback:e[_][i].__callback,inputState:e[_][i]?.inputState}),t.__listeners[i].sub=r)}}}};this.clearListeners=(e,_)=>{if(typeof e=="string"&&(e=this.get(e)),e?.__listeners)for(let t in e.__listeners){if(_&&t!==_||typeof e.__listeners[t].sub!="number")continue;let i=this.get(t);if(i)if(e.__listeners[t].__callback)this.unsubscribe(i,e.__listeners[t].sub,void 0,e.__listeners[t].inputState);else for(let s in e.__listeners[t])this.unsubscribe(i,e.__listeners[t][s].sub,void 0,e.__listeners[t][s].inputState);else if(i=this.get(t.substring(0,t.lastIndexOf("."))),i)if(e.__listeners[t].__callback)this.unsubscribe(i,e.__listeners[t].sub,t.substring(t.lastIndexOf(".")+1),e.__listeners[t].inputState);else for(let s in e.__listeners[t])this.unsubscribe(i,e.__listeners[t][s].sub,t.substring(t.lastIndexOf(".")+1),e.__listeners[t][s].inputState);delete e.__listeners[t]}};this.get=e=>this.__node.nodes.get(e);this.set=(e,_)=>this.__node.nodes.set(e,_);this.delete=e=>this.__node.nodes.delete(e);this.getProps=(e,_)=>{if(typeof e=="string"&&(e=this.get(e)),e instanceof d){let t;_?t=Object.assign({},this.__node.tree[e.__node.tag]):(t=Object.assign({},e),delete t.__unsubscribe,delete t.__setOperator,delete t.__node,delete t.__subscribeState,delete t.__subscribe)}};this.subscribe=(e,_,t,i,s,r)=>{let o=e;e instanceof d||(o=this.get(e));let a;if(typeof _=="string")if(s){let f=this.get(s)?.[_];typeof f=="function"&&(_=f)}else _=this.get(_)?.__operator;if(o instanceof d){a=o.__subscribe(_,t,i,s,r);let f=()=>{o.__unsubscribe(a,t,i)};o.__addOndisconnected(f)}else if(typeof e=="string")if(this.get(e))if(_ instanceof d&&_.__operator){a=this.get(e).__subscribe(_.__operator,t,i,s,r);let f=()=>{this.get(e).__unsubscribe(a)};_.__addOndisconnected(f)}else(typeof _=="function"||typeof _=="string")&&(a=this.get(e).__subscribe(_,t,i,s,r),this.__node.state.getTrigger(this.get(e).__node.unique,a).source=e);else typeof _=="string"&&(_=this.__node.nodes.get(_).__operator),typeof _=="function"&&(a=this.__node.state.subscribeTrigger(e,_));return a};this.unsubscribe=(e,_,t,i)=>e instanceof d?e.__unsubscribe(_,t,i):this.get(e)?.__unsubscribe(_,t,i);this.setState=e=>{this.__node.state.setState(e)};this.init(e)}};function y(n,e){for(let _ in e)e[_]?.constructor.name==="Object"&&!Array.isArray(e[_])?n[_]?.constructor.name==="Object"&&!Array.isArray(n[_])?y(n[_],e[_]):n[_]=y({},e[_]):n[_]=e[_];return n}function O(n){var e=[],_=n;do{var t=Object.getOwnPropertyNames(_);t.forEach(function(i){e.indexOf(i)===-1&&e.push(i)})}while(_=Object.getPrototypeOf(_));return e}function A(n){let e=O(n),_={};for(let t of e)_[t]=n[t];return _}function b(n){return typeof n=="function"&&n.hasOwnProperty("prototype")&&!n.hasOwnProperty("arguments")}var G=(n,e,_)=>{n.__node.backward&&e instanceof d&&_.setListeners({[e.__node.tag]:{[n.__node.tag]:e}})},m=(n,e,_)=>{if(n.__operator&&!n.__node.looperSet){if(n.__node.looperSet=!0,typeof n.__node.delay=="number"){let t=n.__operator;n.__setOperator((...i)=>new Promise((s,r)=>{setTimeout(async()=>{s(await t(...i))},n.__node.delay)}))}else if(n.__node.frame===!0){let t=n.__operator;n.__setOperator((...i)=>new Promise((s,r)=>{requestAnimationFrame(async()=>{s(await t(...i))})}))}if(typeof n.__node.repeat=="number"||typeof n.__node.recursive=="number"){let t=n.__operator;n.__setOperator(async(...i)=>{let s=n.__node.repeat?n.__node.repeat:n.__node.recursive,r,o=async(a,...f)=>{for(;a>0;){if(n.__node.delay||n.__node.frame){t(...f).then(async h=>{n.__node.recursive?await o(a,h):await o(a,...f)});break}else r=await t(...i);a--}};return await o(s,...i),r})}if(n.__node.loop&&typeof n.__node.loop=="number"){let t=n.__operator;n.__setOperator((...s)=>{"looping"in n.__node||(n.__node.looping=!0),n.__node.looping&&(t(...s),setTimeout(()=>{n.__operator(...s)},n.__node.loop))}),n.__node.looping&&n.__operator();let i=s=>{s.__node.looping&&(s.__node.looping=!1)};n.__addOndisconnected(i)}}},N=(n,e,_)=>{if(n.__node.animate===!0||n.__animation){let t=n.__operator;n.__setOperator((...s)=>{"animating"in n.__node||(n.__node.animating=!0),n.__node.animating&&(typeof n.__animation=="function"?n.__animation(...s):t(...s),requestAnimationFrame(()=>{n.__operator(...s)}))}),(n.__node.animating||(!("animating"in n.__node)||n.__node.animating)&&n.__animation)&&setTimeout(()=>{requestAnimationFrame(n.__operator)},10);let i=s=>{s.__node.animating&&(s.__node.animating=!1)};n.__addOndisconnected(i)}},j=(n,e,_)=>{if(typeof n.__node.branch=="object"&&n.__operator&&!n.__node.branchApplied){let t=n.__operator;n.__node.branchApplied=!0,n.__operator=(...i)=>{let s=t(...i);for(let r in n.__node.branch){let o=()=>{typeof n.__node.branch[r].then=="function"?n.__node.branch[r].then(s):n.__node.branch[r].then instanceof d&&n.__node.branch[r].then.__operator?n.__node.branch[r].then.__operator(s):s=n.__node.branch[r].then};typeof n.__node.branch[r].if=="function"?n.__node.branch[r].if(s)&&o():n.__node.branch[r].if===s&&o()}return s}}if(n.__listeners){for(let t in n.__listeners)if(typeof n.__listeners[t]=="object"&&n.__listeners[t].branch&&!n.__listeners[t].branchApplied){let i=n.__listeners[t].callback;n.__listeners[t].branchApplied=!0,n.__listeners.callback=s=>{let r=()=>{typeof n.__listeners[t].branch.then=="function"?s=n.__listeners[t].branch.then(s):n.__listeners[t].branch.then instanceof d&&n.__listeners[t].branch.then.__operator?s=n.__listeners[t].branch.then.__operator(s):s=n.__listeners[t].branch.then};return typeof n.__listeners[t].branch.if=="function"?n.__listeners[t].branch.if(s)&&r():n.__listeners[t].branch.if===s&&r(),i(s)}}}},S=(n,e,_)=>{if(n.__listeners)for(let t in n.__listeners)typeof n.__listeners[t]=="object"&&n.__listeners[t].oncreate&&n.__listeners[t].callback(n.__listeners[t].oncreate)},x=(n,e,_)=>{if(n.__listeners)for(let t in n.__listeners)typeof n.__listeners[t]=="object"&&typeof n.__listeners[t].binding=="object"&&(n.__listeners.callback=n.__listeners.callback.bind(n.__listeners[t].binding))},q=(n,e,_)=>{if(n.__listeners){for(let t in n.__listeners)if(typeof n.__listeners[t]=="object"&&typeof n.__listeners[t].transform=="function"&&!n.__listeners[t].transformApplied){let i=n.__listeners[t].callback;n.__listeners[t].transformApplied=!0,n.__listeners.callback=s=>(s=n.__listeners[t].transform(s),i(s))}}},v=(n,e,_)=>{n.post&&!n.__operator?n.__setOperator(n.post):!n.__operator&&typeof n.get=="function"&&n.__setOperator(n.get),!n.get&&n.__operator&&(n.get=n.__operator),n.aliases&&n.aliases.forEach(t=>{_.set(t,n);let i=s=>{_.__node.nodes.delete(t)};n.__addOndisconnected(i)}),typeof _.__node.tree[n.__node.tag]=="object"&&n.get&&(_.__node.tree[n.__node.tag].get=n.get)},E={backprop:G,loop:m,animate:N,branching:j,triggerListenerOncreate:S,bindListener:x,transformListenerResult:q,substitute__operator:v};})(); diff --git a/dist/index.d.ts b/dist/index.d.ts index 07ec783e..e1885a32 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -1,22 +1,18 @@ -export * from './src/core/Graph'; -export * from './src/core/EventHandler'; -export * from './src/loaders'; -export * from './src/services/utils'; -export { methodstrings } from './src/loaders/methodstrings'; -export * from './src/services/Service'; -export * from './src/services/remote/remote.routes'; -export * from './src/services/ecs/ECS.service'; -export { html, xml } from './src/loaders/html/html'; -export * from './src/loaders/html/html.loader'; -export { DOMElement, addCustomElement } from './src/loaders/html/DOMElement'; -export * from './src/loaders/html/wc.loader'; -export * from './src/services/e2ee/E2EE.service'; -export * from './src/services/http/HTTP.browser'; -export * from './src/services/sse/SSE.browser'; -export * from './src/services/wss/WSS.browser'; -export * from './src/services/webrtc/WebRTC.browser'; -export * from './src/services/worker/Worker.service'; -export * from './src/services/worker/ProxyListener'; -export * from './src/services/worker/WorkerCanvas'; -export * from './src/services/sessions/sessions.service'; -export * from './src/services/router/Router'; +export * from './Graph'; +export * from './loaders'; +export * from './services/Service'; +export * from './services/unsafe/Unsafe.service'; +export * from './services/ecs/ECS.service'; +export { DOMElement, addCustomElement } from './loaders/html/DOMElement'; +export * from './loaders/html/html.loader'; +export * from './services/e2ee/E2EE.service'; +export * from './services/http/HTTP.browser'; +export * from './services/sse/SSE.browser'; +export * from './services/wss/WSS.browser'; +export * from './services/webrtc/WebRTC.browser'; +export * from './services/worker/Worker.service'; +export * from './services/worker/ProxyListener'; +export * from './services/worker/WorkerCanvas'; +export * from './services/worker/Subprocess'; +export * from './services/sessions/sessions.service'; +export * from './services/router/Router'; diff --git a/dist/index.esm.js b/dist/index.esm.js index 25d48469..0ef71283 100644 --- a/dist/index.esm.js +++ b/dist/index.esm.js @@ -1 +1 @@ -var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i2=l-1;i2>=0;i2--){run(this.triggers[statesubKey][i2].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i2=l-1;i2>=0;i2--){fn(this.triggers[key][i2])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.sub===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps2=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys2=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys2){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps2();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys2=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys2.push(...nonArrowFunctions);keys2=keys2.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys2){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys2=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t2=>{for(const key in t2){this.unsubscribe(t2[key]);this.delete(t2[key].__node.tag);delete this.__node.roots[t2[key].__node.tag];this.delete(key);delete this.__node.roots[key];t2[key].__node.tag=t2[key].__node.tag.substring(t2[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t2[key])}t2[key].__callDisconnected();if(t2[key].__children){recursiveRemove(t2[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i2)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i2]={__callback:inp=>{return inp},__args:void 0,idx:i2}}else if(typeof a==="string"){args[i2]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i2}}else if(typeof a==="function"){let fn2=a;args[i2]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i2}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i2}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i2}}else{input={__callback:input,__args:void 0,idx:i2}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i2}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i2}}}return input};args[i2]=recursivelyCreateCallback(a)}else{let arg=a;args[i2]={__callback:()=>{return arg},__args:void 0,idx:i2}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i2=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i2,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function getFnParamNames(fn){if(typeof fn!=="string")fn=fn.toString();const arrowMatch=fn.match(/\(?[^]*?\)?\s*=>/);if(arrowMatch)return arrowMatch[0].replace(/[()\s]/gi,"").replace("=>","").split(",");const match=fn.match(/\([^]*?\)/);return match?match[0].replace(/[()\s]/gi,"").split(","):[]}var getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}function reconstructObject(json="{}"){try{let parsed=typeof json==="string"?JSON.parse(json):json;const parseObj=obj=>{for(const prop in obj){if(typeof obj[prop]==="string"){let funcParsed=parseFunctionFromText(obj[prop]);if(typeof funcParsed==="function"){obj[prop]=funcParsed}}else if(typeof obj[prop]==="object"){parseObj(obj[prop])}}return obj};return parseObj(parsed)}catch(err){console.error(err);return void 0}}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs3(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value==="function"?value.toString():value,path.join("."))}}}return typeof value==="function"?value.toString():value}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str2;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str2=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str2=properties.toString();else if(typeof properties==="string")str2=properties;if(str2){if(connection.run)return connection.run("setNode",[str2]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str2},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str2}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(template);if(node){nodeTemplates[node.__node.tag]=template;return node.__node?.tag}else return false}else return false},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str2=recursivelyStringifyFunctions(properties);return str2},getListenerJSON:function(){const triggers=this.__node.state.triggers;let result={};for(const key in triggers){triggers[key].forEach(trigger=>{let t2=trigger;if(!result[t2.target])result[t2.target]={};let l=t2.source+(t2.key?"."+t2.key:"");result[t2.target][l]={__callback:t2.__callback};if(t2.__args)result[t2.target][l].__args=t2.__args;if(t2.subInput)result[t2.target][l].subInput=t2.subInput})}return result},makeRootTransferrable:function(){let roots={};for(const r in this.__node.graph.__node.roots){let properties=this.__node.graph.__node.roots[r];if(typeof properties==="function"){roots[r]=properties.toString()}else if(typeof properties!=="object"){roots[r]=properties}else{roots[r]={};let keys2=Object.getOwnPropertyNames(properties).filter(v=>!objProps2.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter(v=>!objProps2.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(typeof properties[key]==="function"){roots[r][key]=properties[key].toString()}else if(typeof properties[key]==="object")roots[r][key]=stringifyWithFunctionsAndCircularRefs(properties[key]);else roots[r][key]=properties[key]}}}return roots},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key of properties){if(typeof node[key]==="function"){let str2=node[key].toString();let isNative=str2.indexOf("[native code]")>-1;result[key]={type:"function",args:getFnParamNames(node[key]),native:isNative}}else result[key]=typeof node[key]}return result}return void 0},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]?.type==="function"){if(props[key].native||props[key].args){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{proxy[key]=()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})}}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};if(connection.run)return connection.run("receiveClass",[str2,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str2,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str2,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str2=fn.toString();let message={route:"setNode",args:[str2,fnName]};if(connection.run)return connection.run("setNode",[str2,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str2,fnName]},void 0);return new Promise(r=>r(fnName))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str2,fnName]}));return new Promise(r=>r(fnName))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var objProps2=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var ECSService=class extends Service{entities={};systems={};entityMap=new Map;entityKeyMap=new Map;order=[];animating=false;entityCt=0;systemCt=0;constructor(options){super(options);this.load(this);if(options?.systems)for(const key in options.systems){this.addSystem(options.systems[key],void 0,void 0,void 0,void 0,options.order)}if(options?.entities){for(const key in options.entities){this.addEntity(options.entities[key],options.entities[key].components)}}}updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};stop=()=>{this.animating=false};start=filter=>{this.animateEntities(filter)};addEntities=(prototype,components={},count=1)=>{let i2=0;let newEntities={};while(i2{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};removeEntities(entities){if(!Array.isArray(entities))entities=Object.keys(entities);entities.forEach(t2=>{this.removeEntity(t2)})}removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};bufferValues=(entities,property,keys2,buffer)=>{if(!Array.isArray(keys2)&&typeof keys2==="object")keys2=Object.keys(keys2);if(!buffer){let entkeys=Object.keys(entities);if(keys2)buffer=new Float32Array(entkeys.length*keys2.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys2=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys2.length)}else buffer=new Float32Array(entkeys.length)}}let i2=0;for(const key in entities){if(entities[key][property]){if(keys2){for(let j=0;j{combinedHTML+=string;if(args[i2]instanceof HTMLElement){combinedHTML+=``}else if(args[i2]!==void 0){combinedHTML+=args[i2]}};strings.forEach(withStr);template.innerHTML=combinedHTML;let dummyNodes=Array.from(template.content.querySelectorAll(`#${rand}`));const withArg=(arg,i2)=>{if(arg instanceof HTMLElement){let dummyNode=dummyNodes[i2];if(dummyNode){dummyNode.parentNode.replaceChild(arg,dummyNode)}}};args.forEach(withArg);if(elm){elm.appendChild(template.content);return elm}return template.content}}function xml(strings,...args){return function append(elm,namespace="http://www.w3.org/1999/xhtml"){let parser=new DOMParser;let serializer=new XMLSerializer;let xmlDoc=parser.parseFromString('',"application/xml");let template=xmlDoc.createElement("template");xmlDoc.documentElement.appendChild(template);for(let i2=0;i2{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if(node.tagName||node.__element){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var dummy=html``;var DOMElement=class extends HTMLElement{useShadow=false;FRAGMENT;STYLE;attachedShadow=false;static get tag(){return this.name.toLowerCase()+"-"}obsAttributes=["props","options","onchanged","onresize","ondelete","oncreate","template"];props={};static addElement(tag=this.tag,cls=this,extend=void 0){addCustomElement(cls,tag,extend)}attributeChangedCallback=(name2,old,val)=>{if(name2==="onchanged"){let onchanged=val;if(typeof onchanged==="string")onchanged=parseFunctionFromText2(onchanged);if(typeof onchanged==="function"){this.onchanged=onchanged;this.state.data.props=this.props;this.state.unsubscribeTrigger("props");this.state.subscribeTrigger("props",this.onchanged);let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)})}}else if(name2==="onresize"){let onresize=val;if(typeof onresize==="string")onresize=parseFunctionFromText2(onresize);if(typeof onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this.props,this)};this.onresize=onresize;window.addEventListener("resize",this.ONRESIZE)}}else if(name2==="ondelete"){let ondelete=val;if(typeof ondelete==="string")ondelete=parseFunctionFromText2(ondelete);if(typeof ondelete==="function"){this.ondelete=()=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");if(ondelete)ondelete(this.props,this)}}}else if(name2==="oncreate"){let oncreate=val;if(typeof oncreate==="string")oncreate=parseFunctionFromText2(oncreate);if(typeof oncreate==="function"){this.oncreate=oncreate}}else if(name2==="renderonchanged"){let rpc=val;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!=false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}else if(name2==="props"){let newProps=val;if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props})}else if(name2==="template"){let template=val;this.template=template;this.render(this.props);let created=new CustomEvent("created",{detail:{props:this.props}});this.dispatchEvent(created)}else{let parsed=val;if(name2.includes("eval_")){name2=name2.split("_");name2.shift();name2=name2.join();parsed=parseFunctionFromText2(val)}else if(typeof val==="string"){try{parsed=JSON.parse(val)}catch(err){parsed=val}}this[name2]=parsed;if(name2!=="props"&&this.props)this.props[name2]=parsed}};connectedCallback(){if(!this.props)this.props={};let newProps=this.getAttribute("props");if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props});Array.from(this.attributes).forEach(att=>{let name2=att.name;let parsed=att.value;if(name2.includes("eval_")||name2.includes("()")){if(name2.includes("eval_"))name2=name2.split("_");else if(name2.includes("()"))name2=name2.substring(0,name2.indexOf("("));name2.shift();name2=name2.join();parsed=parseFunctionFromText2(att.value)}else if(typeof att.value==="string"){try{parsed=JSON.parse(att.value)}catch(err){parsed=att.value}}if(!this[name2]){Object.defineProperties(this,att,{value:parsed,writable:true,get(){return this[name2]},set(val){this.setAttribute(name2,val)}})}this[name2]=parsed;if(name2!=="props")this.props[name2]=parsed;this.obsAttributes.push(name2)});let resizeevent=new CustomEvent("resized",{detail:{props:this.props,self:this}});let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});let deleted=new CustomEvent("deleted",{detail:{props:this.props,self:this}});let created=new CustomEvent("created",{detail:{props:this.props,self:this}});this.render(this.props);this.dispatchEvent(created);this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)});if(typeof this.onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this,this.props);this.dispatchEvent(resizeevent)};window.addEventListener("resize",this.ONRESIZE)}if(typeof this.ondelete==="function"){let ondelete=this.ondelete;this.ondelete=(props=this.props)=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");this.dispatchEvent(deleted);ondelete(this,props)}}if(typeof this.onchanged==="function"){this.state.data.props=this.props;this.state.subscribeTrigger("props",this.onchanged)}if(this.renderonchanged){let rpc=this.renderonchanged;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!==false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}}constructor(){super()}delete=()=>{this.remove();if(typeof this.ondelete==="function")this.ondelete(this.props)};render=(props=this.props)=>{const t2=document.createElement("template");let usingHTMLFunction=this.template.prototype?.constructor?.name==dummy.prototype.constructor.name;if(typeof this.template==="function"){if(usingHTMLFunction){this.template(t2.content)}else this.templateResult=this.template(this,props)}else this.templateResult=this.template;if(this.styles)this.templateResult=`${this.templateResult}`;if(!usingHTMLFunction){if(typeof this.templateResult==="string")t2.innerHTML=this.templateResult;else if(this.templateResult instanceof HTMLElement||this.templateResult instanceof DocumentFragment){if(this.templateResult.parentNode){this.templateResult.parentNode.removeChild(this.templateResult)}t2.content.appendChild(this.templateResult)}}const fragment=t2.content;if(this.FRAGMENT){if(this.useShadow){if(this.STYLE)this.shadowRoot.removeChild(this.STYLE);this.FRAGMENT.forEach(c=>{this.shadowRoot.removeChild(c)})}else this.FRAGMENT.forEach(c=>{this.removeChild(c)})}if(this.useShadow){if(!this.attachedShadow){this.attachShadow({mode:"open"}).innerHTML="";this.attachedShadow=true}if(this.styles){let style=document.createElement("style");style.textContent=this.styles;this.shadowRoot.prepend(style);this.STYLE=style}let len=fragment.childNodes.length;this.shadowRoot.prepend(fragment);this.FRAGMENT=Array.from(this.shadowRoot.childNodes).slice(0,len)}else{let len=fragment.childNodes.length;this.prepend(fragment);this.FRAGMENT=Array.from(this.childNodes).slice(0,len)}let rendered=new CustomEvent("rendered",{detail:{props:this.props,self:this}});this.dispatchEvent(rendered);if(this.oncreate)this.oncreate(this,props)};state={pushToState:{},data:{},triggers:{},setState(updateObj){Object.assign(this.pushToState,updateObj);if(Object.keys(this.triggers).length>0){for(const prop of Object.getOwnPropertyNames(this.triggers)){if(this.pushToState[prop]){this.data[prop]=this.pushToState[prop];delete this.pushToState[prop];this.triggers[prop].forEach(obj=>{obj.onchanged(this.data[prop])})}}}return this.pushToState},subscribeTrigger(key,onchanged=res=>{}){if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({idx:l,onchanged});return this.triggers[key].length-1}else return void 0},unsubscribeTrigger(key,sub){let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.idx===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);return true}}},subscribeTriggerOnce(key=void 0,onchanged=value=>{}){let sub;let changed=value=>{onchanged(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)}}};function addCustomElement(cls,tag,extend=null){try{if(extend){if(tag)window.customElements.define(tag,cls,{extends:extend});else window.customElements.define(cls.name.toLowerCase()+"-",cls,{extends:extend})}else{if(tag)window.customElements.define(tag,cls);else window.customElements.define(cls.name.toLowerCase()+"-",cls)}}catch(err){}}function parseFunctionFromText2(method){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf(")");return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;try{if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch(err){newFunc=(0,eval)(method)}}}}catch(err){}return newFunc}var wchtmlloader=(node,parent,graph,roots,properties,key)=>{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if((node.tagName||node.__element)&&!node.__props&&!node.__template){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}else if(typeof node.__css==="string"){node.__template+=``;delete node.__css}const registerElement=(node2,tagNameOverride)=>{if(isNativeClass(node2))node2=new node2;else if(typeof node2==="function"&&!node2.__node)node2=node2();class CustomElement extends DOMElement{props=node2.props;styles=node2.__css;useShadow=node2.useShadow;template=node2.__template;oncreate=node2.__onrender;onresize=node2.__onresize;ondelete=node2.__onremove;renderonchanged=node2.__renderonchanged}if(tagNameOverride?.includes("-"))node2.tagName=tagNameOverride;else if(node2.__element)node2.tagName=node2.__element;if(!node2.tagName)node2.tagName=`element${Math.floor(Math.random()*1e15)}-`;CustomElement.addElement(node2.tagName)};if("__components"in node){if(Array.isArray(node.__components))node.__components.forEach(c=>registerElement(c));else Object.entries(node.__components).forEach(([k,c])=>registerElement(c,k.includes("-")?k:void 0))}if("__template"in node){if(typeof node.__renderonchanged==="function"){let renderonchanged=node.__renderonchanged;node.__renderonchanged=element=>{renderonchanged.call(element.node,element)}}registerElement(node);node.__props=document.createElement(node.tagName);let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}}}else if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender&&!(node.__props instanceof DOMElement)&&!node.__template)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return new sjcl.hash.sha256().update(a).finalize()};sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=sjcl_default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};static generateSecret(){return sjcl_default.codec.base64.fromBits(sjcl_default.random.randomWords(8,10))}encrypt(message,key){message=sjcl_default.encrypt(key,message).cipher;return message}decrypt(message,key){message=sjcl_default.decrypt(key,message);return message}encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=sjcl_default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message}};var HTTPfrontend=class _HTTPfrontend extends Service{name="http";fetchProxied=false;listening={};constructor(options,path,fetched){super(options);this.load(this);this.listen(path,fetched)}static request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};GET=(url2="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url:url2,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{let obj=message;if(typeof obj==="object"&&!obj.byteLength){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url2);return this.POST(message,url2)};transponder=(url2,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url:url2,data:message,responseType:type,onload:ev=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}}};var SSEfrontend=class extends Service{name="sse";eventsources={};connections={eventsources:this.eventsources};constructor(options){super(options);this.load(this)}openSSE=options=>{let source=new EventSource(options.url);let sse={source,type:"eventsource",...options};if(!("keepState"in options))options.keepState=true;if(!options.events)options.events={};let close;if(options.events.close){close=options.events.close}options.events.close=ev=>{if(sse.onclose)sse.onclose(ev,sse);if(close)close(ev,sse);delete this.eventsources[options.url]};let open;if(options.events.open){open=options.events.open}options.events.open=ev=>{if(sse.onopen)sse.onopen(ev,sse);if(open)open(ev,sse)};let error;if(options.events.error){error=options.events.error}options.events.error=ev=>{if(sse.onerror)sse.onerror(ev,sse);if(error)error(ev,sse)};let message;if(options.events.message){message=options.events.message}if(!sse.onmessage){sse.onmessage=(ev,sse2)=>{let data=ev.data;if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"&&sse2){sse2._id=data.args;options.events.message=(e,sse3)=>{const result2=this.receive(e.data,sse3);if(options.keepState)this.setState({[options.url]:e.data})}}}}}const result=this.receive(ev.data,sse2);if(options.keepState)this.setState({[options.url]:data})}}options.events.message=ev=>{if(sse.onmessage)sse.onmessage(ev,sse);if(message)message(ev,sse)};if(!options.events.error)options.events.error=(ev,sse2)=>{this.terminate(sse2);delete this.eventsources[options.url]};if(options.events){if(!options.evoptions)options.evoptions=false;for(const key in options.events){if(typeof options.events[key]!=="function"){options.events[key]=ev=>{const result=this.receive(ev.data,sse);if(options.keepState)this.setState({[options.url]:result})}}else{let l=options.events[key];options.events[key]=ev=>{l(ev,sse)}}source.addEventListener(key,options.events[key],options.evoptions)}}let send=message2=>{return this.transmit(message2,options.url)};let request=(message2,method,sessionId)=>{return this.request(message2,options.url,method,sessionId)};let post=(route,args,method)=>{let message2={route,args};if(method)message2.method=method;return this.transmit(message2,options.url)};let run=(route,args,method,sessionId)=>{return this.request({route,args},options.url,method,sessionId)};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSSE(route,options.url,callback,args,key,subInput,sse._id)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options.url)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;this.eventsources[options.url]=sse;return sse};open=this.openSSE;POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="number"||typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{return this.POST(message,url2,"json")};request=(message,url2,method,sessionId)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,url2,callbackId,sessionId]};if(method)req.method=method;let evs=this.eventsources[url2].source;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){evs.removeEventListener("message",onmessage);res(data.args)}}};evs.addEventListener("message",onmessage);this.POST(message,url2,"json")})};runRequest=(message,url2,callbackId,sessionId)=>{let res=this.receive(message);if(url2){if(res instanceof Promise){res.then(r=>{let message2={args:r,callbackId,sessionId};this.POST(message2,url2,"json")})}else{let message2={args:res,callbackId,sessionId};this.POST(message2,url2,"json")}}return res};subscribeSSE=(route,url2,args,key,subInput)=>{if(this.restrict?.[route])return void 0;return this.subscribe(route,res=>{this.POST(res,url2,"json")},args,key,subInput)};subscribeToSSE=(route,url2,callback,args,key,subInput,sessionId)=>{if(url2){this.__node.state.subscribeEvent(url2,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[url2]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.eventsources[url2].run("subscribeSSE",[route,url2,args,key,subInput,sessionId])}};terminate=sse=>{if(typeof sse==="string"){let str2=sse;sse=this.eventsources[sse];delete this.eventsources[str2]}if(!sse)return;if(typeof sse==="object"){if(sse.source){sse=sse.source}if(sse instanceof EventSource){if(sse.readyState!==2)sse.close()}}}};var WSSfrontend=class extends Service{name="wss";sockets={};connections={sockets:this.sockets};constructor(options){super(options);this.load(this)}loadWebSocketRoute=node=>{let wsInfo=this.openWS(node);if(!wsInfo.__ondisconnected){wsInfo.__addOndisconnected(()=>{wsInfo.terminate()})}if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.post(node.callback,args);else return wsInfo.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.send(args);else return wsInfo.request(args)}}}if(!node.__ondisconnected){let ondelete=rt=>{rt?.terminate()};node.__addOndisconnected(ondelete)}return wsInfo};socketloader={"websockets":(node,parent,graph,roots)=>{node._id=node.__node.tag;let ws=this.loadWebSocketRoute(node);Object.assign(node,ws);if(parent&&parent.type==="socket"){let parentWs=this.sockets[parent._id];if(node.parentRoute){parentWs.subscribe(node.parentRoute,node.__operator)}}}};openWS=(options={host:"localhost",port:7e3,path:void 0,protocol:"ws"})=>{let protocol=options.protocol;if(!protocol)protocol="ws";let address=`${protocol}://${options.host}`;if(!("keepState"in options))options.keepState=true;if(options.port)address+=":"+options.port;if(options.path&&!options.path?.startsWith("/"))address+="/";if(options.path)address+=options.path;if(this.sockets[address]?.socket){if(this.sockets[address].socket.readyState===this.sockets[address].socket.OPEN)this.sockets[address].socket.close()}const socket=new WebSocket(address);if(!options.onmessage){if(!options._id){options.onmessage=(data,ws,wsinfo)=>{if(data){if(typeof data==="string"){if(options.debug){console.log("Message from ",address,": ",data)}let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;options.onmessage=(data2,ws2,wsinfo2)=>{if(options.debug){console.log("Message from ",address,": ",data2)}this.receive(data2);if(options.keepState){this.setState({[address]:data2})}}}}}}let res=this.receive(data);if(options.keepState)this.setState({[address]:data})}}else{options.onmessage=(data,ws,wsinfo)=>{if(options.debug){console.log("Message from ",socket.url,": ",data)}this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}}}}if(options.onmessage){socket.addEventListener("message",ev=>{this.sockets[address].onmessage(ev.data,socket,this.sockets[address])})}socket.addEventListener("open",ev=>{if(this.sockets[address].onopen)this.sockets[address].onopen(ev,socket,this.sockets[address])});socket.addEventListener("close",ev=>{let obj=this.sockets[address];let onclose=obj.onclose;delete this.sockets[address];this.remove(address);if(onclose)onclose(ev,socket,obj)});socket.addEventListener("error",ev=>{if(this.sockets[address].onerror)this.sockets[address].onerror(ev,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},this.sockets[address]._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,this.sockets[address]._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSocket(route,this.sockets[address]._id,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(address)};Object.assign(options,{type:"socket",socket,address,send,post,run,request,subscribe,unsubscribe,terminate});if(!(options instanceof GraphNode)){let node=this.add(options);node.__addOndisconnected(function(){terminate()});options=node}this.sockets[address]=options;return options};open=this.openWS;transmit=(data,ws)=>{if(typeof data==="object"&&(data?.route||data?.node||typeof data.arrayBuffer!=="function"&&typeof data.byteLength!=="number")||typeof data==="number")data=JSON.stringify(data);if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}if(ws instanceof WebSocket&&ws?.readyState===1)ws.send(data);return true};terminate=ws=>{let str2;if(!ws){let keys2=Object.keys(this.sockets);for(const key in keys2){this.terminate(key)}}else if(typeof ws==="string"){str2=ws;for(const k in this.sockets){if(k.includes(ws)||this.sockets[k]._id===k){ws=this.sockets[k].socket;break}}}if(ws instanceof WebSocket){if(ws.readyState===ws.OPEN)ws.close();if(this.get(str2?str2:ws.url))this.remove(str2?str2:ws.url)}return true};request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(typeof ws==="string"){for(const s in this.sockets){if(s===ws||this.sockets[s]._id===ws){ws=this.sockets[s].socket;break}}}if(ws){if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))}}return res};subscribeSocket=(route,socket,args,key,subInput)=>{if(this.restrict?.[route])return void 0;if(typeof socket==="string"&&this.sockets[socket]){socket=this.sockets[socket].socket}if(typeof socket==="object"){return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},args,key,subInput)}};subscribeToSocket=(route,socketId,callback,args,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeEvent(socketId,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[socketId]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,args,key,subInput]})}}};var WebRTCfrontend=class extends Service{name="webrtc";rtc={};unanswered={};iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun1.l.google.com:19302"]},{urls:["stun:stun2.l.google.com:19302"]},{urls:["stun:stun3.l.google.com:19302"]},{urls:["stun:stun4.l.google.com:19302"]}];connections={rtc:this.rtc};constructor(options,iceServers){super(options);if(iceServers)this.iceServers=iceServers;this.load(this)}openRTC=async options=>{if(!options)options={};if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(!options.config)options.config={iceServers:this.iceServers};if(!this.rtc[options._id]){let rtc=new RTCPeerConnection(options.config);if(!options.channels)options.channels={"data":true};let firstChannel;for(const key in options.channels){firstChannel=key;break}let send=message=>{return this.transmit(message,options._id,options.channels[firstChannel])};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options._id,options.channels[firstChannel])};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let subscribe=(route,callback,args,key,subInput,channelId)=>{return this.subscribeToRTC(route,options._id,channelId?channelId:firstChannel,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.rtc[options._id]={rtc,_id:options._id,request,run,post,send,subscribe,unsubscribe,terminate,graph:this,...options};const setMessageChannelHandle=channel=>{if(!this.rtc[options._id].ondata){this.rtc[options._id].ondata=mev=>{this.receive(mev.data,channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})};channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}else{channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}};if(this.rtc[options._id].channels){for(const channel in this.rtc[options._id].channels){if(this.rtc[options._id].channels[channel]instanceof RTCDataChannel){}else if(typeof this.rtc[options._id].channels[channel]==="object"){this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel,this.rtc[options._id].channels[channel])}else{this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel)}setMessageChannelHandle(this.rtc[options._id].channels[channel])}}rtc.ontrack=ev=>{if(!this.rtc[options._id].receivers)this.rtc[options._id].receivers=[];this.rtc[options._id].receivers.push(ev.receiver);if(!this.rtc[options._id].streams)this.rtc[options._id].streams=[];this.rtc[options._id].streams.push(...ev.streams);let rlength=this.rtc[options._id].receivers.length;let slength=this.rtc[options._id].streams.length;ev.streams.forEach(s=>{s.addEventListener("removetrack",ev2=>{this.rtc[options._id].receivers[rlength]=void 0;this.rtc[options._id].streams[slength]=void 0;if(this.rtc[options._id].removetrack)this.rtc[options._id].removetrack(ev2)})});if(this.rtc[options._id].ontrack)this.rtc[options._id].ontrack(ev)};rtc.ondatachannel=ev=>{this.rtc[options._id].channels[ev.channel.label]=ev.channel;setMessageChannelHandle(ev.channel);if(this.rtc[options._id].ondatachannel)this.rtc[options._id].ondatachannel(ev)};rtc.onicecandidate=ev=>{if(this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate(ev)};rtc.onicecandidateerror=ev=>{if(this.rtc[options._id].onicecandidateerror)this.rtc[options._id].onicecandidateerror(ev)};let initialOffer=this.rtc[options._id].description===void 0;rtc.onnegotiationneeded=async ev=>{if(!initialOffer){const offer=await rtc.createOffer(this.rtc[options._id].offer);if(rtc.signalingState!="stable")return;await rtc.setLocalDescription(offer);if(this.rtc[options._id].onnegotiationneeded)this.rtc[options._id].onnegotiationneeded(ev,rtc.localDescription)}};rtc.oniceconnectionstatechange=ev=>{if(this.rtc[options._id].oniceconnectionstatechange)this.rtc[options._id].oniceconnectionstatechange(ev)};rtc.onconnectionstatechange=ev=>{if(this.rtc[options._id].onconnectionstatechange)this.rtc[options._id].onconnectionstatechange(ev)};rtc.addEventListener("connectionstatechange",ev=>{if(rtc.connectionState==="closed"||rtc.connectionState==="failed"){if(this.rtc[options._id].onclose){this.rtc[options._id].onclose(this.rtc[options._id])}delete this.rtc[options._id]}});if(!this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].candidates)this.rtc[options._id].candidates={};this.rtc[options._id].candidates[`candidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};if(!options.description)return await new Promise((res,rej)=>{this.rtc[options._id].rtc.createOffer(options.offer).then(offer=>this.rtc[options._id].rtc.setLocalDescription(offer)).then(()=>{initialOffer=false;res(this.rtc[options._id])})})}else{Object.assign(this.rtc[options._id],options)}if(options.description){this.rtc[options._id].polite=true;await this.negotiateCall(options._id,options.description,true)}if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);this.rtc[options._id].rtc.addIceCandidate(candidate).catch(console.error)}}return this.rtc[options._id]};open=this.openRTC;addIceCandidate=(rtc,candidate)=>{if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof candidate==="string")candidate=JSON.parse(decodeURIComponent(candidate));if(rtc&&rtc.remoteDescription)return rtc.addIceCandidate(candidate)};receiveCallInformation=async options=>{if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(this.rtc[options._id]){if(options.candidates){for(const key in options.candidates)this.addIceCandidate(this.rtc[options._id].rtc,options.candidates[key]);delete options.candidates}Object.assign(this.rtc[options._id],options)}else if(this.unanswered[options._id]){this.recursivelyAssign(this.unanswered[options._id],options)}else this.unanswered[options._id]=options;return options._id};answerCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return this.openRTC(options)};rejectCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return true};negotiateCall=async(rtc,description,polite)=>{if(typeof rtc==="string"){if(polite===void 0)polite=this.rtc[rtc].description!==void 0;rtc=this.rtc[rtc].rtc}if(typeof description==="string")description=new RTCSessionDescription(JSON.parse(decodeURIComponent(description)));if(description.type==="offer"&&rtc.signalingState!=="stable"){if(!polite)return;await Promise.all([rtc.setLocalDescription({type:"rollback"}),rtc.setRemoteDescription(description)]);return encodeURIComponent(JSON.stringify(rtc.localDescription))}else{await rtc.setRemoteDescription(description)}if(description.type=="offer"){await rtc.setLocalDescription(await rtc.createAnswer());return encodeURIComponent(JSON.stringify(rtc.localDescription))}};createOffer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc].rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createOffer(options.offer).then(offer=>rtc.setLocalDescription(offer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}createAnswer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createAnswer(options.answer).then(answer=>rtc.setLocalDescription(answer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}answerPeer=(rtc,options)=>{if(typeof rtc==="string"){let cpy=Object.assign(this.rtc[rtc],options);delete cpy.description;delete cpy.candidates;Object.assign(this.rtc[rtc],cpy);rtc=this.rtc[rtc]?.rtc}if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(typeof options.description==="string"){options.description=JSON.parse(decodeURIComponent(options.description))}const description=new RTCSessionDescription(options.description);rtc.setRemoteDescription(description).then(()=>{if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);if(this.rtc[options._id])this.rtc[options._id].candidates[prop]=options.candidates[prop];rtc.addIceCandidate(candidate).catch(console.error)}}if(description.type==="offer"){this.rtc[options._id].rtc.createAnswer(options.answer).then(a=>{this.rtc[options._id].rtc.setLocalDescription(a)})}res(this.rtc[options._id]?this.rtc[options._id]:rtc)}).catch(rej)})};createStream=options=>{let stream=new MediaStream;for(const key in options){let track=options[key].track;if(!(track instanceof MediaStreamTrack)&&typeof track==="object"){track=new MediaStreamTrack;track.applyConstraints(options[key].track);stream.addTrack(track)}if(track instanceof MediaStreamTrack){stream.addTrack(track);track.onmute=options[key].onmute;track.onunmute=options[key].onunmute;track.onended=options[key].onended}}return stream};addUserMedia=(rtc,options={audio:true,video:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560}]}},info)=>{return new Promise(async(res,rej)=>{let RTCRtpSenders=[];let stream=await navigator.mediaDevices.getUserMedia(options);if(stream){let tracks=stream.getTracks();tracks.forEach(track=>{let sender=rtc.addTrack(track,stream);if(track.kind==="video"&&info){info.videoSender=sender;info.videoStream=stream}if(track.kind==="audio"&&info){info.audioSender=sender;info.audioStream=stream}RTCRtpSenders.push(sender)});let str2=stream;if(info)info.senders=info.senders?[...info.senders,...RTCRtpSenders]:RTCRtpSenders;res(str2)}})};addTrack=(rtc,track,stream)=>{return rtc.addTrack(track,stream)};removeTrack=(rtc,sender)=>{rtc.removeTrack(sender);return true};addDataChannel=(rtc,name2,options)=>{return rtc.createDataChannel(name2,options)};enableAudio=async(call,audioOptions=true)=>{if(call.audioStream)this.disableAudio(call);let stream=await this.addUserMedia(call.rtc,{audio:audioOptions,video:false},call);if(audioOptions?.deviceId)call.audioSender.deviceId=audioOptions.deviceId;return stream};enableVideo=async(call,videoOptions={optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]},includeAudio=false)=>{if(call.videoStream)this.disableVideo(call);let stream=await this.addUserMedia(call.rtc,{audio:includeAudio,video:videoOptions?videoOptions:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]}},call);if(videoOptions?.deviceId)call.videoSender.deviceId=videoOptions.deviceId;if(includeAudio){if(includeAudio?.deviceId)call.audioSender.deviceId=includeAudio.deviceId;else if(videoOptions?.deviceId)call.audioSender.deviceId=videoOptions.deviceId}return stream};disableAudio(call){if(call.audioSender){call.senders?.find((s,i2)=>{if(call.audioStream?.getAudioTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.audioSender);call.audioSender=void 0}call.audioStream?.getTracks().forEach(track=>{if(track.kind==="audio")track.stop()});call.audioStream=void 0}disableVideo(call){if(call.videoSender){call.senders?.find((s,i2)=>{if(call.videoStream?.getVideoTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.videoSender);call.videoSender=void 0}call.videoStream?.getTracks().forEach(track=>{if(track.kind==="video")track.stop()});call.videoStream=void 0}transmit=(data,id,channel)=>{if(typeof data==="object"&&(data.route||data.node||!data.byteLength&&typeof data.arrayBuffer!=="function")||typeof data==="number")data=JSON.stringify(data);if(!channel&&id){let keys2=Object.keys(this.rtc[id].channels);if(keys2[0])channel=this.rtc[id].channels[keys2[0]]}if(typeof channel==="string"){if(id){channel=this.rtc[id].channels[channel]}else{for(const id2 in this.rtc){if(this.rtc[id2].channels[channel]instanceof RTCDataChannel)this.rtc[id2].channels[channel].send(data)}}}if(channel instanceof RTCDataChannel)channel.send(data);return true};terminate=rtc=>{let tx;if(typeof rtc==="string"){let room=this.rtc[rtc];delete this.rtc[rtc];if(room){tx=room.rtc}}else if(typeof rtc==="object"){tx=rtc.rtc}if(rtc instanceof RTCPeerConnection&&rtc.signalingState!=="closed"){rtc.close()}else if(tx&&tx.signalingState!=="closed"){if(tx)tx.close()}return true};request=(message,channel,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){channel.removeEventListener("message",onmessage);res(data.args)}}};channel.addEventListener("message",onmessage);channel.send(JSON.stringify(req))})};runRequest=(message,channelOrRtcId,callbackId)=>{let res=this.receive(message);if(channelOrRtcId){if(typeof channelOrRtcId==="string"){for(const key in this.rtc){if(key===channelOrRtcId){channelOrRtcId=this.rtc[key].channels.data?this.rtc[key].channels.data:this.rtc[key].channels[Object.keys(this.rtc[key].channels)[0]];break}}}if(res instanceof Promise)res.then(v=>{res={args:v,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res));return res});else{res={args:res,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res))}}return res};subscribeRTC=(route,rtcId,args,key,subInput,channel)=>{if(this.restrict?.[route])return void 0;if(typeof channel==="string"&&this.rtc[rtcId]){channel=this.rtc[rtcId].channels[channel]}else if(!channel){channel=this.rtc[rtcId].channels[Object.keys(this.rtc[rtcId].channels)[0]]}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{channel.send(JSON.stringify({args:r,callbackId:route}))})}else{channel.send(JSON.stringify({args:res,callbackId:route}))}},args,key,subInput)};subscribeToRTC=(route,rtcId,channelId,callback,args,key,subInput)=>{if(typeof channelId==="string"&&this.rtc[rtcId]){let c=this.rtc[rtcId];let channel=c.channels[channelId];if(channel){this.__node.state.subscribeEvent(rtcId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[rtcId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return c.request({route:"subscribeRTC",args:[route,rtcId,args,key,subInput,channelId]})}}}};var browser_default=Worker;var WorkerService=class extends Service{name="worker";workers={};threadRot=0;connections;constructor(options){super();this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.load(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}loadWorkerRoute=(node,routeKey)=>{if(node.workerUrl)node.url=node.workerUrl;if(node._id)node.__node.tag=node._id;if(!node.__node.tag)node.__node.tag=routeKey;node._id=node.__node.tag;let worker;if(this.workers[node._id])worker=this.workers[node._id];else if(node.worker)worker=node.worker;if(!worker){worker=this.addWorker(node)}node.worker=worker;if(!node.__ondisconnected){let ondelete=rt=>{rt.worker?.terminate()};node.__addOndisconnected(ondelete)}if(node.transferFunctions){for(const prop in node.transferFunctions){this.transferFunction(worker,node.transferFunctions[prop],prop)}}if(node.transferClasses){for(const prop in node.transferClasses){this.transferClass(worker,node.transferClasses[prop],prop)}}if(worker){if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.post(node.callback,args);else return worker.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(node.init){worker.run(node.init,node.initArgs,void 0,node.initTransfer)}return worker}};workerloader={"workers":(node,parent,graph,roots)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?._id&&this.workers[rt._id]||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent?.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&roots[rt.__parent]?.worker){roots[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}}return rt}};addDefaultMessageListener=()=>{globalThis.onmessage=ev=>{let result=this.receive(ev.data);if(this.__node.keepState)this.setState({[this.name]:result})}};postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new browser_default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,method,transfer)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,args,key,subInput,blocking)=>{return this.subscribeToWorker(route,options._id,callback,args,key,subInput,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,void 0,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,void 0,workerSubs[key].callback,void 0,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub});console.log(JSON.stringify(workerSubs))}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]).then(console.log)}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev=>{this.receive(ev.data);this.setState({[options._id]:ev.data})};if(!options.onerror){options.onerror=ev=>{console.error(ev.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;let workersettings={worker,__node:{tag:options._id},send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};let node=this.add(workersettings);this.workers[options._id]=node;node.__addOndisconnected(function(){terminate()});return this.workers[options._id]};open=this.addWorker;close=()=>{globalThis.close()};toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof browser_default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys2=Object.keys(this.workers);this.workers[keys2[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys2.length)this.threadRot=0}return message};terminate=worker=>{let onclose;let str2;if(typeof worker==="string"){str2=worker;let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}else if(typeof worker==="object"){if(worker?._id){worker=worker.worker;delete this.workers[worker?._id]}}if(worker instanceof browser_default){worker.terminate();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}return false};establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof browser_default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof browser_default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};runRequest=(message,worker,callbackId,getTransferable=true)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId},transfer)}return res};subscribeWorker=(route,worker,args,key,subInput,blocking,getTransferable=true)=>{if(this.restrict?.[route])return void 0;let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker?.postMessage)worker.postMessage({args:r,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker?.postMessage)worker.postMessage({args:res,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route},transfer)}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,args,key,subInput)};subscribeToWorker=(route,workerId,callback,args,key,subInput,blocking,getTransferable=true)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeEvent(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,args,key,subInput,blocking,getTransferable])}};triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i2=0;i2{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,args,key,subInput,blocking,getTransferable])};unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof sourceWorker==="object"){return sourceWorker.run("unsubscribe",[sourceRoute,sub])}}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name2 of properties){dst[name2]=src[name2]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};var str=String('(()=>{var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}if(typeof WorkerGlobalScope!=="undefined"){const routes={...workerCanvasRoutes};self.onmessage=ev=>{if(ev.data.route){if(Array.isArray(ev.data.args)){routes[ev.data.route](...ev.data.args)}else routes[ev.data.route](ev.data.args)}}}var canvas_worker_default=self;})();\n');var url=URL.createObjectURL(new globalThis.Blob([str],{type:"text/javascript"}));var canvas_worker_default=url;function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText3(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText3(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText3(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText3(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText3(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText3(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText3(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText3(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText3(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText3(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var SessionsService=class extends Service{name="sessions";users={};sessions={oneWay:{},shared:{}};invites={};constructor(options,users){super(options);this.setLoaders(loaders);this.load(this);if(users)this.users=users}getSessionInfo=(sessionIdOrName,userId)=>{if(!sessionIdOrName){return this.sessions.shared}else{if(this.sessions.oneWay[sessionIdOrName]){let s=this.sessions.oneWay[sessionIdOrName];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{oneWay:{[sessionIdOrName]:s}}}}else if(this.sessions.shared[sessionIdOrName]){return{shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};openOneWaySession=(options={},sourceUserId,listenerUserId)=>{if(!options._id){options._id=`oneWay${Math.floor(Math.random()*1e15)}`;if(this.sessions.oneWay[options._id]){delete options._id;this.openOneWaySession(options,sourceUserId)}}if(options._id&&sourceUserId&&this.users[sourceUserId]){if(sourceUserId){if(!options.settings)options.settings={listener:sourceUserId,source:sourceUserId,propnames:{latency:true},admins:{[sourceUserId]:true},ownerId:sourceUserId};if(!options.settings.listener)options.settings.listener=listenerUserId?listenerUserId:sourceUserId;if(!options.settings.source)options.settings.source=sourceUserId;if(!this.users[sourceUserId].sessions)this.users[sourceUserId].sessions={};this.users[sourceUserId].sessions[options._id]=options}if(!options.data)options.data={};if(options.onopen)options.onopen(options);if(this.sessions.oneWay[options._id]){return this.updateSession(options,sourceUserId)}else if(options.settings?.listener&&options.settings.source)this.sessions.oneWay[options._id]=options}return options};openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;return this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={oneWay:{},shared:{}};if(!options.settings.name)options.name=options.id;if(options.onopen)options.onopen(options);if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};open=(options,userId)=>{if(options.listener)this.openOneWaySession(options,userId);else this.openSharedSession(options,userId)};updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.oneWay[options._id];if(!session)session=this.sessions.shared[options._id];if(session&&userId){if(session.settings&&(session?.settings.source===userId||session.settings.admins?.[userId]||session.settings.moderators?.[userId]||session.settings.ownerId===userId)){return this.recursivelyAssign(session,options)}}else if(options.settings?.source){return this.openOneWaySession(options,userId)}else return this.openSharedSession(options,userId)}return false};joinSession=(sessionId,userId,options,remoteUser=true)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(!sesh)sesh=this.sessions.oneWay[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;sesh.settings.newUser=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options?.source||options?.listener){sesh=this.openOneWaySession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options){sesh=this.openSharedSession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}return false};inviteToSession=(session,userInvited,inviteEndpoint,remoteUser=true)=>{if(remoteUser&&this.users[userInvited]?.send){this.users[userInvited]?.send({route:"receiveSessionInvite",args:[session,userInvited,inviteEndpoint]})}else{this.receiveSessionInvite(session,userInvited,inviteEndpoint)}};receiveSessionInvite=(session,userInvited,endpoint)=>{if(!this.invites[userInvited])this.invites[userInvited]={};let id=typeof session==="string"?session:session._id;this.invites[userInvited][id]={session,endpoint};return id};acceptInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;let invite=this.invites[userInvited]?.[id];let endpoint;if(invite){session=invite.session;endpoint=invite.endpoint;delete this.invites[userInvited]?.[id]}return new Promise((res,rej)=>{if(!id)res(false);if(remoteUser&&endpoint&&this.users[endpoint]?.send){let resolved;let timeout=setTimeout(()=>{if(!resolved){this.unsubscribe("joinSession",subbed);rej(new Error("Session join timed out"))}},1e4);let subbed=this.subscribe("joinSession",result=>{if(typeof result==="object"&&result?._id===id){if(result.setting?.users?.includes(userInvited)){this.unsubscribe("joinSession",subbed);resolved=true;if(timeout)clearTimeout(timeout);res(result)}}});this.users[endpoint]?.send({route:"joinSession",args:[id,userInvited,void 0,true]})}else res(this.joinSession(id,userInvited,typeof session==="object"?session:void 0))})};rejectInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;if(this.invites[userInvited]?.[id]){let endpoint=this.invites[userInvited][id].endpoint;delete this.invites[userInvited][id];if(remoteUser&&endpoint&&this.users[endpoint]?.send){this.users[endpoint].send({route:"rejectInvite",args:[id,userInvited]})}return true}};leaveSession=(session,userId,clear=true,remoteUser=true)=>{let sessionId;if(typeof session==="string"){sessionId=session;session=this.sessions.oneWay[sessionId];if(!session)session=this.sessions.shared[sessionId]}else sessionId=session._id;if(session){if(this.sessions.oneWay[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.oneWay[sessionId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){this.swapHost(session,void 0,true);delete session.data.shared[userId]}}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}return true}return false};deleteSession=(session,userId,remoteUsers=true)=>{if(typeof session==="string"){let id=session;session=this.sessions.oneWay[id];if(!session)session=this.sessions.shared[id]}if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user]?.sessions)delete this.users[user].sessions[session._id];if(this.users[user]?.sessionSubs)delete this.users[user].sessionSubs[session._id];if(remoteUsers){if(session.users){for(const key in session.users){if(this.users[key]?.send)this.users[key].send({route:"unsubscribeFromSession",args:[session._id,key]})}}else if(session.listener){if(this.users[session.listener]?.send)this.users[session.listener].send({route:"unsubscribeFromSession",args:[session._id,session.listener]})}else if(this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId]})}}else{this.unsubsribeFromSession(session,user)}}if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.oneWay[session._id];if(session.onclose)session.onclose(session)}}return true};getFirstMatch(obj1,obj2){for(const i2 in obj1){if(i2 in obj2)return i2}return false}swapHost=(session,newHostId,adoptData=true,remoteUser=true)=>{if(typeof session==="string"){if(this.sessions.oneWay[session])session=this.sessions.oneWay[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){let oldHost=session.settings.host;delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];if(adoptData&&oldHost&&session.settings.inheritHostData!==false){if(session.data?.shared[oldHost]){if(session.data?.shared[oldHost]){session.data.shared[session.settings.host]=Object.assign(session.data.shared[session.settings.host]?session.data.shared[session.settings.host]:{},session.data.shared[oldHost]);if(remoteUser){}}}}return true}return false};subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}let user=this.users[userId];if(!user)return void 0;if(!user.sessionSubs)user.sessionSubs={};if(!user.sessionSubs[session._id])user.sessionSubs[session._id]={};if(onmessage)user.sessionSubs[session._id].onmessage=onmessage;if(onopen)this.sessionSubs[userId][session._id].onopen=onopen;if(onclose)user.sessionSubs[session._id].onclose=onclose;if(typeof onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)this.sessionSubs[userId][session._id].onopen(session,user);this.unsubscribe("joinSession",sub)});user.sessionSubs[session._id].onopenSub=sub}return session};unsubsribeFromSession=(session,userId,clear=true)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}const clearSessionSubs=(Id,s)=>{let u2=this.users[Id];if(!u2)return void 0;if(u2.sessionSubs?.[s._id]){if(u2.sessionSubs[s._id].onopenSub){this.unsubscribe("joinSession",u2.sessionSubs[s._id].onopenSub)}}if(u2.sessionSubs[s._id].onclose)u2.sessionSubs[s._id].onclose(s,u2);delete u2.sessionSubs[s._id]};if(userId){clearSessionSubs(userId,session)}else{for(const key in this.users){clearSessionSubs(key,session)}}if(clear){if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.shared[session._id]}};sessionUpdateCheck=(sessionHasUpdate,transmit=true)=>{let updates={oneWay:{},shared:{}};for(const session in this.sessions.oneWay){const sesh=this.sessions.oneWay[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.oneWay[session];continue}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(prop in this.users[sesh.source]){if(this.sessions.oneWay[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(prop in this.users[sesh.source]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.oneWay[session]?.data&&prop in this.sessions.oneWay[session]?.data)delete this.sessions.oneWay[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.oneWay[session].data,updateObj.data);updates.oneWay[sesh._id]=updateObj;if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.onhasupdate(sesh,updateObj)}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const oneWayData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}else if(sesh.settings.newUser){updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;sesh.settings.newUser=false}if(user!==sesh.settings.host){oneWayData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data?.oneWay&&!(user in sesh.data.oneWay)){if(typeof this.users[user][prop]==="object")oneWayData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else oneWayData[user][prop]=this.users[user][prop]}else if(typeof oneWayData[user][prop]==="object"&&sesh.data){if(prop in this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))oneWayData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.oneWay?.[prop]!==this.users[user][prop])oneWayData[user][prop]=this.users[user][prop]}else if(sesh.data?.oneWay?.[user]&&prop in sesh.data?.oneWay?.[user])delete sesh.data.oneWay[user][prop]}if(Object.keys(oneWayData[user]).length===0)delete oneWayData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user]))sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}}}if(Object.keys(oneWayData).length>0){updateObj.data.oneWay=oneWayData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user]?.[prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user]?.[prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.oneWay){updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){Object.assign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.oneWay){Object.assign(this.sessions.shared[session].data?.oneWay,updateObj.data.oneWay)}if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.settings.onhasupdate(sesh,updateObj)}}if(Object.keys(updates.oneWay).length===0)delete updates.oneWay;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};transmitSessionUpdates=updates=>{let users={};if(updates.oneWay){for(const s in updates.oneWay){let session=this.sessions.oneWay[s];if(session?.settings){let u2=session.settings.listener;if(!users[u2])users[u2]={};users[u2].oneWay[s]=updates.oneWay[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){for(const u2 in session.settings.users){if(!users[u2])users[u2]={};users[u2].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u2 in users){message.args=[u2,users[u2]];if(this.users[u2]?.send)this.users[u2].send(JSON.stringify(message));this.setState({[u2]:Object.create(message)})}return users};receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(user){if(!user.sessions)user.sessions={oneWay:{},shared:{}};if(!user.sessionSubs)user.sessionSubs={}}if(update.oneWay){for(const key in update.oneWay){this.recursivelyAssign(this.sessions.oneWay[key].data,update.oneWay[key].data);if(this.sessions.oneWay[key]?.settings.onmessage)this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key],update.oneWay[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}if(update.shared){for(const key in update.shared){if(update.shared[key].settings.users)this.sessions.shared[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)this.sessions.shared[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.oneWay)this.recursivelyAssign(this.sessions.shared[key].data.oneWay,update.shared[key].data.oneWay);if(update.shared[key].data.shared)this.recursivelyAssign(this.sessions.shared[key].data.shared,update.shared[key].data.shared);if(this.sessions.shared[key]?.settings.onmessage)this.sessions.shared[key].settings.onmessage(this.sessions.shared[key],update.shared[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}return user}};getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};userUpdateCheck=(user,onupdate)=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});if(onupdate){onupdate(user,updateObj)};return updateObj}}return void 0};setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};STREAMLATEST=0;STREAMALLLATEST=1;streamSettings={};streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};setStreamFunc=(name2,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name2].settings[key])this.streamSettings[name2].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name2].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name2].settings[key].callback=callback;if(!this.streamSettings[name2].settings[key].callback)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;return true};addStreamFunc=(name2,callback=data=>{})=>{this.streamFunctions[name2]=callback};setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};removeStream=(streamName,key)=>{if(streamName&&this.streamSettings[streamName]&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}}};var Router=class extends Service{name="router";connections={};sources={};services={};serviceConnections={};users={};userTimeout=1e4;order;constructor(options){super(options);this.load(this);if(options){if(options.order)this.order=options.order;if(options.timeout)this.userTimeout=options.timeout;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}addUser=async(info,connections,config,receiving)=>{let user;if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}if(this.users[info._id]){user=this.users[info._id]}else{user=Object.assign({},info)}if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>this.userTimeout){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}if(!this.users[info._id]){let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let sendAll=(message,...a)=>{let connections2=this.getConnections(user._id,"send");for(const key in connections2)if(connections2[key]?.send)return connections2[key].send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let requestAll=(message,method,...a)=>{let connections2=this.getConnections(user._id,"request");let results=[];for(const key in connections2)if(connections2[key]?.request)results.push(connections2[key].request(message,method,...a));return Promise.all(results)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let postAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"post");for(const key in connections2)if(connections2[key]?.post)connections2[key].post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let runAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"run");let results=[];for(const key in connections2)if(connections2[key]?.run)results.push(connections2[key].run(route,args,method,...a));return Promise.all(results)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let subscribeAll=(route,callback,...a)=>{let connections2=this.getConnections(user._id,"subscribe");let results=[];for(const key in connections2)if(connections2[key]?.post)results.push(connections2[key].subscribe(route,callback,...a));return Promise.all(results)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let unsubscribeAll=(route,subs,...a)=>{let connections2=this.getConnections(user._id,"unsubscribe");let results=[];for(const key in connections2)if(connections2[key]?.post&&subs[key])results.push(connections2[key].unsubscribe(route,subs[key],...a));return Promise.all(results)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;user.sendAll=sendAll;user.requestAll=requestAll;user.postAll=postAll;user.runAll=runAll;user.subscribeAll=subscribeAll;user.unsubscribeAll=unsubscribeAll;user.terminateAll=terminate;this.users[user._id]=user}if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i2)=>{if(connections[k]?._id){connectionIds[`${i2}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}getConnection=(sourceId,hasMethod,connectionId)=>{if(this.connections[sourceId]){return this.connections[sourceId]}else if(this.sources[sourceId]){if(hasMethod?.includes("All"))return this.users[sourceId];if(connectionId){if(hasMethod){if(this.sources[sourceId][connectionId]?.[hasMethod])return this.sources[sourceId][connectionId]}else if(this.sources[sourceId][connectionId])return this.sources[sourceId][connectionId];else return void 0}else if(this.order){for(let i2=0;i2{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}return found}};runConnection=async(userId,method,args,connectionId)=>{let sendTo;if(method.indexOf("All")>-1){sendTo=this.users[userId]}else{sendTo=this.getConnection(userId,method,connectionId)}if(sendTo){let res=sendTo[method](...args);res=await res;return res}};subscribeThroughConnection=(route,remoteRelay,remoteEndpoint,callback,...args)=>{if(typeof remoteRelay==="string"){remoteRelay=this.getConnection(remoteRelay,"run")}if(typeof remoteRelay==="object")return new Promise((res,rej)=>{remoteRelay.run("routeConnections",[route,remoteEndpoint,remoteRelay._id,...args]).then(sub=>{this.__node.state.subscribeEvent(remoteEndpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[remoteEndpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};addConnection=(options,source,autoRemove=true)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.connection=options.connection;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await connectionHasId(info,this.userTimeout)}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await connectionHasId(connection,this.userTimeout)}if(connection._id)return this.addConnection({connection,service},source)}}};terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}}};function connectionHasId(connection,timeout=1e4){return new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>timeout){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connection timed out:",er)})}export{Callable,DOMElement,E2EEService,ECSService,ElementProxyReceiver,EventDispatcher,EventHandler,Graph,GraphNode,HTTPfrontend,ProxyManager,Renderer,Router,SSEfrontend,Service,SessionsService,WSSfrontend,WebRTCfrontend,WorkerService,addCustomElement,animate,backprop,bindListener,branching,clearCanvas,connectionHasId,drawFrame,eventHandlers,getAllProperties,getCallbackFromString,getCanvas,getFnParamNames,getFunctionHead,html,htmlloader,initCanvas,initProxyElement,instanceObject,isFunction,isNativeClass,isTypedArray,loaders,loop,methodstrings,nodeTemplates,parseFunctionFromText,proxyElementWorkerRoutes,reconstructObject,recursivelyAssign2 as recursivelyAssign,recursivelyStringifyFunctions,remoteGraphRoutes,setDraw,setProps,setupCanvas,spliceTypedArray,startAnim,state,stopAnim,stringifyFast,stringifyWithCircularRefs,stringifyWithFunctionsAndCircularRefs,substitute__operator,transferCanvas,transformListenerResult,triggerListenerOncreate,updateCanvas,wchtmlloader,workerCanvasRoutes,wrapArgs,xml}; +var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var require_sjcl=__commonJS({"services/e2ee/sjcl.js"(exports,module){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function instanceObject(obj){let props=getAllProperties(obj);let instance={};for(const key of props){instance[key]=obj[key]}return instance}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var ECSService=class extends Service{constructor(options){super(options);this.entities={};this.systems={};this.entityMap=new Map;this.entityKeyMap=new Map;this.order=[];this.animating=false;this.entityCt=0;this.systemCt=0;this.updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};this.animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};this.stop=()=>{this.animating=false};this.start=filter=>{this.animateEntities(filter)};this.addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};this.addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};this.addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};this.setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};this.removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};this.removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};this.setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};this.setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};this.bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j{this.removeEntity(t)})}filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}};var DOMElement=class extends HTMLElement{constructor(){super();__publicField(this,"template",function(self2=this,props){return`
Custom Fragment Props: ${JSON.stringify(props)}
`});__publicField(this,"props",{});__publicField(this,"useShadow",false);__publicField(this,"styles");__publicField(this,"oncreate");__publicField(this,"onresize");__publicField(this,"ondelete");__publicField(this,"onchanged");__publicField(this,"renderonchanged",false);__publicField(this,"FRAGMENT");__publicField(this,"STYLE");__publicField(this,"attachedShadow",false);__publicField(this,"obsAttributes",["props","options","onchanged","onresize","ondelete","oncreate","template"]);__publicField(this,"attributeChangedCallback",(name,old,val)=>{if(name==="onchanged"){let onchanged=val;if(typeof onchanged==="string")onchanged=parseFunctionFromText2(onchanged);if(typeof onchanged==="function"){this.onchanged=onchanged;this.state.data.props=this.props;this.state.unsubscribeTrigger("props");this.state.subscribeTrigger("props",this.onchanged);let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)})}}else if(name==="onresize"){let onresize=val;if(typeof onresize==="string")onresize=parseFunctionFromText2(onresize);if(typeof onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this.props,this)};this.onresize=onresize;window.addEventListener("resize",this.ONRESIZE)}}else if(name==="ondelete"){let ondelete=val;if(typeof ondelete==="string")ondelete=parseFunctionFromText2(ondelete);if(typeof ondelete==="function"){this.ondelete=()=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");if(ondelete)ondelete(this.props,this)}}}else if(name==="oncreate"){let oncreate=val;if(typeof oncreate==="string")oncreate=parseFunctionFromText2(oncreate);if(typeof oncreate==="function"){this.oncreate=oncreate}}else if(name==="renderonchanged"){let rpc=val;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!=false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}else if(name==="props"){let newProps=val;if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props})}else if(name==="template"){let template=val;this.template=template;this.render(this.props);let created=new CustomEvent("created",{detail:{props:this.props}});this.dispatchEvent(created)}else{let parsed=val;if(name.includes("eval_")){name=name.split("_");name.shift();name=name.join();parsed=parseFunctionFromText2(val)}else if(typeof val==="string"){try{parsed=JSON.parse(val)}catch(err){parsed=val}}this[name]=parsed;if(name!=="props"&&this.props)this.props[name]=parsed}});__publicField(this,"delete",()=>{this.remove();if(typeof this.ondelete==="function")this.ondelete(this.props)});__publicField(this,"render",(props=this.props)=>{if(typeof this.template==="function")this.templateResult=this.template(this,props);else this.templateResult=this.template;if(this.styles)this.templateResult=`${this.templateResult}`;const t=document.createElement("template");if(typeof this.templateResult==="string")t.innerHTML=this.templateResult;else if(this.templateResult instanceof HTMLElement){if(this.templateResult.parentNode){this.templateResult.parentNode.removeChild(this.templateResult)}t.appendChild(this.templateResult)}const fragment=t.content;if(this.FRAGMENT){if(this.useShadow){if(this.STYLE)this.shadowRoot.removeChild(this.STYLE);this.FRAGMENT.forEach(c=>{this.shadowRoot.removeChild(c)})}else this.FRAGMENT.forEach(c=>{this.removeChild(c)})}if(this.useShadow){if(!this.attachedShadow){this.attachShadow({mode:"open"}).innerHTML="";this.attachedShadow=true}if(this.styles){let style=document.createElement("style");style.textContent=this.styles;this.shadowRoot.prepend(style);this.STYLE=style}let len=fragment.childNodes.length;this.shadowRoot.prepend(fragment);this.FRAGMENT=Array.from(this.shadowRoot.childNodes).slice(0,len)}else{let len=fragment.childNodes.length;this.prepend(fragment);this.FRAGMENT=Array.from(this.childNodes).slice(0,len)}let rendered=new CustomEvent("rendered",{detail:{props:this.props,self:this}});this.dispatchEvent(rendered);if(this.oncreate)this.oncreate(this,props)});__publicField(this,"state",{pushToState:{},data:{},triggers:{},setState(updateObj){Object.assign(this.pushToState,updateObj);if(Object.keys(this.triggers).length>0){for(const prop of Object.getOwnPropertyNames(this.triggers)){if(this.pushToState[prop]){this.data[prop]=this.pushToState[prop];delete this.pushToState[prop];this.triggers[prop].forEach(obj=>{obj.onchanged(this.data[prop])})}}}return this.pushToState},subscribeTrigger(key,onchanged=res=>{}){if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({idx:l,onchanged});return this.triggers[key].length-1}else return void 0},unsubscribeTrigger(key,sub){let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.idx===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);return true}}},subscribeTriggerOnce(key=void 0,onchanged=value=>{}){let sub;let changed=value=>{onchanged(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)}})}get observedAttributes(){return this.obsAttributes}get obsAttributes(){return this.obsAttributes}set obsAttributes(att){if(typeof att==="string"){this.obsAttributes.push(att)}else if(Array.isArray(att))this.obsAttributes=att}static get tag(){return this.name.toLowerCase()+"-"}static addElement(tag=this.tag,cls=this,extend=void 0){addCustomElement(cls,tag,extend)}connectedCallback(){if(!this.props)this.props={};let newProps=this.getAttribute("props");if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props});Array.from(this.attributes).forEach(att=>{let name=att.name;let parsed=att.value;if(name.includes("eval_")||name.includes("()")){if(name.includes("eval_"))name=name.split("_");else if(name.includes("()"))name=name.substring(0,name.indexOf("("));name.shift();name=name.join();parsed=parseFunctionFromText2(att.value)}else if(typeof att.value==="string"){try{parsed=JSON.parse(att.value)}catch(err){parsed=att.value}}if(!this[name]){Object.defineProperties(this,att,{value:parsed,writable:true,get(){return this[name]},set(val){this.setAttribute(name,val)}})}this[name]=parsed;if(name!=="props")this.props[name]=parsed;this.obsAttributes.push(name)});let resizeevent=new CustomEvent("resized",{detail:{props:this.props,self:this}});let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});let deleted=new CustomEvent("deleted",{detail:{props:this.props,self:this}});let created=new CustomEvent("created",{detail:{props:this.props,self:this}});this.render(this.props);this.dispatchEvent(created);this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)});if(typeof this.onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this,this.props);this.dispatchEvent(resizeevent)};window.addEventListener("resize",this.ONRESIZE)}if(typeof this.ondelete==="function"){let ondelete=this.ondelete;this.ondelete=(props=this.props)=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");this.dispatchEvent(deleted);ondelete(this,props)}}if(typeof this.onchanged==="function"){this.state.data.props=this.props;this.state.subscribeTrigger("props",this.onchanged)}if(this.renderonchanged){let rpc=this.renderonchanged;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!==false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}}get props(){return this.props}set props(newProps={}){this.setAttribute("props",newProps)}get template(){return this.template}set template(template){this.setAttribute("template",template)}get render(){return this.render}get delete(){return this.delete}get state(){return this.state}get onchanged(){return this.onchanged}set onchanged(onchanged){this.setAttribute("onchanged",onchanged)}get styles(){return this.styles}set styles(templateStr){this.styles=templateStr;if(this.querySelector("style")){this.querySelector("style").innerHTML=templateStr}else{this.render()}}get renderonchanged(){return this.renderonchanged}set renderonchanged(onchanged){this.setAttribute("renderonchanged",onchanged)}get onresize(){return this.props}set onresize(onresize){this.setAttribute("onresize",onresize)}get ondelete(){return this.props}set ondelete(ondelete){this.setAttribute("ondelete",ondelete)}get oncreate(){return this.oncreate}set oncreate(oncreate){this.setAttribute("oncreated",oncreate)}};function addCustomElement(cls,tag,extend=null){try{if(extend){if(tag)window.customElements.define(tag,cls,{extends:extend});else window.customElements.define(cls.name.toLowerCase()+"-",cls,{extends:extend})}else{if(tag)window.customElements.define(tag,cls);else window.customElements.define(cls.name.toLowerCase()+"-",cls)}}catch(err){}}function parseFunctionFromText2(method){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf(")");return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;try{if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch(err){newFunc=(0,eval)(method)}}}}catch(err){}return newFunc}var htmlloader=(node,parent2,graph,tree,properties,key)=>{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if(node.tagName&&!node.__props&&!node.__template){node.__props=document.createElement(node.tagName);node.__proxyObject(node.__props);let keys=Object.getOwnPropertyNames(properties);for(const k of keys){if(k==="style"&&typeof properties[k]==="object"){Object.assign(node.__props.style,properties[k])}else node.__props[k]=properties[k]}}else if(node.__element&&!node.__template){if(typeof node.__element==="string")node.__element=document.createElement(node.__element);if(!(node.__element instanceof HTMLElement))return;node.__props=node.__element;node.__proxyObject(node.__props);let keys=Object.getOwnPropertyNames(properties);for(const k of keys){if(k==="style"&&typeof properties[k]==="object"){Object.assign(node.__props.style,properties[k])}else node.__props[k]=properties[k]}}else if(typeof node.__css==="string"){node.__template=``;delete node.__css}if(node.__template){if(typeof node.__renderonchanged==="function"){let renderonchanged=node.__renderonchanged;node.__renderonchanged=element=>{renderonchanged.call(element.node,element)}}class CustomElement extends DOMElement{constructor(){super(...arguments);this.props=node.props;this.styles=node.__css;this.useShadow=node.useShadow;this.template=node.__template;this.oncreate=node.__onrender;this.onresize=node.__onresize;this.ondelete=node.__onremove;this.renderonchanged=node.__renderonchanged}}if(node.__element)node.tagName=node.__element;if(!node.tagName)node.tagName=`element${Math.floor(Math.random()*1e15)}-`;CustomElement.addElement(node.tagName);node.__props=document.createElement(node.tagName);node.__proxyObject(node.__props);node.__props.node=node;let keys=Object.getOwnPropertyNames(properties);for(const k of keys){if(k==="style"&&typeof properties[k]==="object"){Object.assign(node.__props.style,properties[k])}else node.__props[k]=properties[k]}}else if(node.__props instanceof HTMLElement){if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__attributes&&node.__props instanceof HTMLElement){for(const k in node.__attributes){if(k==="style"&&typeof node.__attribute[k]==="object"){Object.assign(node.__props.style,node.__attribute[k])}node.__props[k]=node.__attributes[k]}}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__addOnconnected(n=>{if(n.__props.parentNode)n.__props.remove();if(n.parentNode){if(typeof n.parentNode==="string"&&document.getElementById(n.parentNode))document.getElementById(n.parentNode).appendChild(n.__props);else if(n.parentNode instanceof HTMLElement)n.parentNode.appendChild(n.__props)}else if(parent2.__props instanceof HTMLElement){parent2.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(n.parentNode)){document.getElementById(n.parentNode).appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender&&!node.__template)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var import_sjcl=__toESM(require_sjcl());var E2EEService=class extends Service{constructor(options,keys,secureKeys,secret){super(options);this.name="e2ee";this.securedKeys=false;this.addKey=(key,_id)=>{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=import_sjcl.default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};this.encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=import_sjcl.default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};this.decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=import_sjcl.default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=import_sjcl.default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};this.transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};this.receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message};if(keys){if(secureKeys&&secret){this.securedKeys=true;this.encryptedkeys=import_sjcl.default.encrypt(secret,JSON.stringify(keys)).cipher;this.secret=secret}else Object.assign(this.keys,keys)}this.setTree(this)}static generateSecret(){return import_sjcl.default.codec.base64.fromBits(import_sjcl.default.random.randomWords(8,10))}encrypt(message,key){message=import_sjcl.default.encrypt(key,message).cipher;return message}decrypt(message,key){message=import_sjcl.default.decrypt(key,message);return message}};var _HTTPfrontend=class extends Service{constructor(options,path,fetched){super(options);this.name="http";this.fetchProxied=false;this.listening={};this.GET=(url="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{let obj=message;if(typeof obj==="object"){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url);return this.POST(message,url)};this.transponder=(url,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url,data:message,responseType:type,onload:ev=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};this.listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};this.stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}};this.setTree(this);this.listen(path,fetched)}};var HTTPfrontend=_HTTPfrontend;HTTPfrontend.request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};var SSEfrontend=class extends Service{constructor(options){super(options);this.name="sse";this.eventsources={};this.connections={eventsources:this.eventsources};this.openSSE=options=>{let source=new EventSource(options.url);let sse={source,type:"eventsource",...options};if(!("keepState"in options))options.keepState=true;if(!options.events)options.events={};if(options.events.close){let close=options.events.close;options.events.close=ev=>{if(sse.onclose)sse.onclose(ev,sse);close(ev,sse)}}if(options.events.open){let open=options.events.open;options.events.open=ev=>{if(sse.onopen)sse.onopen(ev,sse);open(ev,sse)}}if(options.events.error){let error=options.events.error;options.events.error=ev=>{if(sse.onerror)sse.onerror(ev,sse);error(ev,sse)}}if(options.events.message){let message=options.events.message;options.events.message=ev=>{if(sse.onmessage)sse.onmessage(ev,sse);message(ev,sse)}}if(!options.events.message){options.events.message=(ev,sse2)=>{let data=ev.data;if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"&&sse2){sse2._id=data.args;options.events.message=(e,sse3)=>{const result2=this.receive(e.data,sse3);if(options.keepState)this.setState({[options.url]:e.data})}}}}}const result=this.receive(ev.data,sse2);if(options.keepState)this.setState({[options.url]:data})}}if(!options.events.error)options.events.error=(ev,sse2)=>{this.terminate(sse2);delete this.eventsources[options.url]};if(options.events){if(!options.evoptions)options.evoptions=false;for(const key in options.events){if(typeof options.events[key]!=="function"){options.events[key]=ev=>{const result=this.receive(ev.data,sse);if(options.keepState)this.setState({[options.url]:result})}}else{let l=options.events[key];options.events[key]=ev=>{l(ev,sse)}}source.addEventListener(key,options.events[key],options.evoptions)}}let send=message=>{return this.transmit(message,options.url)};let request=(message,method,sessionId)=>{return this.request(message,options.url,sessionId,method)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options.url)};let run=(route,args,method,sessionId)=>{return this.request({route,args},options.url,method,sessionId)};let subscribe=(route,callback)=>{return this.subscribeToSSE(route,options.url,callback,sse._id)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options.url)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;this.eventsources[options.url]=sse;return sse};this.open=this.openSSE;this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{return this.POST(message,url,"json")};this.request=(message,url,method,sessionId)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,url,callbackId,sessionId]};if(method)req.method=method;let evs=this.eventsources[url].source;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){evs.removeEventListener("message",onmessage);res(data.args)}}};evs.addEventListener("message",onmessage);this.POST(message,url,"json")})};this.runRequest=(message,url,callbackId,sessionId)=>{let res=this.receive(message);if(url){if(res instanceof Promise){res.then(r=>{let message2={args:r,callbackId,sessionId};this.POST(message2,url,"json")})}else{let message2={args:res,callbackId,sessionId};this.POST(message2,url,"json")}}return res};this.subscribeSSE=(route,url,key,subInput)=>{return this.subscribe(route,res=>{this.POST(res,url,"json")},key,subInput)};this.subscribeToSSE=(route,url,callback,sessionId,key,subInput)=>{if(url){this.__node.state.subscribeTrigger(url,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[url]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.eventsources[url].run("subscribeSSE",[route,url,sessionId,key,subInput])}};this.terminate=sse=>{if(typeof sse==="string"){let str=sse;sse=this.eventsources[sse];delete this.eventsources[str]}if(!sse)return;if(typeof sse==="object"){if(sse.source){sse=sse.source}if(sse instanceof EventSource){if(sse.readyState!==2)sse.close()}}};this.setTree(this)}};var WSSfrontend=class extends Service{constructor(options){super(options);this.name="wss";this.sockets={};this.connections={sockets:this.sockets};this.openWS=(options={host:"localhost",port:7e3,path:void 0,protocol:"ws",onclose:(ev,socket,wsinfo)=>{if(ev.target.url)delete this.sockets[ev.target.url]}})=>{let protocol=options.protocol;if(!protocol)protocol="ws";let address=`${protocol}://${options.host}`;if(!("keepState"in options))options.keepState=true;if(options.port)address+=":"+options.port;if(options.path&&!options.path?.startsWith("/"))address+="/";if(options.path)address+=options.path;if(this.sockets[address]?.socket){if(this.sockets[address].socket.readyState===this.sockets[address].socket.OPEN)this.sockets[address].socket.close()}const socket=new WebSocket(address);if(!options.onmessage){if(!options._id){options.onmessage=(data,ws,wsinfo)=>{if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;options.onmessage=(data2,ws2,wsinfo2)=>{this.receive(data2);if(options.keepState){this.setState({[address]:data2})}}}}}}let res=this.receive(data);if(options.keepState)this.setState({[address]:data})}}else{options.onmessage=(data,ws,wsinfo)=>{this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}}}}if(options.onmessage){socket.addEventListener("message",ev=>{this.sockets[address].onmessage(ev.data,socket,this.sockets[address])})}socket.addEventListener("open",ev=>{if(this.sockets[address].onopen)this.sockets[address].onopen(ev,socket,this.sockets[address])});socket.addEventListener("close",ev=>{if(this.sockets[address].onclose)this.sockets[address].onclose(ev,socket,this.sockets[address])});socket.addEventListener("error",ev=>{if(this.sockets[address].onerror)this.sockets[address].onerror(ev,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="string"&&ev.data.indexOf("{")>-1)ev.data=JSON.parse(ev.data);if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(ev.data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="string"&&ev.data.indexOf("{")>-1)ev.data=JSON.parse(ev.data);if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(ev.data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let subscribe=(route,callback)=>{return this.subscribeToSocket(route,options._id,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.sockets[address]={type:"socket",socket,address,send,post,run,request,subscribe,unsubscribe,terminate,graph:this,...options};return this.sockets[address]};this.open=this.openWS;this.transmit=(data,ws)=>{if(typeof data==="object")data=JSON.stringify(data);if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}if(ws instanceof WebSocket&&ws?.readyState===1)ws.send(data);return true};this.terminate=ws=>{if(!ws){let key=Object.keys(this.sockets)[0];if(key)ws=this.sockets[key].socket}else if(typeof ws==="string"){for(const k in this.sockets){if(k.includes(ws)){ws=this.sockets[k].socket;break}}}if(ws instanceof WebSocket){if(ws.readyState===ws.OPEN)ws.close()}return true};this.request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};this.runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(typeof ws==="string"){for(const s in this.sockets){if(s===ws){ws=this.sockets[s].socket;break}}}if(ws){if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))}}return res};this.subscribeSocket=(route,socket,key,subInput)=>{if(typeof socket==="string"&&this.sockets[socket]){socket=this.sockets[socket].socket}if(typeof socket==="object")return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},key,subInput)};this.subscribeToSocket=(route,socketId,callback,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeTrigger(socketId,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[socketId]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,key,subInput]})}};this.setTree(this)}};var WebRTCfrontend=class extends Service{constructor(options,iceServers){super(options);this.name="webrtc";this.rtc={};this.iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun1.l.google.com:19302"]},{urls:["stun:stun2.l.google.com:19302"]},{urls:["stun:stun3.l.google.com:19302"]},{urls:["stun:stun4.l.google.com:19302"]}];this.connections={rtc:this.rtc};this.createStream=options=>{let stream=new MediaStream;for(const key in options){let track=options[key].track;if(!(track instanceof MediaStreamTrack)&&typeof track==="object"){track=new MediaStreamTrack;track.applyConstraints(options[key].track);stream.addTrack(track)}if(track instanceof MediaStreamTrack){stream.addTrack(track);track.onmute=options[key].onmute;track.onunmute=options[key].onunmute;track.onended=options[key].onended}}return stream};this.openRTC=async options=>{if(!options)options={};if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(!options.config)options.config={iceServers:this.iceServers};let rtc=new RTCPeerConnection(options.config);if(!this.rtc[options._id]){if(!options.channels)options.channels={"data":true};let firstChannel;for(const key in options.channels){firstChannel=key;break}let send=message=>{return this.transmit(message,options._id,options.channels[firstChannel])};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options._id,options.channels[firstChannel])};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let subscribe=(route,callback)=>{return this.subscribeToRTC(route,options._id,firstChannel,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.rtc[options._id]={rtc,_id:options._id,request,run,post,send,subscribe,unsubscribe,terminate,graph:this,...options};if(!options.ondatachannel)options.ondatachannel=ev=>{this.rtc[options._id].channels[ev.channel.label]=ev.channel;if(!options.ondata){ev.channel.addEventListener("message",mev=>{this.receive(mev.data,ev.channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})})}else ev.channel.addEventListener("message",mev=>{options.ondata(mev.data,ev.channel,this.rtc[options._id])})};if(options.channels){for(const channel in options.channels){if(options.channels[channel]instanceof RTCDataChannel){}else if(typeof options.channels[channel]==="object"){options.channels[channel]=this.addDataChannel(rtc,channel,options.channels[channel])}else{options.channels[channel]=this.addDataChannel(rtc,channel)}options.channels[channel].addEventListener("message",mev=>{this.receive(mev.data,channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})})}}rtc.ontrack=options.ontrack;rtc.onicecandidate=options.onicecandidate;rtc.onicecandidateerror=options.onicecandidateerror;rtc.ondatachannel=options.ondatachannel;rtc.onnegotiationneeded=options.onnegotiationneeded;rtc.oniceconnectionstatechange=options.oniceconnectionstatechange;rtc.onconnectionstatechange=options.onconnectionstatechange;rtc.addEventListener("connectionstatechange",ev=>{if(rtc.connectionState==="closed"||rtc.connectionState==="failed"){if(this.rtc[options._id].onclose){this.rtc[options._id].onclose(this.rtc[options._id])}}})}else{Object.assign(this.rtc[options._id],options)}if(options.hostdescription&&!options.peerdescription){if(!options.onicecandidate)options.onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].peercandidates)this.rtc[options._id].peercandidates={};this.rtc[options._id].peercandidates[`peercandidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};return await new Promise((res,rej)=>{if(typeof options.hostdescription==="string"){options.hostdescription=JSON.parse(decodeURIComponent(options.hostdescription))}const description=new RTCSessionDescription(options.hostdescription);options.hostdescription=description;rtc.setRemoteDescription(description).then(()=>{if(options.hostcandidates){for(const prop in options.hostcandidates){const candidate=new RTCIceCandidate(options.hostcandidates[prop]);rtc.addIceCandidate(candidate).catch(console.error)}}rtc.createAnswer(options.answer).then(answer=>rtc.setLocalDescription(answer)).then(()=>{this.rtc[options._id].peerdescription=encodeURIComponent(JSON.stringify(rtc.localDescription));res(this.rtc[options._id])})}).catch(rej)})}if(options.peerdescription){this.answerPeer(rtc,options)}if(!options.onicecandidate&&!this.rtc[options._id]?.onicecandidate)options.onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].hostcandidates)this.rtc[options._id].hostcandidates={};this.rtc[options._id].hostcandidates[`hostcandidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};return await new Promise((res,rej)=>{rtc.createOffer(options.offer).then(offer=>rtc.setLocalDescription(offer)).then(()=>{this.rtc[options._id].hostdescription=encodeURIComponent(JSON.stringify(rtc.localDescription));res(this.rtc[options._id])})})};this.addUserMedia=(rtc,options={audio:false,video:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560}]}})=>{let senders=[];navigator.mediaDevices.getUserMedia(options).then(stream=>{let tracks=stream.getTracks();tracks.forEach(track=>{senders.push(rtc.addTrack(track,stream))})});return senders};this.addTrack=(rtc,track,stream)=>{rtc.addTrack(track,stream);return true};this.removeTrack=(rtc,sender)=>{rtc.removeTrack(sender);return true};this.addDataChannel=(rtc,name,options)=>{return rtc.createDataChannel(name,options)};this.transmit=(data,id,channel)=>{if(typeof data==="object"||typeof data==="number")data=JSON.stringify(data);if(!channel&&id){let keys=Object.keys(this.rtc[id].channels);if(keys[0])channel=this.rtc[id].channels[keys[0]]}if(typeof channel==="string"){if(id){channel=this.rtc[id].channels[channel]}else{for(const id2 in this.rtc){if(this.rtc[id2].channels[channel]instanceof RTCDataChannel)this.rtc[id2].channels[channel].send(data)}}}if(channel instanceof RTCDataChannel)channel.send(data);return true};this.terminate=rtc=>{let tx;if(typeof rtc==="string"){let room=this.rtc[rtc];delete this.rtc[rtc];if(room){tx=room.rtc}}else if(typeof rtc==="object"){tx=rtc.rtc}if(rtc instanceof RTCPeerConnection){rtc.close()}else if(tx){if(tx)tx.close()}return true};this.request=(message,channel,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){channel.removeEventListener("message",onmessage);res(data.args)}}};channel.addEventListener("message",onmessage);channel.send(JSON.stringify(req))})};this.runRequest=(message,channel,callbackId)=>{let res=this.receive(message);if(channel){if(typeof channel==="string"){for(const key in this.rtc){if(key===channel){channel=this.rtc[key].channels.data;break}}}if(res instanceof Promise)res.then(v=>{res={args:v,callbackId};if(channel instanceof RTCDataChannel)channel.send(JSON.stringify(res));return res});else{res={args:res,callbackId};if(channel instanceof RTCDataChannel)channel.send(JSON.stringify(res))}}return res};this.subscribeRTC=(route,rtcId,channel)=>{if(typeof channel==="string"&&this.rtc[rtcId]){channel=this.rtc[rtcId].channels[channel]}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{channel.send(JSON.stringify({args:r,callbackId:route}))})}else{channel.send(JSON.stringify({args:res,callbackId:route}))}})};this.subscribeToRTC=(route,rtcId,channelId,callback)=>{if(typeof channelId==="string"&&this.rtc[rtcId]){let c=this.rtc[rtcId];let channel=c.channels[channelId];if(channel){this.__node.state.subscribeTrigger(rtcId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[rtcId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return c.request({route:"subscribeRTC",args:[route,channelId]})}}};this.setTree(this);if(iceServers)this.iceServers=iceServers}addIceCandidate(rtc,candidate){return rtc.addIceCandidate(candidate)}answerPeer(rtc,options){return new Promise((res,rej)=>{if(typeof options.peerdescription==="string"){options.peerdescription=JSON.parse(decodeURIComponent(options.peerdescription))}const description=new RTCSessionDescription(options.peerdescription);options.peerdescription=description;if(this.rtc[options._id])this.rtc[options._id].peerdescription=description;rtc.setRemoteDescription(description).then(()=>{if(options.peercandidates){for(const prop in options.peercandidates){const candidate=new RTCIceCandidate(options.peercandidates[prop]);if(this.rtc[options._id])this.rtc[options._id].peercandidates[prop]=options.peercandidates[prop];rtc.addIceCandidate(candidate).catch(console.error)}}res(this.rtc[options._id]?this.rtc[options._id]:rtc)}).catch(rej)})}};var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent2,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent2?.callback&&parent2?.worker))node.parentRoute=parent2?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev=>{let result=this.receive(ev.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev=>{this.receive(ev.data);this.setState({[options._id]:ev.data})};if(!options.onerror){options.onerror=ev=>{console.error(ev.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setTree(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText3(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText3(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText3(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText3(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText3(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText3(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText3(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText3(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText3(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText3(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w=s.worker;let wpId;wpId=service.establishMessageChannel(w.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w.run("setValue",["routeProxy",s.route]);w.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w2=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w.worker,w2.worker);s.pipeTo.worker=w2}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w.run("setValue",["routeProxy",s.route]);service.transferFunction(w,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;Object.assign(this.__node.graph.ALGORITHMS[_id],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;let res=this.__node.graph.ALGORITHMS[_id].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id]:res});return res}}}};var SessionsService=class extends Service{constructor(options,users){super(options);this.name="sessions";this.users={};this.sessions={private:{},shared:{}};this.getSessionInfo=(sessionId,userId)=>{if(!sessionId){return this.sessions.shared}else{if(this.sessions.private[sessionId]){let s=this.sessions.private[sessionId];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{private:{[sessionId]:s}}}}else if(this.sessions.shared[sessionId]){return{shared:{[sessionId]:this.sessions.shared[sessionId]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};this.openPrivateSession=(options={},userId)=>{if(!options._id){options._id=`private${Math.floor(Math.random()*1e15)}`;if(this.sessions.private[options._id]){delete options._id;this.openPrivateSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(userId){if(!options.settings)options.settings={listener:userId,source:userId,propnames:{latency:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.listener)options.settings.listener=userId;if(!options.settings.source)options.settings.source=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}if(!options.data)options.data={};if(this.sessions.private[options._id]){return this.updateSession(options,userId)}else if(options.settings?.listener&&options.settings.source)this.sessions.private[options._id]=options}return options};this.openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={private:{},shared:{}};if(!options.settings.name)options.name=options.id;if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};this.updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.private[options._id];if(!session)session=this.sessions.shared[options._id];if(this.sessions.private[options._id]&&userId){let sesh=this.sessions.shared[options._id];if(sesh.settings&&(sesh?.settings.source===userId||sesh.settings.admins?.[userId]||sesh.settings.moderators?.[userId]||sesh.settings.ownerId===userId)){return Object.assign(this.sessions.shared[options._id],options)}}else if(options.settings?.source){return this.openPrivateSession(options,userId)}else return this.openSharedSession(options,userId)}return false};this.joinSession=(sessionId,userId,options)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};return sesh}else if(options?.source||options?.listener)return this.openPrivateSession(options,userId);else if(options)return this.openSharedSession(options,userId);return false};this.leaveSession=(sessionId,userId,clear=true)=>{let session=this.sessions.private[sessionId];if(!session)session=this.sessions.shared[sessionId];if(session){if(this.sessions.private[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.private[sessionId];delete this.users[userId].sessions[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId].sessions[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){delete session.settings.host;delete session.data.shared;session.data.shared={};this.swapHost(session)}}}return true}return false};this.swapHost=(session,newHostId)=>{if(typeof session==="string"){if(this.sessions.private[session])session=this.sessions.private[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];return true}return false};this.deleteSession=(sessionId,userId)=>{let session=this.sessions.private[sessionId];if(!session)session=this.sessions.shared[sessionId];if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user].sessions)delete this.users[user].sessions[sessionId]}if(this.sessions.private[sessionId])delete this.sessions.private[sessionId];else if(this.sessions.shared[sessionId])delete this.sessions.private[sessionId]}}return true};this.subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.private[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}if(typeof session.onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)session.onopen(session,userId);this.unsubscribe("joinSession",sub)})}if(typeof session==="object"){if(onmessage)session.onmessage=onmessage;if(onopen)session.onclose=onopen;if(onclose)session.onclose=onclose}return session};this.sessionUpdateCheck=(transmit=true)=>{let updates={private:{},shared:{}};for(const session in this.sessions.private){const sesh=this.sessions.private[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.private[session];break}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(this.users[sesh.source][prop]){if(this.sessions.private[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.users[sesh.source][prop]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.private[session]?.data?.[prop])delete this.sessions.private[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.private[session].data,updateObj.data);updates.private[sesh._id]=updateObj}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const privateData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.private?.[user])delete sesh.data.shared[user];if(sesh.settings.host===user)this.swapHost(sesh);updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}if(user!==sesh.settings.host){privateData[user]={};for(const prop in sesh.settings.propnames){if(this.users[user][prop]){if(sesh.data?.private&&!(user in sesh.data.private)){if(typeof this.users[user][prop]==="object")privateData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else privateData[user][prop]=this.users[user][prop]}else if(typeof privateData[user][prop]==="object"&&sesh.data){if(this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))privateData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.private?.[prop]!==this.users[user][prop])privateData[user][prop]=this.users[user][prop]}else if(sesh.data?.private?.[user]?.[prop])delete sesh.data.private[user][prop]}if(Object.keys(privateData[user]).length===0)delete privateData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(this.users[user][prop]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])))sharedData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]?.[prop])delete sesh.data.shared[user][prop]}}}if(Object.keys(privateData).length>0){updateObj.data.private=privateData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.private?.[user])delete sesh.data.shared[user];if(sesh.settings.host===user)this.swapHost(sesh);updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(this.users[user][prop]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user][prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]?.[prop])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.private)updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){this.recursivelyAssign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.private){this.recursivelyAssign(this.sessions.shared[session].data?.private,updateObj.data.private)}}if(Object.keys(updates.private).length===0)delete updates.private;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};this.transmitSessionUpdates=updates=>{let users={};if(updates.private){for(const s in updates.private){let session=this.sessions.private[s];if(session?.settings){let u=session.settings.listener;if(!users[u])users[u]={private:{}};else if(!users[u].private)users[u].private={};users[u].private[s]=updates.private[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){let copy;if(session.settings.host){copy=Object.assign({},updates.shared[s]);delete copy.data.private}for(const u in session.settings.users){if(!users[u])users[u]={shared:{}};else if(!users[u].shared)users[u].shared={};if(session.settings.host){if(u!==session.settings.host){users[u].shared[s]=copy}else users[u].shared[s]=updates.shared[s]}else users[u].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u in users){message.args=[u,users[u]];if(this.users[u].send)this.users[u].send(JSON.stringify(message));this.setState({[u]:Object.create(message)})}return users};this.receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(!user)return void 0;if(!user.sessions)user.sessions={};if(update.private){for(const key in update.private){if(!user.sessions[key])continue;this.recursivelyAssign(user.sessions[key].data,update.private[key].data);if(user.sessions[key].onmessage)user.sessions[key].onmessage(user.sessions[key],user._id)}}if(update.shared){for(const key in update.shared){if(!user.sessions[key])continue;if(update.shared[key].settings.users)user.sessions[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)user.sessions[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.private)this.recursivelyAssign(user.sessions[key].data.private,update.shared[key].data.private);if(update.shared[key].data.shared)this.recursivelyAssign(user.sessions[key].data.shared,update.shared[key].data.shared);if(user.sessions[key].onmessage)user.sessions[key].onmessage(user.sessions[key],user._id)}}return user}};this.getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};this.userUpdateCheck=user=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});return updateObj}}return void 0};this.setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};this.STREAMLATEST=0;this.STREAMALLLATEST=1;this.streamSettings={};this.streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};this.setStreamFunc=(name,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name].settings[key])this.streamSettings[name].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name].settings[key].callback=callback;if(!this.streamSettings[name].settings[key].callback)this.streamSettings[name].settings[key].callback=this.streamFunctions.allLatestValues;return true};this.addStreamFunc=(name,callback=data=>{})=>{this.streamFunctions[name]=callback};this.setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};this.removeStream=(streamName,key)=>{if(streamName&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};this.updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};this.getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};this.getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};this.streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}};this.userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};this.sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};this.setLoaders(loaders);this.setTree(this);if(users)this.users=users}getFirstMatch(obj1,obj2){for(const i in obj1){for(const j in obj2){if(i===j)return i}}return false}};var Router=class extends Service{constructor(options){super(options);this.name="router";this.connections={};this.sources={};this.services={};this.serviceConnections={};this.users={};this.addUser=async(info,connections,config,receiving)=>{if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}let user=Object.assign({},info);if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>3e3){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;this.users[user._id]=user;if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i)=>{if(connections[k]?._id){connectionIds[`${i}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};this.getConnection=(sourceId,hasMethod)=>{if(this.sources[sourceId]){if(this.order){for(let i=0;i{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}if(pass){if(this.getConnection(this.sources[sourceId][key],hasMethod))found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}}};this.addConnection=(options,source)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};this.removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};this.routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};this.addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};this.openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!info._id){if(performance.now()-start>3e3){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>3e3){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}if(connection._id)return this.addConnection({connection,service},source)}}};this.terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};this.subscribeThroughConnection=(route,relay,endpoint,callback,...args)=>{if(typeof relay==="string"){relay=this.getConnection(relay,"run")}if(typeof relay==="object")return new Promise((res,rej)=>{relay.run("routeConnections",[route,endpoint,relay._id,...args]).then(sub=>{this.__node.state.subscribeTrigger(endpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[endpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};this.routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,transmitter._id,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};this.setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}};this.setTree(this);if(options){if(options.order)this.order=options.order;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}};export{DOMElement,E2EEService,ECSService,ElementProxyReceiver,EventDispatcher,Graph,GraphNode,HTTPfrontend,ProxyManager,Renderer,Router,SSEfrontend,Service,SessionsService,WSSfrontend,WebRTCfrontend,WorkerService,addCustomElement,algorithms,animate,backprop,bindListener,branching,clearCanvas,createSubprocess,drawFrame,eventHandlers,getAllProperties,htmlloader,initCanvas,initProxyElement,instanceObject,isNativeClass,isTypedArray,loadAlgorithms,loaders,loop,proxyElementWorkerRoutes,recursivelyAssign2 as recursivelyAssign,setDraw,setProps,setupCanvas,spliceTypedArray,startAnim,state,stopAnim,subprocessRoutes,substitute__operator,transferCanvas,transformListenerResult,triggerListenerOncreate,unsafeRoutes,updateCanvas,workerCanvasRoutes}; diff --git a/dist/index.js b/dist/index.js index 184ad865..830610a2 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1 +1 @@ -(()=>{var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i2=l-1;i2>=0;i2--){run(this.triggers[statesubKey][i2].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i2=l-1;i2>=0;i2--){fn(this.triggers[key][i2])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.sub===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps2=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys2=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys2){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps2();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys2=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys2.push(...nonArrowFunctions);keys2=keys2.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys2){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys2=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t2=>{for(const key in t2){this.unsubscribe(t2[key]);this.delete(t2[key].__node.tag);delete this.__node.roots[t2[key].__node.tag];this.delete(key);delete this.__node.roots[key];t2[key].__node.tag=t2[key].__node.tag.substring(t2[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t2[key])}t2[key].__callDisconnected();if(t2[key].__children){recursiveRemove(t2[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i2)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i2]={__callback:inp=>{return inp},__args:void 0,idx:i2}}else if(typeof a==="string"){args[i2]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i2}}else if(typeof a==="function"){let fn2=a;args[i2]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i2}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i2}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i2}}else{input={__callback:input,__args:void 0,idx:i2}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i2}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i2}}}return input};args[i2]=recursivelyCreateCallback(a)}else{let arg=a;args[i2]={__callback:()=>{return arg},__args:void 0,idx:i2}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i2=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i2,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function getFnParamNames(fn){if(typeof fn!=="string")fn=fn.toString();const arrowMatch=fn.match(/\(?[^]*?\)?\s*=>/);if(arrowMatch)return arrowMatch[0].replace(/[()\s]/gi,"").replace("=>","").split(",");const match=fn.match(/\([^]*?\)/);return match?match[0].replace(/[()\s]/gi,"").split(","):[]}var getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}function reconstructObject(json="{}"){try{let parsed=typeof json==="string"?JSON.parse(json):json;const parseObj=obj=>{for(const prop in obj){if(typeof obj[prop]==="string"){let funcParsed=parseFunctionFromText(obj[prop]);if(typeof funcParsed==="function"){obj[prop]=funcParsed}}else if(typeof obj[prop]==="object"){parseObj(obj[prop])}}return obj};return parseObj(parsed)}catch(err){console.error(err);return void 0}}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs3(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value==="function"?value.toString():value,path.join("."))}}}return typeof value==="function"?value.toString():value}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str2;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str2=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str2=properties.toString();else if(typeof properties==="string")str2=properties;if(str2){if(connection.run)return connection.run("setNode",[str2]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str2},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str2}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(template);if(node){nodeTemplates[node.__node.tag]=template;return node.__node?.tag}else return false}else return false},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str2=recursivelyStringifyFunctions(properties);return str2},getListenerJSON:function(){const triggers=this.__node.state.triggers;let result={};for(const key in triggers){triggers[key].forEach(trigger=>{let t2=trigger;if(!result[t2.target])result[t2.target]={};let l=t2.source+(t2.key?"."+t2.key:"");result[t2.target][l]={__callback:t2.__callback};if(t2.__args)result[t2.target][l].__args=t2.__args;if(t2.subInput)result[t2.target][l].subInput=t2.subInput})}return result},makeRootTransferrable:function(){let roots={};for(const r in this.__node.graph.__node.roots){let properties=this.__node.graph.__node.roots[r];if(typeof properties==="function"){roots[r]=properties.toString()}else if(typeof properties!=="object"){roots[r]=properties}else{roots[r]={};let keys2=Object.getOwnPropertyNames(properties).filter(v=>!objProps2.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter(v=>!objProps2.includes(v));keys2.push(...nonArrowFunctions);for(const key of keys2){if(typeof properties[key]==="function"){roots[r][key]=properties[key].toString()}else if(typeof properties[key]==="object")roots[r][key]=stringifyWithFunctionsAndCircularRefs(properties[key]);else roots[r][key]=properties[key]}}}return roots},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key of properties){if(typeof node[key]==="function"){let str2=node[key].toString();let isNative=str2.indexOf("[native code]")>-1;result[key]={type:"function",args:getFnParamNames(node[key]),native:isNative}}else result[key]=typeof node[key]}return result}return void 0},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]?.type==="function"){if(props[key].native||props[key].args){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{proxy[key]=()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})}}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};if(connection.run)return connection.run("receiveClass",[str2,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str2,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str2,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str2=fn.toString();let message={route:"setNode",args:[str2,fnName]};if(connection.run)return connection.run("setNode",[str2,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str2,fnName]},void 0);return new Promise(r=>r(fnName))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str2,fnName]}));return new Promise(r=>r(fnName))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var objProps2=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var ECSService=class extends Service{entities={};systems={};entityMap=new Map;entityKeyMap=new Map;order=[];animating=false;entityCt=0;systemCt=0;constructor(options){super(options);this.load(this);if(options?.systems)for(const key in options.systems){this.addSystem(options.systems[key],void 0,void 0,void 0,void 0,options.order)}if(options?.entities){for(const key in options.entities){this.addEntity(options.entities[key],options.entities[key].components)}}}updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};stop=()=>{this.animating=false};start=filter=>{this.animateEntities(filter)};addEntities=(prototype,components={},count=1)=>{let i2=0;let newEntities={};while(i2{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};removeEntities(entities){if(!Array.isArray(entities))entities=Object.keys(entities);entities.forEach(t2=>{this.removeEntity(t2)})}removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};bufferValues=(entities,property,keys2,buffer)=>{if(!Array.isArray(keys2)&&typeof keys2==="object")keys2=Object.keys(keys2);if(!buffer){let entkeys=Object.keys(entities);if(keys2)buffer=new Float32Array(entkeys.length*keys2.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys2=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys2.length)}else buffer=new Float32Array(entkeys.length)}}let i2=0;for(const key in entities){if(entities[key][property]){if(keys2){for(let j=0;j{combinedHTML+=string;if(args[i2]instanceof HTMLElement){combinedHTML+=``}else if(args[i2]!==void 0){combinedHTML+=args[i2]}};strings.forEach(withStr);template.innerHTML=combinedHTML;let dummyNodes=Array.from(template.content.querySelectorAll(`#${rand}`));const withArg=(arg,i2)=>{if(arg instanceof HTMLElement){let dummyNode=dummyNodes[i2];if(dummyNode){dummyNode.parentNode.replaceChild(arg,dummyNode)}}};args.forEach(withArg);if(elm){elm.appendChild(template.content);return elm}return template.content}}function xml(strings,...args){return function append(elm,namespace="http://www.w3.org/1999/xhtml"){let parser=new DOMParser;let serializer=new XMLSerializer;let xmlDoc=parser.parseFromString('',"application/xml");let template=xmlDoc.createElement("template");xmlDoc.documentElement.appendChild(template);for(let i2=0;i2{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if(node.tagName||node.__element){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var dummy=html``;var DOMElement=class extends HTMLElement{useShadow=false;FRAGMENT;STYLE;attachedShadow=false;static get tag(){return this.name.toLowerCase()+"-"}obsAttributes=["props","options","onchanged","onresize","ondelete","oncreate","template"];props={};static addElement(tag=this.tag,cls=this,extend=void 0){addCustomElement(cls,tag,extend)}attributeChangedCallback=(name2,old,val)=>{if(name2==="onchanged"){let onchanged=val;if(typeof onchanged==="string")onchanged=parseFunctionFromText2(onchanged);if(typeof onchanged==="function"){this.onchanged=onchanged;this.state.data.props=this.props;this.state.unsubscribeTrigger("props");this.state.subscribeTrigger("props",this.onchanged);let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)})}}else if(name2==="onresize"){let onresize=val;if(typeof onresize==="string")onresize=parseFunctionFromText2(onresize);if(typeof onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this.props,this)};this.onresize=onresize;window.addEventListener("resize",this.ONRESIZE)}}else if(name2==="ondelete"){let ondelete=val;if(typeof ondelete==="string")ondelete=parseFunctionFromText2(ondelete);if(typeof ondelete==="function"){this.ondelete=()=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");if(ondelete)ondelete(this.props,this)}}}else if(name2==="oncreate"){let oncreate=val;if(typeof oncreate==="string")oncreate=parseFunctionFromText2(oncreate);if(typeof oncreate==="function"){this.oncreate=oncreate}}else if(name2==="renderonchanged"){let rpc=val;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!=false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}else if(name2==="props"){let newProps=val;if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props})}else if(name2==="template"){let template=val;this.template=template;this.render(this.props);let created=new CustomEvent("created",{detail:{props:this.props}});this.dispatchEvent(created)}else{let parsed=val;if(name2.includes("eval_")){name2=name2.split("_");name2.shift();name2=name2.join();parsed=parseFunctionFromText2(val)}else if(typeof val==="string"){try{parsed=JSON.parse(val)}catch(err){parsed=val}}this[name2]=parsed;if(name2!=="props"&&this.props)this.props[name2]=parsed}};connectedCallback(){if(!this.props)this.props={};let newProps=this.getAttribute("props");if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props});Array.from(this.attributes).forEach(att=>{let name2=att.name;let parsed=att.value;if(name2.includes("eval_")||name2.includes("()")){if(name2.includes("eval_"))name2=name2.split("_");else if(name2.includes("()"))name2=name2.substring(0,name2.indexOf("("));name2.shift();name2=name2.join();parsed=parseFunctionFromText2(att.value)}else if(typeof att.value==="string"){try{parsed=JSON.parse(att.value)}catch(err){parsed=att.value}}if(!this[name2]){Object.defineProperties(this,att,{value:parsed,writable:true,get(){return this[name2]},set(val){this.setAttribute(name2,val)}})}this[name2]=parsed;if(name2!=="props")this.props[name2]=parsed;this.obsAttributes.push(name2)});let resizeevent=new CustomEvent("resized",{detail:{props:this.props,self:this}});let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});let deleted=new CustomEvent("deleted",{detail:{props:this.props,self:this}});let created=new CustomEvent("created",{detail:{props:this.props,self:this}});this.render(this.props);this.dispatchEvent(created);this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)});if(typeof this.onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this,this.props);this.dispatchEvent(resizeevent)};window.addEventListener("resize",this.ONRESIZE)}if(typeof this.ondelete==="function"){let ondelete=this.ondelete;this.ondelete=(props=this.props)=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");this.dispatchEvent(deleted);ondelete(this,props)}}if(typeof this.onchanged==="function"){this.state.data.props=this.props;this.state.subscribeTrigger("props",this.onchanged)}if(this.renderonchanged){let rpc=this.renderonchanged;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!==false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}}constructor(){super()}delete=()=>{this.remove();if(typeof this.ondelete==="function")this.ondelete(this.props)};render=(props=this.props)=>{const t2=document.createElement("template");let usingHTMLFunction=this.template.prototype?.constructor?.name==dummy.prototype.constructor.name;if(typeof this.template==="function"){if(usingHTMLFunction){this.template(t2.content)}else this.templateResult=this.template(this,props)}else this.templateResult=this.template;if(this.styles)this.templateResult=`${this.templateResult}`;if(!usingHTMLFunction){if(typeof this.templateResult==="string")t2.innerHTML=this.templateResult;else if(this.templateResult instanceof HTMLElement||this.templateResult instanceof DocumentFragment){if(this.templateResult.parentNode){this.templateResult.parentNode.removeChild(this.templateResult)}t2.content.appendChild(this.templateResult)}}const fragment=t2.content;if(this.FRAGMENT){if(this.useShadow){if(this.STYLE)this.shadowRoot.removeChild(this.STYLE);this.FRAGMENT.forEach(c=>{this.shadowRoot.removeChild(c)})}else this.FRAGMENT.forEach(c=>{this.removeChild(c)})}if(this.useShadow){if(!this.attachedShadow){this.attachShadow({mode:"open"}).innerHTML="";this.attachedShadow=true}if(this.styles){let style=document.createElement("style");style.textContent=this.styles;this.shadowRoot.prepend(style);this.STYLE=style}let len=fragment.childNodes.length;this.shadowRoot.prepend(fragment);this.FRAGMENT=Array.from(this.shadowRoot.childNodes).slice(0,len)}else{let len=fragment.childNodes.length;this.prepend(fragment);this.FRAGMENT=Array.from(this.childNodes).slice(0,len)}let rendered=new CustomEvent("rendered",{detail:{props:this.props,self:this}});this.dispatchEvent(rendered);if(this.oncreate)this.oncreate(this,props)};state={pushToState:{},data:{},triggers:{},setState(updateObj){Object.assign(this.pushToState,updateObj);if(Object.keys(this.triggers).length>0){for(const prop of Object.getOwnPropertyNames(this.triggers)){if(this.pushToState[prop]){this.data[prop]=this.pushToState[prop];delete this.pushToState[prop];this.triggers[prop].forEach(obj=>{obj.onchanged(this.data[prop])})}}}return this.pushToState},subscribeTrigger(key,onchanged=res=>{}){if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({idx:l,onchanged});return this.triggers[key].length-1}else return void 0},unsubscribeTrigger(key,sub){let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let idx=void 0;let obj=triggers.find((o,i2)=>{if(o.idx===sub){idx=i2;return true}});if(obj)triggers.splice(idx,1);return true}}},subscribeTriggerOnce(key=void 0,onchanged=value=>{}){let sub;let changed=value=>{onchanged(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)}}};function addCustomElement(cls,tag,extend=null){try{if(extend){if(tag)window.customElements.define(tag,cls,{extends:extend});else window.customElements.define(cls.name.toLowerCase()+"-",cls,{extends:extend})}else{if(tag)window.customElements.define(tag,cls);else window.customElements.define(cls.name.toLowerCase()+"-",cls)}}catch(err){}}function parseFunctionFromText2(method){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf(")");return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;try{if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch(err){newFunc=(0,eval)(method)}}}}catch(err){}return newFunc}var wchtmlloader=(node,parent,graph,roots,properties,key)=>{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if((node.tagName||node.__element)&&!node.__props&&!node.__template){if(node.tagName)node.__props=document.createElement(node.tagName);else if(node.__element){if(node.__element instanceof HTMLElement)node.__props=node.__element;else node.__props=document.createElement(node.__element)}if(!(node.__props instanceof HTMLElement))return}else if(typeof node.__css==="string"){node.__template+=``;delete node.__css}const registerElement=(node2,tagNameOverride)=>{if(isNativeClass(node2))node2=new node2;else if(typeof node2==="function"&&!node2.__node)node2=node2();class CustomElement extends DOMElement{props=node2.props;styles=node2.__css;useShadow=node2.useShadow;template=node2.__template;oncreate=node2.__onrender;onresize=node2.__onresize;ondelete=node2.__onremove;renderonchanged=node2.__renderonchanged}if(tagNameOverride?.includes("-"))node2.tagName=tagNameOverride;else if(node2.__element)node2.tagName=node2.__element;if(!node2.tagName)node2.tagName=`element${Math.floor(Math.random()*1e15)}-`;CustomElement.addElement(node2.tagName)};if("__components"in node){if(Array.isArray(node.__components))node.__components.forEach(c=>registerElement(c));else Object.entries(node.__components).forEach(([k,c])=>registerElement(c,k.includes("-")?k:void 0))}if("__template"in node){if(typeof node.__renderonchanged==="function"){let renderonchanged=node.__renderonchanged;node.__renderonchanged=element=>{renderonchanged.call(element.node,element)}}registerElement(node);node.__props=document.createElement(node.tagName);let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",node.__attributes[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)}}}}}else if(node.__props instanceof HTMLElement){let cpy=Object.assign({},node);let keys2=Object.getOwnPropertyNames(cpy);for(const k of keys2){if(k==="style"&&typeof node[k]==="object"){Object.assign(node.__props.style,cpy[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=cpy[k]}if(node.__attributes){for(const k in node.__attributes){if(k==="style"&&typeof node.__attributes[k]==="object"){Object.assign(node.__props.style,node.__attributes[k])}else if(k==="className")node.__props.setAttribute("class",cpy[k]);else if(!k.includes("outer"))node.__props[k]=node.__attributes[k]}}node.__proxyObject(node.__props);for(const k of keys2){if(typeof cpy[k]==="function"){let fn=cpy[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}if(node.__attributes){for(const k in node.__attributes){if(typeof cpy[k]==="function"){let fn=node.__attributes[k];node.__props[k]=(...inp)=>{let res=fn(...inp);node.__node.state.triggerEvent(node.__node.unique+"."+k,res)};node[k]=node.__props[k]}}}if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__props.node=node;node.__addOnconnected(n=>{if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement)&&n.__props.parentNode)n.__props.remove();if(properties.parentNode){if(typeof properties.parentNode==="string"&&document.getElementById(properties.parentNode))document.getElementById(properties.parentNode)?.appendChild(n.__props);else if(properties.parentNode instanceof HTMLElement)properties.parentNode.appendChild(n.__props)}else if(parent?.__props instanceof HTMLElement){parent.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(properties.parentNode)){document.getElementById(properties.parentNode)?.appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender&&!(node.__props instanceof DOMElement)&&!node.__template)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return new sjcl.hash.sha256().update(a).finalize()};sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=sjcl_default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};static generateSecret(){return sjcl_default.codec.base64.fromBits(sjcl_default.random.randomWords(8,10))}encrypt(message,key){message=sjcl_default.encrypt(key,message).cipher;return message}decrypt(message,key){message=sjcl_default.decrypt(key,message);return message}encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=sjcl_default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message}};var HTTPfrontend=class _HTTPfrontend extends Service{name="http";fetchProxied=false;listening={};constructor(options,path,fetched){super(options);this.load(this);this.listen(path,fetched)}static request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};GET=(url2="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url:url2,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{let obj=message;if(typeof obj==="object"&&!obj.byteLength){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url2);return this.POST(message,url2)};transponder=(url2,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url:url2,data:message,responseType:type,onload:ev=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}}};var SSEfrontend=class extends Service{name="sse";eventsources={};connections={eventsources:this.eventsources};constructor(options){super(options);this.load(this)}openSSE=options=>{let source=new EventSource(options.url);let sse={source,type:"eventsource",...options};if(!("keepState"in options))options.keepState=true;if(!options.events)options.events={};let close;if(options.events.close){close=options.events.close}options.events.close=ev=>{if(sse.onclose)sse.onclose(ev,sse);if(close)close(ev,sse);delete this.eventsources[options.url]};let open;if(options.events.open){open=options.events.open}options.events.open=ev=>{if(sse.onopen)sse.onopen(ev,sse);if(open)open(ev,sse)};let error;if(options.events.error){error=options.events.error}options.events.error=ev=>{if(sse.onerror)sse.onerror(ev,sse);if(error)error(ev,sse)};let message;if(options.events.message){message=options.events.message}if(!sse.onmessage){sse.onmessage=(ev,sse2)=>{let data=ev.data;if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"&&sse2){sse2._id=data.args;options.events.message=(e,sse3)=>{const result2=this.receive(e.data,sse3);if(options.keepState)this.setState({[options.url]:e.data})}}}}}const result=this.receive(ev.data,sse2);if(options.keepState)this.setState({[options.url]:data})}}options.events.message=ev=>{if(sse.onmessage)sse.onmessage(ev,sse);if(message)message(ev,sse)};if(!options.events.error)options.events.error=(ev,sse2)=>{this.terminate(sse2);delete this.eventsources[options.url]};if(options.events){if(!options.evoptions)options.evoptions=false;for(const key in options.events){if(typeof options.events[key]!=="function"){options.events[key]=ev=>{const result=this.receive(ev.data,sse);if(options.keepState)this.setState({[options.url]:result})}}else{let l=options.events[key];options.events[key]=ev=>{l(ev,sse)}}source.addEventListener(key,options.events[key],options.evoptions)}}let send=message2=>{return this.transmit(message2,options.url)};let request=(message2,method,sessionId)=>{return this.request(message2,options.url,method,sessionId)};let post=(route,args,method)=>{let message2={route,args};if(method)message2.method=method;return this.transmit(message2,options.url)};let run=(route,args,method,sessionId)=>{return this.request({route,args},options.url,method,sessionId)};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSSE(route,options.url,callback,args,key,subInput,sse._id)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options.url)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;this.eventsources[options.url]=sse;return sse};open=this.openSSE;POST=(message,url2="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="number"||typeof message==="object"&&!message.byteLength&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=HTTPfrontend.request({method:"POST",url:url2,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url2 instanceof URL)url2=url2.toString();this.setState({[url2]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};transmit=(message,url2)=>{return this.POST(message,url2,"json")};request=(message,url2,method,sessionId)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,url2,callbackId,sessionId]};if(method)req.method=method;let evs=this.eventsources[url2].source;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){evs.removeEventListener("message",onmessage);res(data.args)}}};evs.addEventListener("message",onmessage);this.POST(message,url2,"json")})};runRequest=(message,url2,callbackId,sessionId)=>{let res=this.receive(message);if(url2){if(res instanceof Promise){res.then(r=>{let message2={args:r,callbackId,sessionId};this.POST(message2,url2,"json")})}else{let message2={args:res,callbackId,sessionId};this.POST(message2,url2,"json")}}return res};subscribeSSE=(route,url2,args,key,subInput)=>{if(this.restrict?.[route])return void 0;return this.subscribe(route,res=>{this.POST(res,url2,"json")},args,key,subInput)};subscribeToSSE=(route,url2,callback,args,key,subInput,sessionId)=>{if(url2){this.__node.state.subscribeEvent(url2,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[url2]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.eventsources[url2].run("subscribeSSE",[route,url2,args,key,subInput,sessionId])}};terminate=sse=>{if(typeof sse==="string"){let str2=sse;sse=this.eventsources[sse];delete this.eventsources[str2]}if(!sse)return;if(typeof sse==="object"){if(sse.source){sse=sse.source}if(sse instanceof EventSource){if(sse.readyState!==2)sse.close()}}}};var WSSfrontend=class extends Service{name="wss";sockets={};connections={sockets:this.sockets};constructor(options){super(options);this.load(this)}loadWebSocketRoute=node=>{let wsInfo=this.openWS(node);if(!wsInfo.__ondisconnected){wsInfo.__addOndisconnected(()=>{wsInfo.terminate()})}if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.post(node.callback,args);else return wsInfo.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)wsInfo.send(args);else return wsInfo.request(args)}}}if(!node.__ondisconnected){let ondelete=rt=>{rt?.terminate()};node.__addOndisconnected(ondelete)}return wsInfo};socketloader={"websockets":(node,parent,graph,roots)=>{node._id=node.__node.tag;let ws=this.loadWebSocketRoute(node);Object.assign(node,ws);if(parent&&parent.type==="socket"){let parentWs=this.sockets[parent._id];if(node.parentRoute){parentWs.subscribe(node.parentRoute,node.__operator)}}}};openWS=(options={host:"localhost",port:7e3,path:void 0,protocol:"ws"})=>{let protocol=options.protocol;if(!protocol)protocol="ws";let address=`${protocol}://${options.host}`;if(!("keepState"in options))options.keepState=true;if(options.port)address+=":"+options.port;if(options.path&&!options.path?.startsWith("/"))address+="/";if(options.path)address+=options.path;if(this.sockets[address]?.socket){if(this.sockets[address].socket.readyState===this.sockets[address].socket.OPEN)this.sockets[address].socket.close()}const socket=new WebSocket(address);if(!options.onmessage){if(!options._id){options.onmessage=(data,ws,wsinfo)=>{if(data){if(typeof data==="string"){if(options.debug){console.log("Message from ",address,": ",data)}let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;options.onmessage=(data2,ws2,wsinfo2)=>{if(options.debug){console.log("Message from ",address,": ",data2)}this.receive(data2);if(options.keepState){this.setState({[address]:data2})}}}}}}let res=this.receive(data);if(options.keepState)this.setState({[address]:data})}}else{options.onmessage=(data,ws,wsinfo)=>{if(options.debug){console.log("Message from ",socket.url,": ",data)}this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}}}}if(options.onmessage){socket.addEventListener("message",ev=>{this.sockets[address].onmessage(ev.data,socket,this.sockets[address])})}socket.addEventListener("open",ev=>{if(this.sockets[address].onopen)this.sockets[address].onopen(ev,socket,this.sockets[address])});socket.addEventListener("close",ev=>{let obj=this.sockets[address];let onclose=obj.onclose;delete this.sockets[address];this.remove(address);if(onclose)onclose(ev,socket,obj)});socket.addEventListener("error",ev=>{if(this.sockets[address].onerror)this.sockets[address].onerror(ev,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},this.sockets[address]._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,this.sockets[address]._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToSocket(route,this.sockets[address]._id,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(address)};Object.assign(options,{type:"socket",socket,address,send,post,run,request,subscribe,unsubscribe,terminate});if(!(options instanceof GraphNode)){let node=this.add(options);node.__addOndisconnected(function(){terminate()});options=node}this.sockets[address]=options;return options};open=this.openWS;transmit=(data,ws)=>{if(typeof data==="object"&&(data?.route||data?.node||typeof data.arrayBuffer!=="function"&&typeof data.byteLength!=="number")||typeof data==="number")data=JSON.stringify(data);if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}if(ws instanceof WebSocket&&ws?.readyState===1)ws.send(data);return true};terminate=ws=>{let str2;if(!ws){let keys2=Object.keys(this.sockets);for(const key in keys2){this.terminate(key)}}else if(typeof ws==="string"){str2=ws;for(const k in this.sockets){if(k.includes(ws)||this.sockets[k]._id===k){ws=this.sockets[k].socket;break}}}if(ws instanceof WebSocket){if(ws.readyState===ws.OPEN)ws.close();if(this.get(str2?str2:ws.url))this.remove(str2?str2:ws.url)}return true};request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(typeof ws==="string"){for(const s in this.sockets){if(s===ws||this.sockets[s]._id===ws){ws=this.sockets[s].socket;break}}}if(ws){if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))}}return res};subscribeSocket=(route,socket,args,key,subInput)=>{if(this.restrict?.[route])return void 0;if(typeof socket==="string"&&this.sockets[socket]){socket=this.sockets[socket].socket}if(typeof socket==="object"){return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},args,key,subInput)}};subscribeToSocket=(route,socketId,callback,args,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeEvent(socketId,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[socketId]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,args,key,subInput]})}}};var WebRTCfrontend=class extends Service{name="webrtc";rtc={};unanswered={};iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun1.l.google.com:19302"]},{urls:["stun:stun2.l.google.com:19302"]},{urls:["stun:stun3.l.google.com:19302"]},{urls:["stun:stun4.l.google.com:19302"]}];connections={rtc:this.rtc};constructor(options,iceServers){super(options);if(iceServers)this.iceServers=iceServers;this.load(this)}openRTC=async options=>{if(!options)options={};if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(!options.config)options.config={iceServers:this.iceServers};if(!this.rtc[options._id]){let rtc=new RTCPeerConnection(options.config);if(!options.channels)options.channels={"data":true};let firstChannel;for(const key in options.channels){firstChannel=key;break}let send=message=>{return this.transmit(message,options._id,options.channels[firstChannel])};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options._id,options.channels[firstChannel])};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let subscribe=(route,callback,args,key,subInput,channelId)=>{return this.subscribeToRTC(route,options._id,channelId?channelId:firstChannel,callback,args,key,subInput)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.rtc[options._id]={rtc,_id:options._id,request,run,post,send,subscribe,unsubscribe,terminate,graph:this,...options};const setMessageChannelHandle=channel=>{if(!this.rtc[options._id].ondata){this.rtc[options._id].ondata=mev=>{this.receive(mev.data,channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})};channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}else{channel.addEventListener("message",mev=>{if(this.rtc[options._id].ondata)this.rtc[options._id].ondata(mev,channel,this.rtc[options._id])})}};if(this.rtc[options._id].channels){for(const channel in this.rtc[options._id].channels){if(this.rtc[options._id].channels[channel]instanceof RTCDataChannel){}else if(typeof this.rtc[options._id].channels[channel]==="object"){this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel,this.rtc[options._id].channels[channel])}else{this.rtc[options._id].channels[channel]=this.addDataChannel(rtc,channel)}setMessageChannelHandle(this.rtc[options._id].channels[channel])}}rtc.ontrack=ev=>{if(!this.rtc[options._id].receivers)this.rtc[options._id].receivers=[];this.rtc[options._id].receivers.push(ev.receiver);if(!this.rtc[options._id].streams)this.rtc[options._id].streams=[];this.rtc[options._id].streams.push(...ev.streams);let rlength=this.rtc[options._id].receivers.length;let slength=this.rtc[options._id].streams.length;ev.streams.forEach(s=>{s.addEventListener("removetrack",ev2=>{this.rtc[options._id].receivers[rlength]=void 0;this.rtc[options._id].streams[slength]=void 0;if(this.rtc[options._id].removetrack)this.rtc[options._id].removetrack(ev2)})});if(this.rtc[options._id].ontrack)this.rtc[options._id].ontrack(ev)};rtc.ondatachannel=ev=>{this.rtc[options._id].channels[ev.channel.label]=ev.channel;setMessageChannelHandle(ev.channel);if(this.rtc[options._id].ondatachannel)this.rtc[options._id].ondatachannel(ev)};rtc.onicecandidate=ev=>{if(this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate(ev)};rtc.onicecandidateerror=ev=>{if(this.rtc[options._id].onicecandidateerror)this.rtc[options._id].onicecandidateerror(ev)};let initialOffer=this.rtc[options._id].description===void 0;rtc.onnegotiationneeded=async ev=>{if(!initialOffer){const offer=await rtc.createOffer(this.rtc[options._id].offer);if(rtc.signalingState!="stable")return;await rtc.setLocalDescription(offer);if(this.rtc[options._id].onnegotiationneeded)this.rtc[options._id].onnegotiationneeded(ev,rtc.localDescription)}};rtc.oniceconnectionstatechange=ev=>{if(this.rtc[options._id].oniceconnectionstatechange)this.rtc[options._id].oniceconnectionstatechange(ev)};rtc.onconnectionstatechange=ev=>{if(this.rtc[options._id].onconnectionstatechange)this.rtc[options._id].onconnectionstatechange(ev)};rtc.addEventListener("connectionstatechange",ev=>{if(rtc.connectionState==="closed"||rtc.connectionState==="failed"){if(this.rtc[options._id].onclose){this.rtc[options._id].onclose(this.rtc[options._id])}delete this.rtc[options._id]}});if(!this.rtc[options._id].onicecandidate)this.rtc[options._id].onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].candidates)this.rtc[options._id].candidates={};this.rtc[options._id].candidates[`candidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};if(!options.description)return await new Promise((res,rej)=>{this.rtc[options._id].rtc.createOffer(options.offer).then(offer=>this.rtc[options._id].rtc.setLocalDescription(offer)).then(()=>{initialOffer=false;res(this.rtc[options._id])})})}else{Object.assign(this.rtc[options._id],options)}if(options.description){this.rtc[options._id].polite=true;await this.negotiateCall(options._id,options.description,true)}if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);this.rtc[options._id].rtc.addIceCandidate(candidate).catch(console.error)}}return this.rtc[options._id]};open=this.openRTC;addIceCandidate=(rtc,candidate)=>{if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof candidate==="string")candidate=JSON.parse(decodeURIComponent(candidate));if(rtc&&rtc.remoteDescription)return rtc.addIceCandidate(candidate)};receiveCallInformation=async options=>{if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(this.rtc[options._id]){if(options.candidates){for(const key in options.candidates)this.addIceCandidate(this.rtc[options._id].rtc,options.candidates[key]);delete options.candidates}Object.assign(this.rtc[options._id],options)}else if(this.unanswered[options._id]){this.recursivelyAssign(this.unanswered[options._id],options)}else this.unanswered[options._id]=options;return options._id};answerCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return this.openRTC(options)};rejectCall=options=>{if(typeof options==="string")options=this.unanswered[options];delete this.unanswered[options._id];return true};negotiateCall=async(rtc,description,polite)=>{if(typeof rtc==="string"){if(polite===void 0)polite=this.rtc[rtc].description!==void 0;rtc=this.rtc[rtc].rtc}if(typeof description==="string")description=new RTCSessionDescription(JSON.parse(decodeURIComponent(description)));if(description.type==="offer"&&rtc.signalingState!=="stable"){if(!polite)return;await Promise.all([rtc.setLocalDescription({type:"rollback"}),rtc.setRemoteDescription(description)]);return encodeURIComponent(JSON.stringify(rtc.localDescription))}else{await rtc.setRemoteDescription(description)}if(description.type=="offer"){await rtc.setLocalDescription(await rtc.createAnswer());return encodeURIComponent(JSON.stringify(rtc.localDescription))}};createOffer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc].rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createOffer(options.offer).then(offer=>rtc.setLocalDescription(offer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}createAnswer(rtc,options){if(typeof rtc==="string")rtc=this.rtc[rtc]?.rtc;if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(!rtc)rej(void 0);rtc.createAnswer(options.answer).then(answer=>rtc.setLocalDescription(answer)).then(()=>{let description=encodeURIComponent(JSON.stringify(rtc.localDescription));res(description)})})}answerPeer=(rtc,options)=>{if(typeof rtc==="string"){let cpy=Object.assign(this.rtc[rtc],options);delete cpy.description;delete cpy.candidates;Object.assign(this.rtc[rtc],cpy);rtc=this.rtc[rtc]?.rtc}if(typeof options==="string")options=this.rtc[options];return new Promise((res,rej)=>{if(typeof options.description==="string"){options.description=JSON.parse(decodeURIComponent(options.description))}const description=new RTCSessionDescription(options.description);rtc.setRemoteDescription(description).then(()=>{if(options.candidates){for(const prop in options.candidates){const candidate=new RTCIceCandidate(options.candidates[prop]);if(this.rtc[options._id])this.rtc[options._id].candidates[prop]=options.candidates[prop];rtc.addIceCandidate(candidate).catch(console.error)}}if(description.type==="offer"){this.rtc[options._id].rtc.createAnswer(options.answer).then(a=>{this.rtc[options._id].rtc.setLocalDescription(a)})}res(this.rtc[options._id]?this.rtc[options._id]:rtc)}).catch(rej)})};createStream=options=>{let stream=new MediaStream;for(const key in options){let track=options[key].track;if(!(track instanceof MediaStreamTrack)&&typeof track==="object"){track=new MediaStreamTrack;track.applyConstraints(options[key].track);stream.addTrack(track)}if(track instanceof MediaStreamTrack){stream.addTrack(track);track.onmute=options[key].onmute;track.onunmute=options[key].onunmute;track.onended=options[key].onended}}return stream};addUserMedia=(rtc,options={audio:true,video:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560}]}},info)=>{return new Promise(async(res,rej)=>{let RTCRtpSenders=[];let stream=await navigator.mediaDevices.getUserMedia(options);if(stream){let tracks=stream.getTracks();tracks.forEach(track=>{let sender=rtc.addTrack(track,stream);if(track.kind==="video"&&info){info.videoSender=sender;info.videoStream=stream}if(track.kind==="audio"&&info){info.audioSender=sender;info.audioStream=stream}RTCRtpSenders.push(sender)});let str2=stream;if(info)info.senders=info.senders?[...info.senders,...RTCRtpSenders]:RTCRtpSenders;res(str2)}})};addTrack=(rtc,track,stream)=>{return rtc.addTrack(track,stream)};removeTrack=(rtc,sender)=>{rtc.removeTrack(sender);return true};addDataChannel=(rtc,name2,options)=>{return rtc.createDataChannel(name2,options)};enableAudio=async(call,audioOptions=true)=>{if(call.audioStream)this.disableAudio(call);let stream=await this.addUserMedia(call.rtc,{audio:audioOptions,video:false},call);if(audioOptions?.deviceId)call.audioSender.deviceId=audioOptions.deviceId;return stream};enableVideo=async(call,videoOptions={optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]},includeAudio=false)=>{if(call.videoStream)this.disableVideo(call);let stream=await this.addUserMedia(call.rtc,{audio:includeAudio,video:videoOptions?videoOptions:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560},{minWidth:3840}]}},call);if(videoOptions?.deviceId)call.videoSender.deviceId=videoOptions.deviceId;if(includeAudio){if(includeAudio?.deviceId)call.audioSender.deviceId=includeAudio.deviceId;else if(videoOptions?.deviceId)call.audioSender.deviceId=videoOptions.deviceId}return stream};disableAudio(call){if(call.audioSender){call.senders?.find((s,i2)=>{if(call.audioStream?.getAudioTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.audioSender);call.audioSender=void 0}call.audioStream?.getTracks().forEach(track=>{if(track.kind==="audio")track.stop()});call.audioStream=void 0}disableVideo(call){if(call.videoSender){call.senders?.find((s,i2)=>{if(call.videoStream?.getVideoTracks()[0].id===s.track.id){call.senders.splice(i2,1);return true}});call.rtc.removeTrack(call.videoSender);call.videoSender=void 0}call.videoStream?.getTracks().forEach(track=>{if(track.kind==="video")track.stop()});call.videoStream=void 0}transmit=(data,id,channel)=>{if(typeof data==="object"&&(data.route||data.node||!data.byteLength&&typeof data.arrayBuffer!=="function")||typeof data==="number")data=JSON.stringify(data);if(!channel&&id){let keys2=Object.keys(this.rtc[id].channels);if(keys2[0])channel=this.rtc[id].channels[keys2[0]]}if(typeof channel==="string"){if(id){channel=this.rtc[id].channels[channel]}else{for(const id2 in this.rtc){if(this.rtc[id2].channels[channel]instanceof RTCDataChannel)this.rtc[id2].channels[channel].send(data)}}}if(channel instanceof RTCDataChannel)channel.send(data);return true};terminate=rtc=>{let tx;if(typeof rtc==="string"){let room=this.rtc[rtc];delete this.rtc[rtc];if(room){tx=room.rtc}}else if(typeof rtc==="object"){tx=rtc.rtc}if(rtc instanceof RTCPeerConnection&&rtc.signalingState!=="closed"){rtc.close()}else if(tx&&tx.signalingState!=="closed"){if(tx)tx.close()}return true};request=(message,channel,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){channel.removeEventListener("message",onmessage);res(data.args)}}};channel.addEventListener("message",onmessage);channel.send(JSON.stringify(req))})};runRequest=(message,channelOrRtcId,callbackId)=>{let res=this.receive(message);if(channelOrRtcId){if(typeof channelOrRtcId==="string"){for(const key in this.rtc){if(key===channelOrRtcId){channelOrRtcId=this.rtc[key].channels.data?this.rtc[key].channels.data:this.rtc[key].channels[Object.keys(this.rtc[key].channels)[0]];break}}}if(res instanceof Promise)res.then(v=>{res={args:v,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res));return res});else{res={args:res,callbackId};if(channelOrRtcId instanceof RTCDataChannel)channelOrRtcId.send(JSON.stringify(res))}}return res};subscribeRTC=(route,rtcId,args,key,subInput,channel)=>{if(this.restrict?.[route])return void 0;if(typeof channel==="string"&&this.rtc[rtcId]){channel=this.rtc[rtcId].channels[channel]}else if(!channel){channel=this.rtc[rtcId].channels[Object.keys(this.rtc[rtcId].channels)[0]]}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{channel.send(JSON.stringify({args:r,callbackId:route}))})}else{channel.send(JSON.stringify({args:res,callbackId:route}))}},args,key,subInput)};subscribeToRTC=(route,rtcId,channelId,callback,args,key,subInput)=>{if(typeof channelId==="string"&&this.rtc[rtcId]){let c=this.rtc[rtcId];let channel=c.channels[channelId];if(channel){this.__node.state.subscribeEvent(rtcId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[rtcId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return c.request({route:"subscribeRTC",args:[route,rtcId,args,key,subInput,channelId]})}}}};var browser_default=Worker;var WorkerService=class extends Service{name="worker";workers={};threadRot=0;connections;constructor(options){super();this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.load(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}loadWorkerRoute=(node,routeKey)=>{if(node.workerUrl)node.url=node.workerUrl;if(node._id)node.__node.tag=node._id;if(!node.__node.tag)node.__node.tag=routeKey;node._id=node.__node.tag;let worker;if(this.workers[node._id])worker=this.workers[node._id];else if(node.worker)worker=node.worker;if(!worker){worker=this.addWorker(node)}node.worker=worker;if(!node.__ondisconnected){let ondelete=rt=>{rt.worker?.terminate()};node.__addOndisconnected(ondelete)}if(node.transferFunctions){for(const prop in node.transferFunctions){this.transferFunction(worker,node.transferFunctions[prop],prop)}}if(node.transferClasses){for(const prop in node.transferClasses){this.transferClass(worker,node.transferClasses[prop],prop)}}if(worker){if(!node.__operator){node.__operator=(...args)=>{if(node.callback){if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.post(node.callback,args);else return worker.run(node.callback,args)}else{if(!this.__node.nodes.get(node.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(node.init){worker.run(node.init,node.initArgs,void 0,node.initTransfer)}return worker}};workerloader={"workers":(node,parent,graph,roots)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?._id&&this.workers[rt._id]||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent?.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&roots[rt.__parent]?.worker){roots[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}}return rt}};addDefaultMessageListener=()=>{globalThis.onmessage=ev=>{let result=this.receive(ev.data);if(this.__node.keepState)this.setState({[this.name]:result})}};postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new browser_default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,method,transfer)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,args,key,subInput,blocking)=>{return this.subscribeToWorker(route,options._id,callback,args,key,subInput,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,void 0,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,void 0,workerSubs[key].callback,void 0,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub});console.log(JSON.stringify(workerSubs))}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]).then(console.log)}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev=>{this.receive(ev.data);this.setState({[options._id]:ev.data})};if(!options.onerror){options.onerror=ev=>{console.error(ev.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;let workersettings={worker,__node:{tag:options._id},send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};let node=this.add(workersettings);this.workers[options._id]=node;node.__addOndisconnected(function(){terminate()});return this.workers[options._id]};open=this.addWorker;close=()=>{globalThis.close()};toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof browser_default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys2=Object.keys(this.workers);this.workers[keys2[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys2.length)this.threadRot=0}return message};terminate=worker=>{let onclose;let str2;if(typeof worker==="string"){str2=worker;let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}else if(typeof worker==="object"){if(worker?._id){worker=worker.worker;delete this.workers[worker?._id]}}if(worker instanceof browser_default){worker.terminate();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);if(str2&&this.get(str2))this.remove(str2);return true}return false};establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof browser_default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof browser_default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};runRequest=(message,worker,callbackId,getTransferable=true)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker instanceof browser_default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId},transfer);else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId},transfer)}return res};subscribeWorker=(route,worker,args,key,subInput,blocking,getTransferable=true)=>{if(this.restrict?.[route])return void 0;let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{let transfer=getTransferable?this.getTransferable(r):void 0;if(worker?.postMessage)worker.postMessage({args:r,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route},transfer)})}else{let transfer=getTransferable?this.getTransferable(res):void 0;if(worker?.postMessage)worker.postMessage({args:res,callbackId:route},transfer);else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route},transfer)}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,args,key,subInput)};subscribeToWorker=(route,workerId,callback,args,key,subInput,blocking,getTransferable=true)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeEvent(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,args,key,subInput,blocking,getTransferable])}};triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i2=0;i2{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,args,key,subInput,blocking,getTransferable])};unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof sourceWorker==="object"){return sourceWorker.run("unsubscribe",[sourceRoute,sub])}}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name2 of properties){dst[name2]=src[name2]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};var str=String('(()=>{var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn,preventDefault){if(preventDefault&&event.preventDefault)event.preventDefault();const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id,preventDefault){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent,preventDefault)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev){eventHandlers.keydown(ev,sendEvent,preventDefault)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev){eventHandlers.keyup(ev,sendEvent,preventDefault)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{__listeners;addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};releasePointerCapture=()=>{};getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};focus(){}blur(){}};var ProxyManager=class{targets={};constructor(){if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};getProxy=id=>{return this.targets[id]};handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}if(typeof WorkerGlobalScope!=="undefined"){const routes={...workerCanvasRoutes};self.onmessage=ev=>{if(ev.data.route){if(Array.isArray(ev.data.args)){routes[ev.data.route](...ev.data.args)}else routes[ev.data.route](ev.data.args)}}}var canvas_worker_default=self;})();\n');var url=URL.createObjectURL(new globalThis.Blob([str],{type:"text/javascript"}));var canvas_worker_default=url;function Renderer(options){if(options.worker===true){options.worker=canvas_worker_default}if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id,options.preventDefault);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas instanceof OffscreenCanvas?options.canvas:options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("initProxyElement",options.canvas,worker,options._id,options.preventDefault);else proxy=initProxyElement(options.canvas,worker,options._id,options.preventDefault);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{if(proxy)proxy.terminate();worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(canvasopts.proxy)canvasopts.proxy.terminate();let proxy;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas);canvasopts.proxy=proxy}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText3(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText3(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText3(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText3(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;let proxy;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)proxy=this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxy=proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText3(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText3(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText3(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText3(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}const finishSetup=()=>{canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){let res=s.draw(s,canvas,context);if(res?.then){res.then(()=>{requestAnimationFrame(()=>{draw(s,canvas,context)})})}else requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,proxy,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(canvascontrols.proxy){canvascontrols.proxy.terminate()}if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}};if(typeof canvasOptions.init==="function"){let res=canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);if(res?.then){return new Promise(resolve=>{res.then(()=>{resolve(finishSetup())})})}}return finishSetup()}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts&&props){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText3(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText3(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead3=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead3(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var SessionsService=class extends Service{name="sessions";users={};sessions={oneWay:{},shared:{}};invites={};constructor(options,users){super(options);this.setLoaders(loaders);this.load(this);if(users)this.users=users}getSessionInfo=(sessionIdOrName,userId)=>{if(!sessionIdOrName){return this.sessions.shared}else{if(this.sessions.oneWay[sessionIdOrName]){let s=this.sessions.oneWay[sessionIdOrName];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{oneWay:{[sessionIdOrName]:s}}}}else if(this.sessions.shared[sessionIdOrName]){return{shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};openOneWaySession=(options={},sourceUserId,listenerUserId)=>{if(!options._id){options._id=`oneWay${Math.floor(Math.random()*1e15)}`;if(this.sessions.oneWay[options._id]){delete options._id;this.openOneWaySession(options,sourceUserId)}}if(options._id&&sourceUserId&&this.users[sourceUserId]){if(sourceUserId){if(!options.settings)options.settings={listener:sourceUserId,source:sourceUserId,propnames:{latency:true},admins:{[sourceUserId]:true},ownerId:sourceUserId};if(!options.settings.listener)options.settings.listener=listenerUserId?listenerUserId:sourceUserId;if(!options.settings.source)options.settings.source=sourceUserId;if(!this.users[sourceUserId].sessions)this.users[sourceUserId].sessions={};this.users[sourceUserId].sessions[options._id]=options}if(!options.data)options.data={};if(options.onopen)options.onopen(options);if(this.sessions.oneWay[options._id]){return this.updateSession(options,sourceUserId)}else if(options.settings?.listener&&options.settings.source)this.sessions.oneWay[options._id]=options}return options};openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;return this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={oneWay:{},shared:{}};if(!options.settings.name)options.name=options.id;if(options.onopen)options.onopen(options);if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};open=(options,userId)=>{if(options.listener)this.openOneWaySession(options,userId);else this.openSharedSession(options,userId)};updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.oneWay[options._id];if(!session)session=this.sessions.shared[options._id];if(session&&userId){if(session.settings&&(session?.settings.source===userId||session.settings.admins?.[userId]||session.settings.moderators?.[userId]||session.settings.ownerId===userId)){return this.recursivelyAssign(session,options)}}else if(options.settings?.source){return this.openOneWaySession(options,userId)}else return this.openSharedSession(options,userId)}return false};joinSession=(sessionId,userId,options,remoteUser=true)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(!sesh)sesh=this.sessions.oneWay[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;sesh.settings.newUser=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options?.source||options?.listener){sesh=this.openOneWaySession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options){sesh=this.openSharedSession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}return false};inviteToSession=(session,userInvited,inviteEndpoint,remoteUser=true)=>{if(remoteUser&&this.users[userInvited]?.send){this.users[userInvited]?.send({route:"receiveSessionInvite",args:[session,userInvited,inviteEndpoint]})}else{this.receiveSessionInvite(session,userInvited,inviteEndpoint)}};receiveSessionInvite=(session,userInvited,endpoint)=>{if(!this.invites[userInvited])this.invites[userInvited]={};let id=typeof session==="string"?session:session._id;this.invites[userInvited][id]={session,endpoint};return id};acceptInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;let invite=this.invites[userInvited]?.[id];let endpoint;if(invite){session=invite.session;endpoint=invite.endpoint;delete this.invites[userInvited]?.[id]}return new Promise((res,rej)=>{if(!id)res(false);if(remoteUser&&endpoint&&this.users[endpoint]?.send){let resolved;let timeout=setTimeout(()=>{if(!resolved){this.unsubscribe("joinSession",subbed);rej(new Error("Session join timed out"))}},1e4);let subbed=this.subscribe("joinSession",result=>{if(typeof result==="object"&&result?._id===id){if(result.setting?.users?.includes(userInvited)){this.unsubscribe("joinSession",subbed);resolved=true;if(timeout)clearTimeout(timeout);res(result)}}});this.users[endpoint]?.send({route:"joinSession",args:[id,userInvited,void 0,true]})}else res(this.joinSession(id,userInvited,typeof session==="object"?session:void 0))})};rejectInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;if(this.invites[userInvited]?.[id]){let endpoint=this.invites[userInvited][id].endpoint;delete this.invites[userInvited][id];if(remoteUser&&endpoint&&this.users[endpoint]?.send){this.users[endpoint].send({route:"rejectInvite",args:[id,userInvited]})}return true}};leaveSession=(session,userId,clear=true,remoteUser=true)=>{let sessionId;if(typeof session==="string"){sessionId=session;session=this.sessions.oneWay[sessionId];if(!session)session=this.sessions.shared[sessionId]}else sessionId=session._id;if(session){if(this.sessions.oneWay[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.oneWay[sessionId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){this.swapHost(session,void 0,true);delete session.data.shared[userId]}}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}return true}return false};deleteSession=(session,userId,remoteUsers=true)=>{if(typeof session==="string"){let id=session;session=this.sessions.oneWay[id];if(!session)session=this.sessions.shared[id]}if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user]?.sessions)delete this.users[user].sessions[session._id];if(this.users[user]?.sessionSubs)delete this.users[user].sessionSubs[session._id];if(remoteUsers){if(session.users){for(const key in session.users){if(this.users[key]?.send)this.users[key].send({route:"unsubscribeFromSession",args:[session._id,key]})}}else if(session.listener){if(this.users[session.listener]?.send)this.users[session.listener].send({route:"unsubscribeFromSession",args:[session._id,session.listener]})}else if(this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId]})}}else{this.unsubsribeFromSession(session,user)}}if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.oneWay[session._id];if(session.onclose)session.onclose(session)}}return true};getFirstMatch(obj1,obj2){for(const i2 in obj1){if(i2 in obj2)return i2}return false}swapHost=(session,newHostId,adoptData=true,remoteUser=true)=>{if(typeof session==="string"){if(this.sessions.oneWay[session])session=this.sessions.oneWay[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){let oldHost=session.settings.host;delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];if(adoptData&&oldHost&&session.settings.inheritHostData!==false){if(session.data?.shared[oldHost]){if(session.data?.shared[oldHost]){session.data.shared[session.settings.host]=Object.assign(session.data.shared[session.settings.host]?session.data.shared[session.settings.host]:{},session.data.shared[oldHost]);if(remoteUser){}}}}return true}return false};subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}let user=this.users[userId];if(!user)return void 0;if(!user.sessionSubs)user.sessionSubs={};if(!user.sessionSubs[session._id])user.sessionSubs[session._id]={};if(onmessage)user.sessionSubs[session._id].onmessage=onmessage;if(onopen)this.sessionSubs[userId][session._id].onopen=onopen;if(onclose)user.sessionSubs[session._id].onclose=onclose;if(typeof onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)this.sessionSubs[userId][session._id].onopen(session,user);this.unsubscribe("joinSession",sub)});user.sessionSubs[session._id].onopenSub=sub}return session};unsubsribeFromSession=(session,userId,clear=true)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}const clearSessionSubs=(Id,s)=>{let u2=this.users[Id];if(!u2)return void 0;if(u2.sessionSubs?.[s._id]){if(u2.sessionSubs[s._id].onopenSub){this.unsubscribe("joinSession",u2.sessionSubs[s._id].onopenSub)}}if(u2.sessionSubs[s._id].onclose)u2.sessionSubs[s._id].onclose(s,u2);delete u2.sessionSubs[s._id]};if(userId){clearSessionSubs(userId,session)}else{for(const key in this.users){clearSessionSubs(key,session)}}if(clear){if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.shared[session._id]}};sessionUpdateCheck=(sessionHasUpdate,transmit=true)=>{let updates={oneWay:{},shared:{}};for(const session in this.sessions.oneWay){const sesh=this.sessions.oneWay[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.oneWay[session];continue}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(prop in this.users[sesh.source]){if(this.sessions.oneWay[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(prop in this.users[sesh.source]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.oneWay[session]?.data&&prop in this.sessions.oneWay[session]?.data)delete this.sessions.oneWay[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.oneWay[session].data,updateObj.data);updates.oneWay[sesh._id]=updateObj;if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.onhasupdate(sesh,updateObj)}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const oneWayData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}else if(sesh.settings.newUser){updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;sesh.settings.newUser=false}if(user!==sesh.settings.host){oneWayData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data?.oneWay&&!(user in sesh.data.oneWay)){if(typeof this.users[user][prop]==="object")oneWayData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else oneWayData[user][prop]=this.users[user][prop]}else if(typeof oneWayData[user][prop]==="object"&&sesh.data){if(prop in this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))oneWayData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.oneWay?.[prop]!==this.users[user][prop])oneWayData[user][prop]=this.users[user][prop]}else if(sesh.data?.oneWay?.[user]&&prop in sesh.data?.oneWay?.[user])delete sesh.data.oneWay[user][prop]}if(Object.keys(oneWayData[user]).length===0)delete oneWayData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user]))sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}}}if(Object.keys(oneWayData).length>0){updateObj.data.oneWay=oneWayData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user]?.[prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user]?.[prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.oneWay){updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){Object.assign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.oneWay){Object.assign(this.sessions.shared[session].data?.oneWay,updateObj.data.oneWay)}if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.settings.onhasupdate(sesh,updateObj)}}if(Object.keys(updates.oneWay).length===0)delete updates.oneWay;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};transmitSessionUpdates=updates=>{let users={};if(updates.oneWay){for(const s in updates.oneWay){let session=this.sessions.oneWay[s];if(session?.settings){let u2=session.settings.listener;if(!users[u2])users[u2]={};users[u2].oneWay[s]=updates.oneWay[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){for(const u2 in session.settings.users){if(!users[u2])users[u2]={};users[u2].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u2 in users){message.args=[u2,users[u2]];if(this.users[u2]?.send)this.users[u2].send(JSON.stringify(message));this.setState({[u2]:Object.create(message)})}return users};receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(user){if(!user.sessions)user.sessions={oneWay:{},shared:{}};if(!user.sessionSubs)user.sessionSubs={}}if(update.oneWay){for(const key in update.oneWay){this.recursivelyAssign(this.sessions.oneWay[key].data,update.oneWay[key].data);if(this.sessions.oneWay[key]?.settings.onmessage)this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key],update.oneWay[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}if(update.shared){for(const key in update.shared){if(update.shared[key].settings.users)this.sessions.shared[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)this.sessions.shared[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.oneWay)this.recursivelyAssign(this.sessions.shared[key].data.oneWay,update.shared[key].data.oneWay);if(update.shared[key].data.shared)this.recursivelyAssign(this.sessions.shared[key].data.shared,update.shared[key].data.shared);if(this.sessions.shared[key]?.settings.onmessage)this.sessions.shared[key].settings.onmessage(this.sessions.shared[key],update.shared[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}return user}};getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};userUpdateCheck=(user,onupdate)=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});if(onupdate){onupdate(user,updateObj)};return updateObj}}return void 0};setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};STREAMLATEST=0;STREAMALLLATEST=1;streamSettings={};streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};setStreamFunc=(name2,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name2].settings[key])this.streamSettings[name2].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name2].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name2].settings[key].callback=callback;if(!this.streamSettings[name2].settings[key].callback)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;return true};addStreamFunc=(name2,callback=data=>{})=>{this.streamFunctions[name2]=callback};setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};removeStream=(streamName,key)=>{if(streamName&&this.streamSettings[streamName]&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}}};var Router=class extends Service{name="router";connections={};sources={};services={};serviceConnections={};users={};userTimeout=1e4;order;constructor(options){super(options);this.load(this);if(options){if(options.order)this.order=options.order;if(options.timeout)this.userTimeout=options.timeout;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}addUser=async(info,connections,config,receiving)=>{let user;if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}if(this.users[info._id]){user=this.users[info._id]}else{user=Object.assign({},info)}if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>this.userTimeout){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}if(!this.users[info._id]){let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let sendAll=(message,...a)=>{let connections2=this.getConnections(user._id,"send");for(const key in connections2)if(connections2[key]?.send)return connections2[key].send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let requestAll=(message,method,...a)=>{let connections2=this.getConnections(user._id,"request");let results=[];for(const key in connections2)if(connections2[key]?.request)results.push(connections2[key].request(message,method,...a));return Promise.all(results)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let postAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"post");for(const key in connections2)if(connections2[key]?.post)connections2[key].post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let runAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"run");let results=[];for(const key in connections2)if(connections2[key]?.run)results.push(connections2[key].run(route,args,method,...a));return Promise.all(results)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let subscribeAll=(route,callback,...a)=>{let connections2=this.getConnections(user._id,"subscribe");let results=[];for(const key in connections2)if(connections2[key]?.post)results.push(connections2[key].subscribe(route,callback,...a));return Promise.all(results)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let unsubscribeAll=(route,subs,...a)=>{let connections2=this.getConnections(user._id,"unsubscribe");let results=[];for(const key in connections2)if(connections2[key]?.post&&subs[key])results.push(connections2[key].unsubscribe(route,subs[key],...a));return Promise.all(results)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;user.sendAll=sendAll;user.requestAll=requestAll;user.postAll=postAll;user.runAll=runAll;user.subscribeAll=subscribeAll;user.unsubscribeAll=unsubscribeAll;user.terminateAll=terminate;this.users[user._id]=user}if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i2)=>{if(connections[k]?._id){connectionIds[`${i2}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}getConnection=(sourceId,hasMethod,connectionId)=>{if(this.connections[sourceId]){return this.connections[sourceId]}else if(this.sources[sourceId]){if(hasMethod?.includes("All"))return this.users[sourceId];if(connectionId){if(hasMethod){if(this.sources[sourceId][connectionId]?.[hasMethod])return this.sources[sourceId][connectionId]}else if(this.sources[sourceId][connectionId])return this.sources[sourceId][connectionId];else return void 0}else if(this.order){for(let i2=0;i2{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}return found}};runConnection=async(userId,method,args,connectionId)=>{let sendTo;if(method.indexOf("All")>-1){sendTo=this.users[userId]}else{sendTo=this.getConnection(userId,method,connectionId)}if(sendTo){let res=sendTo[method](...args);res=await res;return res}};subscribeThroughConnection=(route,remoteRelay,remoteEndpoint,callback,...args)=>{if(typeof remoteRelay==="string"){remoteRelay=this.getConnection(remoteRelay,"run")}if(typeof remoteRelay==="object")return new Promise((res,rej)=>{remoteRelay.run("routeConnections",[route,remoteEndpoint,remoteRelay._id,...args]).then(sub=>{this.__node.state.subscribeEvent(remoteEndpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[remoteEndpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};addConnection=(options,source,autoRemove=true)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.connection=options.connection;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await connectionHasId(info,this.userTimeout)}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await connectionHasId(connection,this.userTimeout)}if(connection._id)return this.addConnection({connection,service},source)}}};terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}}};function connectionHasId(connection,timeout=1e4){return new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>timeout){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connection timed out:",er)})}})(); +(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var require_sjcl=__commonJS({"services/e2ee/sjcl.js"(exports,module){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function instanceObject(obj){let props=getAllProperties(obj);let instance={};for(const key of props){instance[key]=obj[key]}return instance}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var ECSService=class extends Service{constructor(options){super(options);this.entities={};this.systems={};this.entityMap=new Map;this.entityKeyMap=new Map;this.order=[];this.animating=false;this.entityCt=0;this.systemCt=0;this.updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};this.animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};this.stop=()=>{this.animating=false};this.start=filter=>{this.animateEntities(filter)};this.addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};this.addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};this.addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};this.setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};this.removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};this.removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};this.setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};this.setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};this.bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j{this.removeEntity(t)})}filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}};var DOMElement=class extends HTMLElement{constructor(){super();__publicField(this,"template",function(self2=this,props){return`
Custom Fragment Props: ${JSON.stringify(props)}
`});__publicField(this,"props",{});__publicField(this,"useShadow",false);__publicField(this,"styles");__publicField(this,"oncreate");__publicField(this,"onresize");__publicField(this,"ondelete");__publicField(this,"onchanged");__publicField(this,"renderonchanged",false);__publicField(this,"FRAGMENT");__publicField(this,"STYLE");__publicField(this,"attachedShadow",false);__publicField(this,"obsAttributes",["props","options","onchanged","onresize","ondelete","oncreate","template"]);__publicField(this,"attributeChangedCallback",(name,old,val)=>{if(name==="onchanged"){let onchanged=val;if(typeof onchanged==="string")onchanged=parseFunctionFromText2(onchanged);if(typeof onchanged==="function"){this.onchanged=onchanged;this.state.data.props=this.props;this.state.unsubscribeTrigger("props");this.state.subscribeTrigger("props",this.onchanged);let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)})}}else if(name==="onresize"){let onresize=val;if(typeof onresize==="string")onresize=parseFunctionFromText2(onresize);if(typeof onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this.props,this)};this.onresize=onresize;window.addEventListener("resize",this.ONRESIZE)}}else if(name==="ondelete"){let ondelete=val;if(typeof ondelete==="string")ondelete=parseFunctionFromText2(ondelete);if(typeof ondelete==="function"){this.ondelete=()=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");if(ondelete)ondelete(this.props,this)}}}else if(name==="oncreate"){let oncreate=val;if(typeof oncreate==="string")oncreate=parseFunctionFromText2(oncreate);if(typeof oncreate==="function"){this.oncreate=oncreate}}else if(name==="renderonchanged"){let rpc=val;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!=false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}else if(name==="props"){let newProps=val;if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props})}else if(name==="template"){let template=val;this.template=template;this.render(this.props);let created=new CustomEvent("created",{detail:{props:this.props}});this.dispatchEvent(created)}else{let parsed=val;if(name.includes("eval_")){name=name.split("_");name.shift();name=name.join();parsed=parseFunctionFromText2(val)}else if(typeof val==="string"){try{parsed=JSON.parse(val)}catch(err){parsed=val}}this[name]=parsed;if(name!=="props"&&this.props)this.props[name]=parsed}});__publicField(this,"delete",()=>{this.remove();if(typeof this.ondelete==="function")this.ondelete(this.props)});__publicField(this,"render",(props=this.props)=>{if(typeof this.template==="function")this.templateResult=this.template(this,props);else this.templateResult=this.template;if(this.styles)this.templateResult=`${this.templateResult}`;const t=document.createElement("template");if(typeof this.templateResult==="string")t.innerHTML=this.templateResult;else if(this.templateResult instanceof HTMLElement){if(this.templateResult.parentNode){this.templateResult.parentNode.removeChild(this.templateResult)}t.appendChild(this.templateResult)}const fragment=t.content;if(this.FRAGMENT){if(this.useShadow){if(this.STYLE)this.shadowRoot.removeChild(this.STYLE);this.FRAGMENT.forEach(c=>{this.shadowRoot.removeChild(c)})}else this.FRAGMENT.forEach(c=>{this.removeChild(c)})}if(this.useShadow){if(!this.attachedShadow){this.attachShadow({mode:"open"}).innerHTML="";this.attachedShadow=true}if(this.styles){let style=document.createElement("style");style.textContent=this.styles;this.shadowRoot.prepend(style);this.STYLE=style}let len=fragment.childNodes.length;this.shadowRoot.prepend(fragment);this.FRAGMENT=Array.from(this.shadowRoot.childNodes).slice(0,len)}else{let len=fragment.childNodes.length;this.prepend(fragment);this.FRAGMENT=Array.from(this.childNodes).slice(0,len)}let rendered=new CustomEvent("rendered",{detail:{props:this.props,self:this}});this.dispatchEvent(rendered);if(this.oncreate)this.oncreate(this,props)});__publicField(this,"state",{pushToState:{},data:{},triggers:{},setState(updateObj){Object.assign(this.pushToState,updateObj);if(Object.keys(this.triggers).length>0){for(const prop of Object.getOwnPropertyNames(this.triggers)){if(this.pushToState[prop]){this.data[prop]=this.pushToState[prop];delete this.pushToState[prop];this.triggers[prop].forEach(obj=>{obj.onchanged(this.data[prop])})}}}return this.pushToState},subscribeTrigger(key,onchanged=res=>{}){if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({idx:l,onchanged});return this.triggers[key].length-1}else return void 0},unsubscribeTrigger(key,sub){let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.idx===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);return true}}},subscribeTriggerOnce(key=void 0,onchanged=value=>{}){let sub;let changed=value=>{onchanged(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)}})}get observedAttributes(){return this.obsAttributes}get obsAttributes(){return this.obsAttributes}set obsAttributes(att){if(typeof att==="string"){this.obsAttributes.push(att)}else if(Array.isArray(att))this.obsAttributes=att}static get tag(){return this.name.toLowerCase()+"-"}static addElement(tag=this.tag,cls=this,extend=void 0){addCustomElement(cls,tag,extend)}connectedCallback(){if(!this.props)this.props={};let newProps=this.getAttribute("props");if(typeof newProps==="string")newProps=JSON.parse(newProps);Object.assign(this.props,newProps);this.state.setState({props:this.props});Array.from(this.attributes).forEach(att=>{let name=att.name;let parsed=att.value;if(name.includes("eval_")||name.includes("()")){if(name.includes("eval_"))name=name.split("_");else if(name.includes("()"))name=name.substring(0,name.indexOf("("));name.shift();name=name.join();parsed=parseFunctionFromText2(att.value)}else if(typeof att.value==="string"){try{parsed=JSON.parse(att.value)}catch(err){parsed=att.value}}if(!this[name]){Object.defineProperties(this,att,{value:parsed,writable:true,get(){return this[name]},set(val){this.setAttribute(name,val)}})}this[name]=parsed;if(name!=="props")this.props[name]=parsed;this.obsAttributes.push(name)});let resizeevent=new CustomEvent("resized",{detail:{props:this.props,self:this}});let changed=new CustomEvent("changed",{detail:{props:this.props,self:this}});let deleted=new CustomEvent("deleted",{detail:{props:this.props,self:this}});let created=new CustomEvent("created",{detail:{props:this.props,self:this}});this.render(this.props);this.dispatchEvent(created);this.state.subscribeTrigger("props",()=>{this.dispatchEvent(changed)});if(typeof this.onresize==="function"){if(this.ONRESIZE){try{window.removeEventListener("resize",this.ONRESIZE)}catch(err){}}this.ONRESIZE=ev=>{this.onresize(this,this.props);this.dispatchEvent(resizeevent)};window.addEventListener("resize",this.ONRESIZE)}if(typeof this.ondelete==="function"){let ondelete=this.ondelete;this.ondelete=(props=this.props)=>{if(this.ONRESIZE)window.removeEventListener("resize",this.ONRESIZE);this.state.unsubscribeTrigger("props");this.dispatchEvent(deleted);ondelete(this,props)}}if(typeof this.onchanged==="function"){this.state.data.props=this.props;this.state.subscribeTrigger("props",this.onchanged)}if(this.renderonchanged){let rpc=this.renderonchanged;if(typeof this.renderonchanged==="number")this.unsubscribeTrigger(this.renderonchanged);if(typeof rpc==="string")rpc=parseFunctionFromText2(rpc);if(typeof rpc==="function"){this.renderonchanged=this.state.subscribeTrigger("props",p=>{this.render(p);rpc(this,p)})}else if(rpc!==false)this.renderonchanged=this.state.subscribeTrigger("props",this.render)}}get props(){return this.props}set props(newProps={}){this.setAttribute("props",newProps)}get template(){return this.template}set template(template){this.setAttribute("template",template)}get render(){return this.render}get delete(){return this.delete}get state(){return this.state}get onchanged(){return this.onchanged}set onchanged(onchanged){this.setAttribute("onchanged",onchanged)}get styles(){return this.styles}set styles(templateStr){this.styles=templateStr;if(this.querySelector("style")){this.querySelector("style").innerHTML=templateStr}else{this.render()}}get renderonchanged(){return this.renderonchanged}set renderonchanged(onchanged){this.setAttribute("renderonchanged",onchanged)}get onresize(){return this.props}set onresize(onresize){this.setAttribute("onresize",onresize)}get ondelete(){return this.props}set ondelete(ondelete){this.setAttribute("ondelete",ondelete)}get oncreate(){return this.oncreate}set oncreate(oncreate){this.setAttribute("oncreated",oncreate)}};function addCustomElement(cls,tag,extend=null){try{if(extend){if(tag)window.customElements.define(tag,cls,{extends:extend});else window.customElements.define(cls.name.toLowerCase()+"-",cls,{extends:extend})}else{if(tag)window.customElements.define(tag,cls);else window.customElements.define(cls.name.toLowerCase()+"-",cls)}}catch(err){}}function parseFunctionFromText2(method){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf(")");return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;try{if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch(err){newFunc=(0,eval)(method)}}}}catch(err){}return newFunc}var htmlloader=(node,parent2,graph,tree,properties,key)=>{if(node.__onresize){let onresize=node.__onresize;node.__onresize=ev=>{onresize.call(node,ev,node.__props)}}if(node.__onremove){let ondelete=node.__onremove;node.__onremove=element=>{ondelete.call(node,element)}}if(node.__onrender){let onrender=node.__onrender;node.__onrender=element=>{onrender.call(node,element)}}if(node.tagName&&!node.__props&&!node.__template){node.__props=document.createElement(node.tagName);node.__proxyObject(node.__props);let keys=Object.getOwnPropertyNames(properties);for(const k of keys){if(k==="style"&&typeof properties[k]==="object"){Object.assign(node.__props.style,properties[k])}else node.__props[k]=properties[k]}}else if(node.__element&&!node.__template){if(typeof node.__element==="string")node.__element=document.createElement(node.__element);if(!(node.__element instanceof HTMLElement))return;node.__props=node.__element;node.__proxyObject(node.__props);let keys=Object.getOwnPropertyNames(properties);for(const k of keys){if(k==="style"&&typeof properties[k]==="object"){Object.assign(node.__props.style,properties[k])}else node.__props[k]=properties[k]}}else if(typeof node.__css==="string"){node.__template=``;delete node.__css}if(node.__template){if(typeof node.__renderonchanged==="function"){let renderonchanged=node.__renderonchanged;node.__renderonchanged=element=>{renderonchanged.call(element.node,element)}}class CustomElement extends DOMElement{constructor(){super(...arguments);this.props=node.props;this.styles=node.__css;this.useShadow=node.useShadow;this.template=node.__template;this.oncreate=node.__onrender;this.onresize=node.__onresize;this.ondelete=node.__onremove;this.renderonchanged=node.__renderonchanged}}if(node.__element)node.tagName=node.__element;if(!node.tagName)node.tagName=`element${Math.floor(Math.random()*1e15)}-`;CustomElement.addElement(node.tagName);node.__props=document.createElement(node.tagName);node.__proxyObject(node.__props);node.__props.node=node;let keys=Object.getOwnPropertyNames(properties);for(const k of keys){if(k==="style"&&typeof properties[k]==="object"){Object.assign(node.__props.style,properties[k])}else node.__props[k]=properties[k]}}else if(node.__props instanceof HTMLElement){if(node.__onresize)window.addEventListener("resize",node.__onresize)}if(node.__attributes&&node.__props instanceof HTMLElement){for(const k in node.__attributes){if(k==="style"&&typeof node.__attribute[k]==="object"){Object.assign(node.__props.style,node.__attribute[k])}node.__props[k]=node.__attributes[k]}}if(node.__props instanceof HTMLElement){node.__props.id=key;node.__addOnconnected(n=>{if(n.__props.parentNode)n.__props.remove();if(n.parentNode){if(typeof n.parentNode==="string"&&document.getElementById(n.parentNode))document.getElementById(n.parentNode).appendChild(n.__props);else if(n.parentNode instanceof HTMLElement)n.parentNode.appendChild(n.__props)}else if(parent2.__props instanceof HTMLElement){parent2.__props.appendChild(node.__props)}else if(typeof graph.parentNode==="string"&&document.getElementById(n.parentNode)){document.getElementById(n.parentNode).appendChild(graph.__props)}else if(graph.parentNode instanceof HTMLElement){graph.parentNode.appendChild(node.__props)}else if(!(node.__props instanceof HTMLBodyElement||node.__props instanceof HTMLHeadElement))document.body.appendChild(node.__props);if(node.__onrender&&!node.__template)setTimeout(()=>{node.__onrender(node.__props)},.01)});node.__addOndisconnected(n=>{n.__props.remove();if(typeof n.__onremove==="function"){n.__onremove(n.__props)}if(n.__onresize){window.removeEventListener("resize",n.__onresize)}})}};var import_sjcl=__toESM(require_sjcl());var E2EEService=class extends Service{constructor(options,keys,secureKeys,secret){super(options);this.name="e2ee";this.securedKeys=false;this.addKey=(key,_id)=>{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=import_sjcl.default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};this.encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=import_sjcl.default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};this.decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=import_sjcl.default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=import_sjcl.default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};this.transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};this.receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message};if(keys){if(secureKeys&&secret){this.securedKeys=true;this.encryptedkeys=import_sjcl.default.encrypt(secret,JSON.stringify(keys)).cipher;this.secret=secret}else Object.assign(this.keys,keys)}this.setTree(this)}static generateSecret(){return import_sjcl.default.codec.base64.fromBits(import_sjcl.default.random.randomWords(8,10))}encrypt(message,key){message=import_sjcl.default.encrypt(key,message).cipher;return message}decrypt(message,key){message=import_sjcl.default.decrypt(key,message);return message}};var _HTTPfrontend=class extends Service{constructor(options,path,fetched){super(options);this.name="http";this.fetchProxied=false;this.listening={};this.GET=(url="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{let obj=message;if(typeof obj==="object"){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url);return this.POST(message,url)};this.transponder=(url,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url,data:message,responseType:type,onload:ev=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};this.listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};this.stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}};this.setTree(this);this.listen(path,fetched)}};var HTTPfrontend=_HTTPfrontend;HTTPfrontend.request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};var SSEfrontend=class extends Service{constructor(options){super(options);this.name="sse";this.eventsources={};this.connections={eventsources:this.eventsources};this.openSSE=options=>{let source=new EventSource(options.url);let sse={source,type:"eventsource",...options};if(!("keepState"in options))options.keepState=true;if(!options.events)options.events={};if(options.events.close){let close=options.events.close;options.events.close=ev=>{if(sse.onclose)sse.onclose(ev,sse);close(ev,sse)}}if(options.events.open){let open=options.events.open;options.events.open=ev=>{if(sse.onopen)sse.onopen(ev,sse);open(ev,sse)}}if(options.events.error){let error=options.events.error;options.events.error=ev=>{if(sse.onerror)sse.onerror(ev,sse);error(ev,sse)}}if(options.events.message){let message=options.events.message;options.events.message=ev=>{if(sse.onmessage)sse.onmessage(ev,sse);message(ev,sse)}}if(!options.events.message){options.events.message=(ev,sse2)=>{let data=ev.data;if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"&&sse2){sse2._id=data.args;options.events.message=(e,sse3)=>{const result2=this.receive(e.data,sse3);if(options.keepState)this.setState({[options.url]:e.data})}}}}}const result=this.receive(ev.data,sse2);if(options.keepState)this.setState({[options.url]:data})}}if(!options.events.error)options.events.error=(ev,sse2)=>{this.terminate(sse2);delete this.eventsources[options.url]};if(options.events){if(!options.evoptions)options.evoptions=false;for(const key in options.events){if(typeof options.events[key]!=="function"){options.events[key]=ev=>{const result=this.receive(ev.data,sse);if(options.keepState)this.setState({[options.url]:result})}}else{let l=options.events[key];options.events[key]=ev=>{l(ev,sse)}}source.addEventListener(key,options.events[key],options.evoptions)}}let send=message=>{return this.transmit(message,options.url)};let request=(message,method,sessionId)=>{return this.request(message,options.url,sessionId,method)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options.url)};let run=(route,args,method,sessionId)=>{return this.request({route,args},options.url,method,sessionId)};let subscribe=(route,callback)=>{return this.subscribeToSSE(route,options.url,callback,sse._id)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options.url)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;this.eventsources[options.url]=sse;return sse};this.open=this.openSSE;this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{return this.POST(message,url,"json")};this.request=(message,url,method,sessionId)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,url,callbackId,sessionId]};if(method)req.method=method;let evs=this.eventsources[url].source;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){evs.removeEventListener("message",onmessage);res(data.args)}}};evs.addEventListener("message",onmessage);this.POST(message,url,"json")})};this.runRequest=(message,url,callbackId,sessionId)=>{let res=this.receive(message);if(url){if(res instanceof Promise){res.then(r=>{let message2={args:r,callbackId,sessionId};this.POST(message2,url,"json")})}else{let message2={args:res,callbackId,sessionId};this.POST(message2,url,"json")}}return res};this.subscribeSSE=(route,url,key,subInput)=>{return this.subscribe(route,res=>{this.POST(res,url,"json")},key,subInput)};this.subscribeToSSE=(route,url,callback,sessionId,key,subInput)=>{if(url){this.__node.state.subscribeTrigger(url,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[url]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.eventsources[url].run("subscribeSSE",[route,url,sessionId,key,subInput])}};this.terminate=sse=>{if(typeof sse==="string"){let str=sse;sse=this.eventsources[sse];delete this.eventsources[str]}if(!sse)return;if(typeof sse==="object"){if(sse.source){sse=sse.source}if(sse instanceof EventSource){if(sse.readyState!==2)sse.close()}}};this.setTree(this)}};var WSSfrontend=class extends Service{constructor(options){super(options);this.name="wss";this.sockets={};this.connections={sockets:this.sockets};this.openWS=(options={host:"localhost",port:7e3,path:void 0,protocol:"ws",onclose:(ev,socket,wsinfo)=>{if(ev.target.url)delete this.sockets[ev.target.url]}})=>{let protocol=options.protocol;if(!protocol)protocol="ws";let address=`${protocol}://${options.host}`;if(!("keepState"in options))options.keepState=true;if(options.port)address+=":"+options.port;if(options.path&&!options.path?.startsWith("/"))address+="/";if(options.path)address+=options.path;if(this.sockets[address]?.socket){if(this.sockets[address].socket.readyState===this.sockets[address].socket.OPEN)this.sockets[address].socket.close()}const socket=new WebSocket(address);if(!options.onmessage){if(!options._id){options.onmessage=(data,ws,wsinfo)=>{if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;options.onmessage=(data2,ws2,wsinfo2)=>{this.receive(data2);if(options.keepState){this.setState({[address]:data2})}}}}}}let res=this.receive(data);if(options.keepState)this.setState({[address]:data})}}else{options.onmessage=(data,ws,wsinfo)=>{this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}}}}if(options.onmessage){socket.addEventListener("message",ev=>{this.sockets[address].onmessage(ev.data,socket,this.sockets[address])})}socket.addEventListener("open",ev=>{if(this.sockets[address].onopen)this.sockets[address].onopen(ev,socket,this.sockets[address])});socket.addEventListener("close",ev=>{if(this.sockets[address].onclose)this.sockets[address].onclose(ev,socket,this.sockets[address])});socket.addEventListener("error",ev=>{if(this.sockets[address].onerror)this.sockets[address].onerror(ev,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="string"&&ev.data.indexOf("{")>-1)ev.data=JSON.parse(ev.data);if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(ev.data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="string"&&ev.data.indexOf("{")>-1)ev.data=JSON.parse(ev.data);if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(ev.data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let subscribe=(route,callback)=>{return this.subscribeToSocket(route,options._id,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.sockets[address]={type:"socket",socket,address,send,post,run,request,subscribe,unsubscribe,terminate,graph:this,...options};return this.sockets[address]};this.open=this.openWS;this.transmit=(data,ws)=>{if(typeof data==="object")data=JSON.stringify(data);if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}if(ws instanceof WebSocket&&ws?.readyState===1)ws.send(data);return true};this.terminate=ws=>{if(!ws){let key=Object.keys(this.sockets)[0];if(key)ws=this.sockets[key].socket}else if(typeof ws==="string"){for(const k in this.sockets){if(k.includes(ws)){ws=this.sockets[k].socket;break}}}if(ws instanceof WebSocket){if(ws.readyState===ws.OPEN)ws.close()}return true};this.request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};this.runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(typeof ws==="string"){for(const s in this.sockets){if(s===ws){ws=this.sockets[s].socket;break}}}if(ws){if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof WebSocket)ws.send(JSON.stringify(res))}}return res};this.subscribeSocket=(route,socket,key,subInput)=>{if(typeof socket==="string"&&this.sockets[socket]){socket=this.sockets[socket].socket}if(typeof socket==="object")return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},key,subInput)};this.subscribeToSocket=(route,socketId,callback,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeTrigger(socketId,res=>{let msg=JSON.parse(res);if(msg?.callbackId===route){if(!callback)this.setState({[socketId]:msg.args});else if(typeof callback==="string"){this.run(callback,msg.args)}else callback(msg.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,key,subInput]})}};this.setTree(this)}};var WebRTCfrontend=class extends Service{constructor(options,iceServers){super(options);this.name="webrtc";this.rtc={};this.iceServers=[{urls:["stun:stun.l.google.com:19302"]},{urls:["stun:stun1.l.google.com:19302"]},{urls:["stun:stun2.l.google.com:19302"]},{urls:["stun:stun3.l.google.com:19302"]},{urls:["stun:stun4.l.google.com:19302"]}];this.connections={rtc:this.rtc};this.createStream=options=>{let stream=new MediaStream;for(const key in options){let track=options[key].track;if(!(track instanceof MediaStreamTrack)&&typeof track==="object"){track=new MediaStreamTrack;track.applyConstraints(options[key].track);stream.addTrack(track)}if(track instanceof MediaStreamTrack){stream.addTrack(track);track.onmute=options[key].onmute;track.onunmute=options[key].onunmute;track.onended=options[key].onended}}return stream};this.openRTC=async options=>{if(!options)options={};if(!options._id)options._id=`rtc${Math.floor(Math.random()*1e15)}`;if(!options.config)options.config={iceServers:this.iceServers};let rtc=new RTCPeerConnection(options.config);if(!this.rtc[options._id]){if(!options.channels)options.channels={"data":true};let firstChannel;for(const key in options.channels){firstChannel=key;break}let send=message=>{return this.transmit(message,options._id,options.channels[firstChannel])};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,options._id,options.channels[firstChannel])};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let request=(message,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let sub;let ondata=data=>{if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){this.unsubscribe(options._id,sub);res(data.args)}}};sub=this.subscribe(options._id,ondata);this.transmit(req,options._id,options.channels[firstChannel])})};let subscribe=(route,callback)=>{return this.subscribeToRTC(route,options._id,firstChannel,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{return this.terminate(options._id)};this.rtc[options._id]={rtc,_id:options._id,request,run,post,send,subscribe,unsubscribe,terminate,graph:this,...options};if(!options.ondatachannel)options.ondatachannel=ev=>{this.rtc[options._id].channels[ev.channel.label]=ev.channel;if(!options.ondata){ev.channel.addEventListener("message",mev=>{this.receive(mev.data,ev.channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})})}else ev.channel.addEventListener("message",mev=>{options.ondata(mev.data,ev.channel,this.rtc[options._id])})};if(options.channels){for(const channel in options.channels){if(options.channels[channel]instanceof RTCDataChannel){}else if(typeof options.channels[channel]==="object"){options.channels[channel]=this.addDataChannel(rtc,channel,options.channels[channel])}else{options.channels[channel]=this.addDataChannel(rtc,channel)}options.channels[channel].addEventListener("message",mev=>{this.receive(mev.data,channel,this.rtc[options._id]);this.setState({[options._id]:mev.data})})}}rtc.ontrack=options.ontrack;rtc.onicecandidate=options.onicecandidate;rtc.onicecandidateerror=options.onicecandidateerror;rtc.ondatachannel=options.ondatachannel;rtc.onnegotiationneeded=options.onnegotiationneeded;rtc.oniceconnectionstatechange=options.oniceconnectionstatechange;rtc.onconnectionstatechange=options.onconnectionstatechange;rtc.addEventListener("connectionstatechange",ev=>{if(rtc.connectionState==="closed"||rtc.connectionState==="failed"){if(this.rtc[options._id].onclose){this.rtc[options._id].onclose(this.rtc[options._id])}}})}else{Object.assign(this.rtc[options._id],options)}if(options.hostdescription&&!options.peerdescription){if(!options.onicecandidate)options.onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].peercandidates)this.rtc[options._id].peercandidates={};this.rtc[options._id].peercandidates[`peercandidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};return await new Promise((res,rej)=>{if(typeof options.hostdescription==="string"){options.hostdescription=JSON.parse(decodeURIComponent(options.hostdescription))}const description=new RTCSessionDescription(options.hostdescription);options.hostdescription=description;rtc.setRemoteDescription(description).then(()=>{if(options.hostcandidates){for(const prop in options.hostcandidates){const candidate=new RTCIceCandidate(options.hostcandidates[prop]);rtc.addIceCandidate(candidate).catch(console.error)}}rtc.createAnswer(options.answer).then(answer=>rtc.setLocalDescription(answer)).then(()=>{this.rtc[options._id].peerdescription=encodeURIComponent(JSON.stringify(rtc.localDescription));res(this.rtc[options._id])})}).catch(rej)})}if(options.peerdescription){this.answerPeer(rtc,options)}if(!options.onicecandidate&&!this.rtc[options._id]?.onicecandidate)options.onicecandidate=ev=>{if(ev.candidate){let icecandidate=ev.candidate;if(!this.rtc[options._id].hostcandidates)this.rtc[options._id].hostcandidates={};this.rtc[options._id].hostcandidates[`hostcandidate${Math.floor(Math.random()*1e15)}`]=icecandidate}};return await new Promise((res,rej)=>{rtc.createOffer(options.offer).then(offer=>rtc.setLocalDescription(offer)).then(()=>{this.rtc[options._id].hostdescription=encodeURIComponent(JSON.stringify(rtc.localDescription));res(this.rtc[options._id])})})};this.addUserMedia=(rtc,options={audio:false,video:{optional:[{minWidth:320},{minWidth:640},{minWidth:1024},{minWidth:1280},{minWidth:1920},{minWidth:2560}]}})=>{let senders=[];navigator.mediaDevices.getUserMedia(options).then(stream=>{let tracks=stream.getTracks();tracks.forEach(track=>{senders.push(rtc.addTrack(track,stream))})});return senders};this.addTrack=(rtc,track,stream)=>{rtc.addTrack(track,stream);return true};this.removeTrack=(rtc,sender)=>{rtc.removeTrack(sender);return true};this.addDataChannel=(rtc,name,options)=>{return rtc.createDataChannel(name,options)};this.transmit=(data,id,channel)=>{if(typeof data==="object"||typeof data==="number")data=JSON.stringify(data);if(!channel&&id){let keys=Object.keys(this.rtc[id].channels);if(keys[0])channel=this.rtc[id].channels[keys[0]]}if(typeof channel==="string"){if(id){channel=this.rtc[id].channels[channel]}else{for(const id2 in this.rtc){if(this.rtc[id2].channels[channel]instanceof RTCDataChannel)this.rtc[id2].channels[channel].send(data)}}}if(channel instanceof RTCDataChannel)channel.send(data);return true};this.terminate=rtc=>{let tx;if(typeof rtc==="string"){let room=this.rtc[rtc];delete this.rtc[rtc];if(room){tx=room.rtc}}else if(typeof rtc==="object"){tx=rtc.rtc}if(rtc instanceof RTCPeerConnection){rtc.close()}else if(tx){if(tx)tx.close()}return true};this.request=(message,channel,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(ev.data);if(typeof data==="object"){if(data.callbackId===callbackId){channel.removeEventListener("message",onmessage);res(data.args)}}};channel.addEventListener("message",onmessage);channel.send(JSON.stringify(req))})};this.runRequest=(message,channel,callbackId)=>{let res=this.receive(message);if(channel){if(typeof channel==="string"){for(const key in this.rtc){if(key===channel){channel=this.rtc[key].channels.data;break}}}if(res instanceof Promise)res.then(v=>{res={args:v,callbackId};if(channel instanceof RTCDataChannel)channel.send(JSON.stringify(res));return res});else{res={args:res,callbackId};if(channel instanceof RTCDataChannel)channel.send(JSON.stringify(res))}}return res};this.subscribeRTC=(route,rtcId,channel)=>{if(typeof channel==="string"&&this.rtc[rtcId]){channel=this.rtc[rtcId].channels[channel]}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{channel.send(JSON.stringify({args:r,callbackId:route}))})}else{channel.send(JSON.stringify({args:res,callbackId:route}))}})};this.subscribeToRTC=(route,rtcId,channelId,callback)=>{if(typeof channelId==="string"&&this.rtc[rtcId]){let c=this.rtc[rtcId];let channel=c.channels[channelId];if(channel){this.__node.state.subscribeTrigger(rtcId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[rtcId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return c.request({route:"subscribeRTC",args:[route,channelId]})}}};this.setTree(this);if(iceServers)this.iceServers=iceServers}addIceCandidate(rtc,candidate){return rtc.addIceCandidate(candidate)}answerPeer(rtc,options){return new Promise((res,rej)=>{if(typeof options.peerdescription==="string"){options.peerdescription=JSON.parse(decodeURIComponent(options.peerdescription))}const description=new RTCSessionDescription(options.peerdescription);options.peerdescription=description;if(this.rtc[options._id])this.rtc[options._id].peerdescription=description;rtc.setRemoteDescription(description).then(()=>{if(options.peercandidates){for(const prop in options.peercandidates){const candidate=new RTCIceCandidate(options.peercandidates[prop]);if(this.rtc[options._id])this.rtc[options._id].peercandidates[prop]=options.peercandidates[prop];rtc.addIceCandidate(candidate).catch(console.error)}}res(this.rtc[options._id]?this.rtc[options._id]:rtc)}).catch(rej)})}};var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent2,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent2?.callback&&parent2?.worker))node.parentRoute=parent2?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev=>{let result=this.receive(ev.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev=>{this.receive(ev.data);this.setState({[options._id]:ev.data})};if(!options.onerror){options.onerror=ev=>{console.error(ev.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev=>{if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setTree(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText3(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText3(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText3(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText3(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText3(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText3(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText3(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText3(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText3(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText3(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w=s.worker;let wpId;wpId=service.establishMessageChannel(w.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w.run("setValue",["routeProxy",s.route]);w.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w2=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w.worker,w2.worker);s.pipeTo.worker=w2}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w.run("setValue",["routeProxy",s.route]);service.transferFunction(w,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;Object.assign(this.__node.graph.ALGORITHMS[_id],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;let res=this.__node.graph.ALGORITHMS[_id].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id]:res});return res}}}};var SessionsService=class extends Service{constructor(options,users){super(options);this.name="sessions";this.users={};this.sessions={private:{},shared:{}};this.getSessionInfo=(sessionId,userId)=>{if(!sessionId){return this.sessions.shared}else{if(this.sessions.private[sessionId]){let s=this.sessions.private[sessionId];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{private:{[sessionId]:s}}}}else if(this.sessions.shared[sessionId]){return{shared:{[sessionId]:this.sessions.shared[sessionId]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};this.openPrivateSession=(options={},userId)=>{if(!options._id){options._id=`private${Math.floor(Math.random()*1e15)}`;if(this.sessions.private[options._id]){delete options._id;this.openPrivateSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(userId){if(!options.settings)options.settings={listener:userId,source:userId,propnames:{latency:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.listener)options.settings.listener=userId;if(!options.settings.source)options.settings.source=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}if(!options.data)options.data={};if(this.sessions.private[options._id]){return this.updateSession(options,userId)}else if(options.settings?.listener&&options.settings.source)this.sessions.private[options._id]=options}return options};this.openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={private:{},shared:{}};if(!options.settings.name)options.name=options.id;if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};this.updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.private[options._id];if(!session)session=this.sessions.shared[options._id];if(this.sessions.private[options._id]&&userId){let sesh=this.sessions.shared[options._id];if(sesh.settings&&(sesh?.settings.source===userId||sesh.settings.admins?.[userId]||sesh.settings.moderators?.[userId]||sesh.settings.ownerId===userId)){return Object.assign(this.sessions.shared[options._id],options)}}else if(options.settings?.source){return this.openPrivateSession(options,userId)}else return this.openSharedSession(options,userId)}return false};this.joinSession=(sessionId,userId,options)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};return sesh}else if(options?.source||options?.listener)return this.openPrivateSession(options,userId);else if(options)return this.openSharedSession(options,userId);return false};this.leaveSession=(sessionId,userId,clear=true)=>{let session=this.sessions.private[sessionId];if(!session)session=this.sessions.shared[sessionId];if(session){if(this.sessions.private[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.private[sessionId];delete this.users[userId].sessions[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId].sessions[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){delete session.settings.host;delete session.data.shared;session.data.shared={};this.swapHost(session)}}}return true}return false};this.swapHost=(session,newHostId)=>{if(typeof session==="string"){if(this.sessions.private[session])session=this.sessions.private[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];return true}return false};this.deleteSession=(sessionId,userId)=>{let session=this.sessions.private[sessionId];if(!session)session=this.sessions.shared[sessionId];if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user].sessions)delete this.users[user].sessions[sessionId]}if(this.sessions.private[sessionId])delete this.sessions.private[sessionId];else if(this.sessions.shared[sessionId])delete this.sessions.private[sessionId]}}return true};this.subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.private[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}if(typeof session.onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)session.onopen(session,userId);this.unsubscribe("joinSession",sub)})}if(typeof session==="object"){if(onmessage)session.onmessage=onmessage;if(onopen)session.onclose=onopen;if(onclose)session.onclose=onclose}return session};this.sessionUpdateCheck=(transmit=true)=>{let updates={private:{},shared:{}};for(const session in this.sessions.private){const sesh=this.sessions.private[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.private[session];break}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(this.users[sesh.source][prop]){if(this.sessions.private[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.users[sesh.source][prop]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.private[session]?.data?.[prop])delete this.sessions.private[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.private[session].data,updateObj.data);updates.private[sesh._id]=updateObj}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const privateData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.private?.[user])delete sesh.data.shared[user];if(sesh.settings.host===user)this.swapHost(sesh);updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}if(user!==sesh.settings.host){privateData[user]={};for(const prop in sesh.settings.propnames){if(this.users[user][prop]){if(sesh.data?.private&&!(user in sesh.data.private)){if(typeof this.users[user][prop]==="object")privateData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else privateData[user][prop]=this.users[user][prop]}else if(typeof privateData[user][prop]==="object"&&sesh.data){if(this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))privateData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.private?.[prop]!==this.users[user][prop])privateData[user][prop]=this.users[user][prop]}else if(sesh.data?.private?.[user]?.[prop])delete sesh.data.private[user][prop]}if(Object.keys(privateData[user]).length===0)delete privateData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(this.users[user][prop]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])))sharedData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]?.[prop])delete sesh.data.shared[user][prop]}}}if(Object.keys(privateData).length>0){updateObj.data.private=privateData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.private?.[user])delete sesh.data.shared[user];if(sesh.settings.host===user)this.swapHost(sesh);updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(this.users[user][prop]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user][prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]?.[prop])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.private)updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){this.recursivelyAssign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.private){this.recursivelyAssign(this.sessions.shared[session].data?.private,updateObj.data.private)}}if(Object.keys(updates.private).length===0)delete updates.private;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};this.transmitSessionUpdates=updates=>{let users={};if(updates.private){for(const s in updates.private){let session=this.sessions.private[s];if(session?.settings){let u=session.settings.listener;if(!users[u])users[u]={private:{}};else if(!users[u].private)users[u].private={};users[u].private[s]=updates.private[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){let copy;if(session.settings.host){copy=Object.assign({},updates.shared[s]);delete copy.data.private}for(const u in session.settings.users){if(!users[u])users[u]={shared:{}};else if(!users[u].shared)users[u].shared={};if(session.settings.host){if(u!==session.settings.host){users[u].shared[s]=copy}else users[u].shared[s]=updates.shared[s]}else users[u].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u in users){message.args=[u,users[u]];if(this.users[u].send)this.users[u].send(JSON.stringify(message));this.setState({[u]:Object.create(message)})}return users};this.receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(!user)return void 0;if(!user.sessions)user.sessions={};if(update.private){for(const key in update.private){if(!user.sessions[key])continue;this.recursivelyAssign(user.sessions[key].data,update.private[key].data);if(user.sessions[key].onmessage)user.sessions[key].onmessage(user.sessions[key],user._id)}}if(update.shared){for(const key in update.shared){if(!user.sessions[key])continue;if(update.shared[key].settings.users)user.sessions[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)user.sessions[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.private)this.recursivelyAssign(user.sessions[key].data.private,update.shared[key].data.private);if(update.shared[key].data.shared)this.recursivelyAssign(user.sessions[key].data.shared,update.shared[key].data.shared);if(user.sessions[key].onmessage)user.sessions[key].onmessage(user.sessions[key],user._id)}}return user}};this.getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};this.userUpdateCheck=user=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});return updateObj}}return void 0};this.setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};this.STREAMLATEST=0;this.STREAMALLLATEST=1;this.streamSettings={};this.streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};this.setStreamFunc=(name,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name].settings[key])this.streamSettings[name].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name].settings[key].callback=callback;if(!this.streamSettings[name].settings[key].callback)this.streamSettings[name].settings[key].callback=this.streamFunctions.allLatestValues;return true};this.addStreamFunc=(name,callback=data=>{})=>{this.streamFunctions[name]=callback};this.setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};this.removeStream=(streamName,key)=>{if(streamName&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};this.updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};this.getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};this.getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};this.streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}};this.userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};this.sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};this.setLoaders(loaders);this.setTree(this);if(users)this.users=users}getFirstMatch(obj1,obj2){for(const i in obj1){for(const j in obj2){if(i===j)return i}}return false}};var Router=class extends Service{constructor(options){super(options);this.name="router";this.connections={};this.sources={};this.services={};this.serviceConnections={};this.users={};this.addUser=async(info,connections,config,receiving)=>{if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}let user=Object.assign({},info);if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>3e3){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;this.users[user._id]=user;if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i)=>{if(connections[k]?._id){connectionIds[`${i}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};this.getConnection=(sourceId,hasMethod)=>{if(this.sources[sourceId]){if(this.order){for(let i=0;i{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}if(pass){if(this.getConnection(this.sources[sourceId][key],hasMethod))found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}}};this.addConnection=(options,source)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};this.removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};this.routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};this.addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};this.openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!info._id){if(performance.now()-start>3e3){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>3e3){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}if(connection._id)return this.addConnection({connection,service},source)}}};this.terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};this.subscribeThroughConnection=(route,relay,endpoint,callback,...args)=>{if(typeof relay==="string"){relay=this.getConnection(relay,"run")}if(typeof relay==="object")return new Promise((res,rej)=>{relay.run("routeConnections",[route,endpoint,relay._id,...args]).then(sub=>{this.__node.state.subscribeTrigger(endpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[endpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};this.routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,transmitter._id,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};this.setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}};this.setTree(this);if(options){if(options.order)this.order=options.order;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}};})(); diff --git a/dist/index.node.d.ts b/dist/index.node.d.ts index c5c0af0d..a14ea73f 100644 --- a/dist/index.node.d.ts +++ b/dist/index.node.d.ts @@ -1,14 +1,12 @@ -export * from './src/core/Graph'; -export * from './src/core/EventHandler'; -export * from './src/loaders'; -export { methodstrings } from './src/loaders/methodstrings'; -export * from './src/services/Service'; -export * from './src/services/remote/remote.routes'; -export * from './src/services/ecs/ECS.service'; -export * from './src/services/e2ee/E2EE.service'; -export * from './src/services/http/HTTP.node'; -export * from './src/services/sse/SSE.node'; -export * from './src/services/wss/WSS.node'; -export * from './src/services/cmd/CMD.node'; -export * from './src/services/sessions/sessions.service'; -export * from './src/services/router/Router'; +export * from './Graph'; +export * from './loaders'; +export * from './services/Service'; +export * from './services/unsafe/Unsafe.service'; +export * from './services/ecs/ECS.service'; +export * from './services/e2ee/E2EE.service'; +export * from './services/http/HTTP.node'; +export * from './services/sse/SSE.node'; +export * from './services/wss/WSS.node'; +export * from './services/cmd/CMD.node'; +export * from './services/sessions/sessions.service'; +export * from './services/router/Router'; diff --git a/dist/index.node.js b/dist/index.node.js index 003fd2c1..c4623970 100644 --- a/dist/index.node.js +++ b/dist/index.node.js @@ -1,107 +1,8 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name2 in all)__defProp(target,name2,{get:all[name2],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var require_build=__commonJS({"node_modules/better-sse/build/index.js"(exports2,module2){!function(e,t2){if("object"==typeof exports2&&"object"==typeof module2)module2.exports=t2();else if("function"==typeof define&&define.amd)define([],t2);else{var s=t2();for(var i in s)("object"==typeof exports2?exports2:e)[i]=s[i]}}(global,()=>(()=>{"use strict";var e={n:t3=>{var s2=t3&&t3.__esModule?()=>t3.default:()=>t3;return e.d(s2,{a:s2}),s2},d:(t3,s2)=>{for(var i2 in s2)e.o(s2,i2)&&!e.o(t3,i2)&&Object.defineProperty(t3,i2,{enumerable:true,get:s2[i2]})},o:(e2,t3)=>Object.prototype.hasOwnProperty.call(e2,t3),r:e2=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e2,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e2,"__esModule",{value:true})}},t2={};e.r(t2),e.d(t2,{Channel:()=>g,EventBuffer:()=>d,Session:()=>m,SseError:()=>v,createChannel:()=>y2,createEventBuffer:()=>w,createSession:()=>b});const s=require("http"),i=e2=>JSON.stringify(e2),r=/(\r\n|\r|\n)/g,n=/\n+$/g,o=e2=>{let t3=e2;return t3=t3.replace(r,"\n"),t3=t3.replace(n,""),t3},h=require("crypto");let a;a=h.randomUUID?()=>(0,h.randomUUID)():()=>(0,h.randomBytes)(4).toString("hex");const c=e2=>async(t3,s2={})=>{const{eventName:i2="stream"}=s2;return await new Promise((s3,r2)=>{t3.on("data",t4=>{let s4;s4=Buffer.isBuffer(t4)?t4.toString():t4,e2(s4,i2)}),t3.once("end",()=>s3(true)),t3.once("close",()=>s3(true)),t3.once("error",e3=>r2(e3))})},l=e2=>async(t3,s2={})=>{const{eventName:i2="iteration"}=s2;for await(const s3 of t3)e2(s3,i2)};class d{constructor(e2={}){var t3,s2;this.buffer="",this.writeField=(e3,t4)=>{const s3=this.sanitize(t4);return this.buffer+=e3+":"+s3+"\n",this},this.data=e3=>{const t4=this.serialize(e3);return this.writeField("data",t4),this},this.id=(e3="")=>(this.writeField("id",e3),this),this.retry=e3=>{const t4=e3.toString();return this.writeField("retry",t4),this},this.comment=(e3="")=>(this.writeField("",e3),this),this.dispatch=()=>(this.buffer+="\n",this),this.push=(e3,t4="message",s3=a())=>(this.event(t4).id(s3).data(e3).dispatch(),this),this.stream=c(this.push),this.iterate=l(this.push),this.clear=()=>(this.buffer="",this),this.read=()=>this.buffer,this.serialize=null!==(t3=e2.serializer)&&void 0!==t3?t3:i,this.sanitize=null!==(s2=e2.sanitizer)&&void 0!==s2?s2:o}event(e2){return this.writeField("event",e2),this}}const u2=require("events");var f=e.n(u2);class p extends f(){addListener(e2,t3){return super.addListener(e2,t3)}prependListener(e2,t3){return super.prependListener(e2,t3)}prependOnceListener(e2,t3){return super.prependOnceListener(e2,t3)}on(e2,t3){return super.on(e2,t3)}once(e2,t3){return super.once(e2,t3)}emit(e2,...t3){return super.emit(e2,...t3)}off(e2,t3){return super.off(e2,t3)}removeListener(e2,t3){return super.removeListener(e2,t3)}}class v extends Error{constructor(e2){super(e2),this.message=`better-sse: ${e2}`}}class m extends p{constructor(e2,t3,r2={}){var n2,h2,u3,f2,p2,m2,b2;super(),this.lastId="",this.isConnected=false,this.state={},this.initialize=()=>{var e3,t4,i2;const r3=`http://${this.req.headers.host}${this.req.url}`,n3=new URL(r3).searchParams;if(this.trustClientEventId){const s2=null!==(i2=null!==(t4=null!==(e3=this.req.headers["last-event-id"])&&void 0!==e3?e3:n3.get("lastEventId"))&&void 0!==t4?t4:n3.get("evs_last_event_id"))&&void 0!==i2?i2:"";this.lastId=s2}const o2={};this.res instanceof s.ServerResponse?(o2["Content-Type"]="text/event-stream",o2["Cache-Control"]="private, no-cache, no-store, no-transform, must-revalidate, max-age=0",o2.Connection="keep-alive",o2.Pragma="no-cache",o2["X-Accel-Buffering"]="no"):(o2["content-type"]="text/event-stream",o2["cache-control"]="private, no-cache, no-store, no-transform, must-revalidate, max-age=0",o2.pragma="no-cache",o2["x-accel-buffering"]="no");for(const[e4,t5]of Object.entries(this.headers))o2[e4]=null!=t5?t5:"";this.res.writeHead(this.statusCode,o2),n3.has("padding")&&this.buffer.comment(" ".repeat(2049)).dispatch(),n3.has("evs_preamble")&&this.buffer.comment(" ".repeat(2056)).dispatch(),null!==this.initialRetry&&this.buffer.retry(this.initialRetry).dispatch(),this.flush(),null!==this.keepAliveInterval&&(this.keepAliveTimer=setInterval(this.keepAlive,this.keepAliveInterval)),this.isConnected=true,this.emit("connected")},this.onDisconnected=()=>{this.req.removeListener("close",this.onDisconnected),this.res.removeListener("close",this.onDisconnected),this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.isConnected=false,this.emit("disconnected")},this.keepAlive=()=>{this.buffer.comment().dispatch(),this.flush()},this.data=e3=>(this.buffer.data(e3),this),this.id=(e3="")=>(this.buffer.id(e3),this.lastId=e3,this),this.retry=e3=>(this.buffer.retry(e3),this),this.comment=e3=>(this.buffer.comment(e3),this),this.dispatch=()=>(this.buffer.dispatch(),this),this.flush=()=>(this.res.write(this.buffer.read()),this.buffer.clear(),this),this.push=(e3,t4="message",s2=a())=>{if(!this.isConnected)throw new v("Cannot push data to a non-active session.");return this.buffer.push(e3,t4,s2),this.flush(),this.lastId=s2,this.emit("push",e3,t4,s2),this},this.stream=c(this.push),this.iterate=l(this.push),this.batch=async e3=>{if(e3 instanceof d)this.res.write(e3.read());else{const t4=new d({serializer:this.serialize,sanitizer:this.sanitize});await e3(t4),this.res.write(t4.read())}},this.req=e2,this.res=t3;const g2=null!==(n2=r2.serializer)&&void 0!==n2?n2:i,y3=null!==(h2=r2.sanitizer)&&void 0!==h2?h2:o;this.serialize=g2,this.sanitize=y3,this.buffer=new d({serializer:g2,sanitizer:y3}),this.trustClientEventId=null===(u3=r2.trustClientEventId)||void 0===u3||u3,this.initialRetry=null===r2.retry?null:null!==(f2=r2.retry)&&void 0!==f2?f2:2e3,this.keepAliveInterval=null===r2.keepAlive?null:null!==(p2=r2.keepAlive)&&void 0!==p2?p2:1e4,this.statusCode=null!==(m2=r2.statusCode)&&void 0!==m2?m2:200,this.headers=null!==(b2=r2.headers)&&void 0!==b2?b2:{},this.req.once("close",this.onDisconnected),this.res.once("close",this.onDisconnected),setImmediate(this.initialize)}event(e2){return this.buffer.event(e2),this}}const b=(...e2)=>new Promise(t3=>{const s2=new m(...e2);s2.once("connected",()=>{t3(s2)})});class g extends p{constructor(){super(),this.state={},this.sessions=new Set,this.broadcast=(e2,t3="message",s2={})=>{const i2=a(),r2=s2.filter?this.activeSessions.filter(s2.filter):this.sessions;for(const s3 of r2)s3.push(e2,t3,i2);return this.emit("broadcast",e2,t3,i2),this}}get activeSessions(){return Array.from(this.sessions)}get sessionCount(){return this.sessions.size}register(e2){if(this.sessions.has(e2))return this;if(!e2.isConnected)throw new v("Cannot register a non-active session.");return e2.once("disconnected",()=>{this.emit("session-disconnected",e2),this.deregister(e2)}),this.sessions.add(e2),this.emit("session-registered",e2),this}deregister(e2){return this.sessions.has(e2)?(this.sessions.delete(e2),this.emit("session-deregistered",e2),this):this}}const y2=(...e2)=>new g(...e2),w=(...e2)=>new d(...e2);return t2})())}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports2,module2){"use strict";var{Duplex}=require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream2(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err2){called=true;callback(err2)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module2.exports=createWebSocketStream2}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports2,module2){"use strict";module2.exports={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports2,module2){"use strict";var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module2.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports2,module2){"use strict";var zlib=require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate=class{constructor(options,isServer,maxPayload){this._maxPayload=maxPayload|0;this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._isServer=!!isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&!params.client_max_window_bits){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module2.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;err[kStatusCode]=1007;this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports2,module2){"use strict";var{isUtf8}=require("buffer");var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}module2.exports={isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module2.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=require("utf-8-validate");module2.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports2,module2){"use strict";var{Writable}=require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var promise=Promise.resolve();var queueTask=typeof queueMicrotask==="function"?queueMicrotask:queueMicrotaskShim;var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=!!options.allowSynchronousEvents;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else{data=fragments}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;queueTask(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;queueTask(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;queueTask(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}};module2.exports=Receiver2;function queueMicrotaskShim(cb){promise.then(cb).catch(throwErrorNextTick)}function throwError(err){throw err}function throwErrorNextTick(err){process.nextTick(throwError,err)}}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports2,module2){"use strict";var{Duplex}=require("stream");var{randomFillSync}=require("crypto");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER}=require_constants();var{isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._deflating=false;this._queue=[]}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{randomFillSync(mask,0,4)}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else{buf.set(data,2)}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;if(perMessageDeflate){const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(this._deflating){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}else{this.sendFrame(_Sender.frame(data,{[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1:false}),cb)}}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._deflating=true;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");if(typeof cb==="function")cb(err);for(let i=0;i{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension].concat(Object.keys(params).map(k=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map(v=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module2.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports2,module2){"use strict";var EventEmitter=require("events");var https2=require("https");var http2=require("http");var net=require("net");var tls=require("tls");var{randomBytes,createHash}=require("crypto");var{Duplex,Readable}=require("stream");var{URL:URL2}=require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver2=require_receiver();var Sender2=require_sender();var{BINARY_TYPES,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener:addEventListener2,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var closeTimeout=30*1e3;var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});this._sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._socket=socket;receiver[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=_WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,err=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),closeTimeout)}pause(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener2;WebSocket3.prototype.removeEventListener=removeEventListener;module2.exports=WebSocket3;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:false,autoPong:true,protocolVersion:protocolVersions[1],maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch(e){throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request=isSecure?https2.request:http2.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=isSecure?tlsConnect:netConnect;opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate(opts.perMessageDeflate!==true?opts.perMessageDeflate:{},false,opts.maxPayload);opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key2,value]of Object.entries(headers)){options.headers[key2.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",res=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;if(res.headers.upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket3.CLOSING;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket3.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}websocket.emit("error",err)}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;let chunk;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&(chunk=websocket._socket.read())!==null){websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports2,module2){"use strict";var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i{const body=http2.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(req.headers.upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(!key||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==8&&version!==13){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate(this.options.perMessageDeflate,true,this.options.maxPayload);try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}};module2.exports=WebSocketServer2;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http2.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r -`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message){if(server.listenerCount("wsClientError")){const err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message)}}}});var index_node_exports={};__export(index_node_exports,{CMDService:()=>CMDService,Callable:()=>Callable,E2EEService:()=>E2EEService,ECSService:()=>ECSService,EventHandler:()=>EventHandler,Graph:()=>Graph,GraphNode:()=>GraphNode,HTTPbackend:()=>HTTPbackend,Router:()=>Router,SSEbackend:()=>SSEbackend,Service:()=>Service,SessionsService:()=>SessionsService,WSSbackend:()=>WSSbackend,animate:()=>animate,backprop:()=>backprop,bindListener:()=>bindListener,branching:()=>branching,connectionHasId:()=>connectionHasId,defaultManifest:()=>defaultManifest,defaultServiceWorker:()=>defaultServiceWorker,getAllProperties:()=>getAllProperties,getCallbackFromString:()=>getCallbackFromString,htmlBodyBoilerPlate:()=>htmlBodyBoilerPlate,instanceObject:()=>instanceObject,isFunction:()=>isFunction,isNativeClass:()=>isNativeClass,isTypedArray:()=>isTypedArray,loaders:()=>loaders,loop:()=>loop,methodstrings:()=>methodstrings,nodeTemplates:()=>nodeTemplates,recursivelyAssign:()=>recursivelyAssign2,remoteGraphRoutes:()=>remoteGraphRoutes,scriptBoilerPlate:()=>scriptBoilerPlate,spliceTypedArray:()=>spliceTypedArray,state:()=>state,substitute__operator:()=>substitute__operator,transformListenerResult:()=>transformListenerResult,triggerListenerOncreate:()=>triggerListenerOncreate,wrapArgs:()=>wrapArgs});module.exports=__toCommonJS(index_node_exports);var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t2=>{for(const key in t2){this.unsubscribe(t2[key]);this.delete(t2[key].__node.tag);delete this.__node.roots[t2[key].__node.tag];this.delete(key);delete this.__node.roots[key];t2[key].__node.tag=t2[key].__node.tag.substring(t2[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t2[key])}t2[key].__callDisconnected();if(t2[key].__children){recursiveRemove(t2[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function getFnParamNames(fn){if(typeof fn!=="string")fn=fn.toString();const arrowMatch=fn.match(/\(?[^]*?\)?\s*=>/);if(arrowMatch)return arrowMatch[0].replace(/[()\s]/gi,"").replace("=>","").split(",");const match=fn.match(/\([^]*?\)/);return match?match[0].replace(/[()\s]/gi,"").split(","):[]}var getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path3.join("."))}}}return value}return function stringifyWithCircularRefs3(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value==="function"?value.toString():value,path3.join("."))}}}return typeof value==="function"?value.toString():value}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path3.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str=properties.toString();else if(typeof properties==="string")str=properties;if(str){if(connection.run)return connection.run("setNode",[str]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(template);if(node){nodeTemplates[node.__node.tag]=template;return node.__node?.tag}else return false}else return false},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str=recursivelyStringifyFunctions(properties);return str},getListenerJSON:function(){const triggers=this.__node.state.triggers;let result={};for(const key in triggers){triggers[key].forEach(trigger=>{let t2=trigger;if(!result[t2.target])result[t2.target]={};let l=t2.source+(t2.key?"."+t2.key:"");result[t2.target][l]={__callback:t2.__callback};if(t2.__args)result[t2.target][l].__args=t2.__args;if(t2.subInput)result[t2.target][l].subInput=t2.subInput})}return result},makeRootTransferrable:function(){let roots={};for(const r in this.__node.graph.__node.roots){let properties=this.__node.graph.__node.roots[r];if(typeof properties==="function"){roots[r]=properties.toString()}else if(typeof properties!=="object"){roots[r]=properties}else{roots[r]={};let keys=Object.getOwnPropertyNames(properties).filter(v=>!objProps2.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter(v=>!objProps2.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(typeof properties[key]==="function"){roots[r][key]=properties[key].toString()}else if(typeof properties[key]==="object")roots[r][key]=stringifyWithFunctionsAndCircularRefs(properties[key]);else roots[r][key]=properties[key]}}}return roots},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key of properties){if(typeof node[key]==="function"){let str=node[key].toString();let isNative=str.indexOf("[native code]")>-1;result[key]={type:"function",args:getFnParamNames(node[key]),native:isNative}}else result[key]=typeof node[key]}return result}return void 0},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]?.type==="function"){if(props[key].native||props[key].args){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{proxy[key]=()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})}}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};if(connection.run)return connection.run("receiveClass",[str,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str=fn.toString();let message={route:"setNode",args:[str,fnName]};if(connection.run)return connection.run("setNode",[str,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str,fnName]},void 0);return new Promise(r=>r(fnName))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str,fnName]}));return new Promise(r=>r(fnName))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var objProps2=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var ECSService=class extends Service{entities={};systems={};entityMap=new Map;entityKeyMap=new Map;order=[];animating=false;entityCt=0;systemCt=0;constructor(options){super(options);this.load(this);if(options?.systems)for(const key in options.systems){this.addSystem(options.systems[key],void 0,void 0,void 0,void 0,options.order)}if(options?.entities){for(const key in options.entities){this.addEntity(options.entities[key],options.entities[key].components)}}}updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};stop=()=>{this.animating=false};start=filter=>{this.animateEntities(filter)};addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};removeEntities(entities){if(!Array.isArray(entities))entities=Object.keys(entities);entities.forEach(t2=>{this.removeEntity(t2)})}removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return new sjcl.hash.sha256().update(a).finalize()};sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=sjcl_default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};static generateSecret(){return sjcl_default.codec.base64.fromBits(sjcl_default.random.randomWords(8,10))}encrypt(message,key){message=sjcl_default.encrypt(key,message).cipher;return message}decrypt(message,key){message=sjcl_default.decrypt(key,message);return message}encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=sjcl_default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(sjcl_default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=sjcl_default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message}};var http=__toESM(require("http"));var https=__toESM(require("https"));var fs=__toESM(require("fs"));var path=__toESM(require("path"));function htmlBodyBoilerPlate(html){let template=``;if(Array.isArray(html)){html.forEach(src=>{template+=src})}else{template+=html}template+=``;return template}function scriptBoilerPlate(scripts){let template=``;if(Array.isArray(scripts)){scripts.forEach(src=>{template+=``})}else{template+=``}template+=``;return template}var defaultServiceWorker=function(cacheExpirationDays=4/24){return`//https://github.com/ibrahima92/pwa-with-vanilla-js - -//https://github.com/ibrahima92/pwa-with-vanilla-js -let cacheName = 'pwa-assets'; -const assets = [ - "/", - "/index.html", - "/dist/index.css", //alt default paths - "/dist/index.js", - '/favicon.ico' -]; - -let cacheExpiration = 1000 * 60 * //seconds - 60 * //minutes - 24 * //hours - ${cacheExpirationDays}; //days - -let isValid = function (response) { - if (!response) return false; - var fetched = response.headers.get('sw-fetched-on'); - if (fetched && (!navigator.onLine || (parseFloat(fetched) + (cacheExpiration)) > new Date().getTime())) - return true; - return false; -}; - -self.addEventListener("install", installEvent => { - installEvent.waitUntil( - caches.open(cacheName).then(cache => { - cache.addAll(assets); - }) - ); -}); - -self.addEventListener("fetch", fetchEvent => { //https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/ - fetchEvent.respondWith( - caches.match(fetchEvent.request).then(function (response) { - - // If there's a cached API and it's still valid, use it - if (isValid(response)) { - return response; - } - - // Otherwise, make a fresh API call - if(response && !assets.includes(fetchEvent.request.url)) return response; - // Otherwise, make a fresh API call - else return fetch(fetchEvent.request).then(function (response) { - - // Cache for offline access - if(assets.includes(fetchEvent.request.url)){ - var copy = response.clone(); - fetchEvent.waitUntil(caches.open(cacheName).then(function (cache) { - var headers = new Headers(copy.headers); - headers.append('sw-fetched-on', new Date().getTime()); - return copy.blob().then(function (body) { - return cache.put(fetchEvent.request, new Response(body, { - status: copy.status ? copy.status : 200, - statusText: copy.statusText, - headers: headers - })); - }); - })); - } - - // Return the requested file - return response; - - }) - // .catch(function (error) { - // return caches.match(request).then(function (response) { //fallback to offline cache - // return response || caches.match('/offline.json'); //todo: figure out what is supposed to go in offline.json (https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/) - // }); - // }); - })); -}); - -`};var defaultManifest=(pwaName="PWA")=>{return`{ - "short_name": "${pwaName}", - "name": "${pwaName}", - "start_url": "/", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "description": "${pwaName} Test", - "lang": "en-US", - "permissions": [ - "storage" - ], - "icons":[{ - "src": "./assets/logo196.png", - "sizes": "196x196" - }, - { - "src": "./assets/logo512.png", - "sizes": "512x512" - }] -}`};var HTTPbackend=class extends Service{name="http";server;debug=false;servers={};mimeTypes={".html":"text/html",".htm":"text/html",".js":"text/javascript",".css":"text/css",".json":"application/json",".txt":"text/plain",".png":"image/png",".jpg":"image/jpg",".jpeg":"image/jpg",".gif":"image/gif",".svg":"image/svg+xml",".xhtml":"application/xhtml+xml",".bmp":"image/bmp",".wav":"audio/wav",".mp3":"audio/mpeg",".mp4":"video/mp4",".xml":"application/xml",".webm":"video/webm",".webp":"image/webp",".weba":"audio/webm",".woff":"font/woff","woff2":"font/woff2",".ttf":"application/font-ttf",".eot":"application/vnd.ms-fontobject",".otf":"application/font-otf",".wasm":"application/wasm",".zip":"application/zip",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".tif":"image/tiff",".sh":"application/x-sh",".csh":"application/x-csh",".rar":"application/vnd.rar",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".mpeg":"video/mpeg",".mjs":"text/javascript",".cjs":"text/javascript",".jsonld":"application/ld+json",".jar":"application/java-archive",".ico":"image/vnd.microsoft.icon",".gz":"application/gzip","epub":"application/epub+zip",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".csv":"text/csv",".avi":"video/x-msvideo",".aac":"audio/aac",".mpkg":"application/vnd.apple.installer+xml",".oga":"audio/ogg",".ogv":"video/ogg","ogx":"application/ogg",".php":"application/x-httpd-php",".rtf":"application/rtf",".swf":"application/x-shockwave-flash",".7z":"application/x-7z-compressed",".3gp":"video/3gpp"};constructor(options,settings){super(options);this.load(this);if(settings){this.setupServer(settings)}}onStarted=(protocol,host,port)=>{console.log(`\u{1F431} Node server running at - ${protocol}://${host}:${port}/`)};setupServer=(options={protocol:"http",host:"localhost",port:8080,startpage:"index.html"},requestListener,onStarted)=>{if(options.pages){for(const key in options.pages){if(typeof options.pages[key]==="string"){this.addPage(`${options.port}/${key}`,options.pages[key])}else if(typeof options.pages[key]==="object"||typeof options.pages[key]==="function"){if(options.pages[key].template){options.pages[key].get=options.pages[key].template}let rt=`${options.port}/${key}`;if(key!=="_all")this.load({[rt]:options.pages[key]})}}}this.setupHTTPserver(options,requestListener,onStarted)};open=this.setupServer;setupHTTPserver=(options={host:"localhost",port:8080,startpage:"index.html",errpage:void 0},requestListener,onStarted=()=>{this.onStarted("http",options.host,options.port)})=>{const host=options.host?options.host:"localhost";const port=options.port?options.port:8e3;if(!host||!port)return;const address=`${host}:${port}`;if(this.servers[address])this.terminate(this.servers[address]);if(!("keepState"in options))options.keepState=true;const served={server:void 0,type:"httpserver",address,...options};if(!requestListener)requestListener=(request,response)=>{let received={args:{request,response},method:request.method,served};let url=request.url.slice(1);if(!url)url="/";if(options.debug){let time=getHoursAndMinutes(new Date);console.log(time," | ","From: ",request.socket?.remoteAddress,"For: ",request.url," | ",request.method)}if(options.pages){getPageOptions.call(this,url,received,options.pages,request,response,options.port)}else received.route=url;this.receive(received)};let server=void 0;if(options.protocol==="http")server=http.createServer(requestListener);else{let opts;if(options.keypath&&options.certpath){opts={key:fs.readFileSync(options.keypath),cert:fs.readFileSync(options.certpath),passphrase:options.passphrase};server=https.createServer(opts,requestListener)}else console.error("Error, key and/or cert .pem SSL files not provided. See OpenSSL certbot for more info on how to create free SSL certifications, or create your own self-signed one for local development.")}if(!server){console.error("Server not successfully created.");return void 0}served.server=server;served.terminate=()=>{this.terminate(served)};served.service=this;this.servers[address]=served;served._id=options._id?options._id:address;return new Promise((resolve,reject)=>{let resolved;server.on("error",err=>{if(served.onerror)served.onerror(err,served);else console.error("Server error:",err.toString());if(!resolved)reject(err)});server.on("clientError",(err,socket)=>{if(served.onerror)served.onerror(err,served);else console.error(getHoursAndMinutes(new Date)," | Server clientError:",err.toString()," | From: ",socket.remoteAddress);if(socket)socket.destroy()});server.on("tlsClientError",(err,socket)=>{if(served.onerror)served.onerror(err,served);else console.error(getHoursAndMinutes(new Date)," | Server tlsClientError: ",err.toString()," | From: ",socket.remoteAddress);if(socket)socket.destroy()});server.on("upgrade",(request,socket,head)=>{if(served.onupgrade)served.onupgrade(request,socket,head,served)});server.listen(port,host,()=>{onStarted();if(served.onopen)served.onopen(served);resolved=true;resolve(served)})})};transmit=(message,options,ondata,onend)=>{let input=message;if(typeof input==="object"&&!input.byteLength)input=JSON.stringify(input);if(typeof options==="string"&&message)return this.POST(options,message);else if(typeof options==="string")return this.GET(options);if(!options){let server=this.servers[Object.keys(this.servers)[0]];options={protocol:server.protocol,host:server.host,port:server.port,method:"POST",path:message.route,headers:{"Content-Type":"application/json","Content-Length":input.length}}}else if(!options.headers){options.headers={"Content-Type":"application/json","Content-Length":input.length}}return this.request(options,input,ondata,onend)};withResult=(response,result,message)=>{if(result&&!response.writableEnded&&!response.destroyed){let mimeType="text/plain";let head={};if(typeof result==="string"){let extname2=path.extname(result);if(extname2&&fs.existsSync(path.join(process.cwd(),result))){mimeType=this.mimeTypes[extname2]||"application/octet-stream";result=fs.readFileSync(path.join(process.cwd(),result));if(mimeType==="text/html"&&(message.served?.pages?._all||message.served?.pages?.[message.route])){let{templateString,headers}=this.injectPageCode(result.toString(),message.route,message.served);result=templateString;Object.assign(head,headers)}}else if(typeof result==="string"&&result.includes("<")&&result.includes(">")&&result.indexOf("<")")){head["Content-Type"]="text/html";if(message?.served?.pages?._all||message?.served?.pages?.[message.route]){let{templateString,headers}=this.injectPageCode(result,message.route,message.served);result=templateString;Object.assign(head,headers)}response.writeHead(200,head);response.end(result,"utf-8");return}}else if(typeof result==="object"){result=JSON.stringify(result);mimeType="application/json"}head["Content-Type"]=mimeType;response.writeHead(200,head);response.end(result,"utf-8")}else{try{response.destroy()}catch{}}};injectPageCode=(templateString,url,served)=>{if(served?.pages?.[url]?.inject){if(typeof served.pages[url].inject==="object")templateString=this.buildPage(served.pages[url].inject,templateString);else if(typeof served.pages[url].inject==="function")templateString+=served.pages[url].inject();else if(typeof served.pages[url].inject==="string"||typeof served.pages[url].inject==="number")templateString+=served.pages[url].inject}if(served?.pages?._all?.inject){if(typeof served.pages._all.inject==="object")templateString=this.buildPage(served.pages._all.inject,templateString);else if(typeof served.pages._all.inject==="function")templateString+=served.pages._all.inject();else if(typeof served.pages._all.inject==="string"||typeof served.pages._all.inject==="number")templateString+=served.pages._all.inject}let headers={};if(served.pages._all.headers)Object.assign(headers,served.pages._all.headers);if(served.pages[url].headers)Object.assign(headers,served.pages[url].headers);return{templateString,headers}};receive=message=>{if(this.debug)console.log(message.args.request.method,message.args.request.url);let result=new Promise((resolve,reject)=>{this.responsePromiseHandler(resolve,reject,message,message.args.request,message.args.response,message.method,message.served)}).catch(er=>{console.error("Request Error:",er)});return result};responseOnErrorPromiseHandler=(response,reject,err)=>{if(!response.writableEnded||!response.destroyed){response.statusCode=400;response.end(void 0,void 0);reject(err)}else{try{response.destroy()}catch{}reject(err)}};getFailedPromiseHandler=(resolve,reject,requestURL,message,response,served)=>{if(response.writableEnded||response.destroyed)reject(requestURL);if(requestURL=="./"||requestURL==served?.startpage){let template=`

Brains@Play Server

`;if(served?.pages?._all||served?.pages?.error){let{templateString,headers}=this.injectPageCode(template,message.route,served);template=templateString}response.writeHead(200,{"Content-Type":"text/html"});response.end(template,"utf-8");resolve(template);if(served?.keepState)this.setState({[served.address]:template});return}else if(this.debug)console.log(`File ${requestURL} does not exist on path!`);response.writeHead(500);response.end(void 0,void 0);reject(requestURL)};handleBufferedPostBodyPromiseHandler=(resolve,body,message,response,served)=>{body=Buffer.concat(body).toString();if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}let route,method,args;if(body?.route){route=body.route;method=body.method;args=body.args;if(!route){if(typeof body.route==="string"){if(body.route.includes("/")&&body.route.length>1)body.route=body.route.split("/").pop()}route=body.route}}if(!route){if(message?.route){let route2=message.route;method=message.method;args=message.args;if(!route2){if(typeof message.route==="string"){if(message.route.includes("/")&&message.route.length>1)message.route=message.route.split("/").pop()}route2=message.route}}}let res=body;if(route){if(this.restrict?.[route]){try{response.destroy()}catch{}resolve(res)}else{if(body.method){res=this.handleMethod(route,method,args)}else if(body.node){res=this.handleGraphNodeCall(body.node,body.args)}else res=this.handleServiceMessage({route,args,method});if(res instanceof Promise){res.then(r=>{this.withResult(response,r,message);if(served?.keepState)this.setState({[served.address]:res});resolve(res)})}else{this.withResult(response,res,message);if(served?.keepState)this.setState({[served.address]:res});resolve(res)}}}else if(!response.writableEnded||!response.destroyed){response.statusCode=200;response.end(void 0,void 0);resolve(res)}else{try{response.destroy()}catch{}resolve(res)}};onRequestFileReadPromiseHandler=(error,content,resolve,reject,requestURL,response,message,served)=>{if(error){if(error.code=="ENOENT"){if(served?.errpage){fs.readFile(served.errpage,(er,content2)=>{response.writeHead(404,{"Content-Type":"text/html"});if(served.pages?._all||served.pages?.error){let{templateString,headers}=this.injectPageCode(content2.toString(),message.route,served);content2=templateString}response.end(content2,"utf-8");reject(content2)})}else{response.writeHead(404,{"Content-Type":"text/html"});let content2=`

Error: ${error.code}

`;if(served?.pages?._all||served?.pages?.[message.route]){let{templateString,headers}=this.injectPageCode(content2.toString(),message.route,served);content2=templateString}response.end(content2,"utf-8");reject(error.code)}}else{response.writeHead(500);response.end("Something went wrong: "+error.code+" ..\n","utf-8");reject(error.code)}}else{var extname2=String(path.extname(requestURL)).toLowerCase();var contentType=this.mimeTypes[extname2]||"application/octet-stream";let head={"Content-Type":contentType};if(contentType==="text/html"&&(served?.pages?._all||served?.pages?.[message.route])){let{templateString,headers}=this.injectPageCode(content.toString(),message.route,served);Object.assign(head,headers);content=templateString}response.writeHead(200,head);response.end(content,"utf-8");resolve(content)}};responsePromiseHandler=(resolve,reject,message,request,response,method,served)=>{response.on("error",err=>{if(served.debug){let time=getHoursAndMinutes(new Date);console.error(time,"| Response Error: ",err," From: ",request.socket?.remoteAddress," For: ",request.url," | ",request.method)}this.responseOnErrorPromiseHandler(response,reject,err);request.destroy();request.socket?.destroy()});if(method==="GET"||method==="get"){var requestURL="."+request.url;if(request.url&&this.restrict?.[request.url])reject(request.url);if(requestURL=="./"&&served?.startpage){requestURL=served.startpage}if(requestURL.includes("?"))requestURL=requestURL.substring(0,requestURL.indexOf("?"));if((request.url!=="/"||served?.startpage)&&fs.existsSync(path.join(process.cwd(),requestURL))){if(response.writableEnded||response.destroyed)reject(requestURL);else{fs.readFile(path.join(process.cwd(),requestURL),(error,content)=>{this.onRequestFileReadPromiseHandler(error,content,resolve,reject,requestURL,response,message,served)})}}else if(message.route){let route;if(served){let rt=`${served.port}/${message.route}`;if(this.__node.nodes.get(rt))route=rt}if(!route&&this.__node.nodes.get(message.route))route=message.route;if(route){let res;if(message.method){res=this.handleMethod(route,message.method,void 0)}else if(message.node){res=this.handleGraphNodeCall(message.node,void 0)}else res=this.handleServiceMessage({route,args:void 0,method:message.method});if(res instanceof Promise)res.then(r=>{if(served?.keepState)this.setState({[served.address]:res});this.withResult(response,r,message);resolve(res)});else if(res){if(served?.keepState)this.setState({[served.address]:res});this.withResult(response,res,message);resolve(res)}}else if(message.redirect){response.writeHead(301,{"Location":message.redirect});response.end();resolve(true)}else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served)}else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served)}else{let requestBody;let timedOut=true;let timeout;request.on("data",chunk=>{if(!requestBody)requestBody=[];requestBody.push(chunk);if(timedOut){timedOut=false;if(timeout)clearTimeout(timeout)}}).on("end",()=>{this.handleBufferedPostBodyPromiseHandler(resolve,requestBody,message,response,served)});timeout=setTimeout(()=>{if(timedOut){let errMessage=new Error(`Request timed out from | ${request.socket?.remoteAddress} | For: ${request.url} | ${request.method}`);request.destroy(errMessage);served.server.emit("clientError",errMessage,request.socket);if(served.debug){console.error(errMessage)}reject(errMessage)}},served.timeout?served.timeout:1e3)}};request=(options,send,ondata,onend)=>{let client=http;if(options.protocol?.includes("https")){client=https}delete options.protocol;const req=client.request(options,res=>{if(ondata)res.on("data",ondata);if(onend)res.on("end",onend)});if(options.headers){for(const head in options.headers){req.setHeader(head,options.headers[head])}}if(send)req.write(send);req.end();return req};POST=(url,data,headers)=>{let urlstring=url;if(urlstring instanceof URL)urlstring=url.toString();let protocol=urlstring.startsWith("https")?"https":"http";let host,port,path3;let split=urlstring.split("/");split.forEach(s=>{if(s.includes(":")){let ss=s.split(":");host=ss[0];port=ss[1]}});if(split.length>3){path3=split.slice(3).join("/")}let req=this.request({protocol,host,port,path:path3,method:"POST",headers},data);return req};GET=url=>{return new Promise((resolve,reject)=>{let client=http;let urlstring=url;if(url instanceof URL)urlstring=url.toString();if(urlstring.includes("https")){client=https}client.get(url,resp=>{let chunks=[];resp.on("data",chunk=>{chunks.push(chunk)});resp.on("end",()=>{resolve(Buffer.concat(chunks))})}).on("error",err=>{reject(err)})})};terminate=served=>{if(typeof served==="string")served=this.servers[served];if(typeof served==="object"){served.server.close();if(served.onclose)served.onclose(served)}};getRequestBody(req){let chunks=[];return new Promise((resolve,reject)=>{req.on("data",chunk=>{chunks.push(chunk)}).on("end",()=>{resolve(Buffer.concat(chunks))}).on("error",er=>{let errMessage=new Error(`Request timed out from | ${req.socket?.remoteAddress} | For: ${req.url} | ${req.method}`);req.destroy(errMessage);reject(errMessage)})})}addPage=(path3,template)=>{if(typeof template==="string"){if(!template.includes(""+template+""}if(typeof this.__node.roots?.[path3]==="object"){this.__node.roots[path3].get=template;this.__node.nodes.get(path3).get=template}else this.load({[path3]:{get:template}})};addHTML=(path3,template)=>{if(typeof template==="string"){if(!template.includes("<")||!template.includes(">"))template="
"+template+"
"}if(typeof this.__node.roots?.[path3]==="object"){this.__node.roots[path3].get=template;this.__node.nodes.get(path3).get=template}else this.load({[path3]:{get:template}})};buildPage=(pageStructure,baseTemplate)=>{let result=``;if(baseTemplate)result+=baseTemplate;let appendTemplate=(obj,r,res)=>{if(!Array.isArray(obj[r])&&typeof obj[r]==="object"){for(const key in obj){appendTemplate(obj,key,res)}}else if(this.__node.nodes.get(r)?.get){let toAdd=this.__node.nodes.get(r)?.get;if(typeof toAdd==="function"){if(Array.isArray(obj[r])){toAdd=toAdd(...obj[r])}else toAdd=toAdd(obj[r])}if(typeof toAdd==="string"){let lastDiv=res.lastIndexOf("<");if(lastDiv>0){let end=res.substring(lastDiv);res=res.substring(0,lastDiv)+toAdd+end}else res+=toAdd}}else if(this.__node.nodes.get(r)?.__operator){let routeresult;if(this.__node.nodes.get(r)?.__operator)routeresult=this.__node.nodes.get(r).__operator(obj[r]);if(typeof routeresult==="string"){let lastDiv=res.lastIndexOf("<");if(lastDiv>0){let end=res.substring(lastDiv);res=res.substring(0,lastDiv)+routeresult+end}else res+=routeresult}}else if(typeof this.__node.nodes.get(r)==="string")res+=this.__node.nodes.get(r);return res};if(Array.isArray(pageStructure)){pageStructure.forEach(r=>{result=appendTemplate(pageStructure,r,result)})}else if(typeof pageStructure==="object"){for(const r in pageStructure){result=appendTemplate(pageStructure,r,result)}}else if(typeof pageStructure==="string")result+=pageStructure;else if(typeof pageStructure==="function")result+=pageStructure();return result};hotreload=(socketURL=`http://localhost:8080/wss`,esbuild_cssFileName)=>{if(socketURL instanceof URL)socketURL=socketURL.toString();const HotReloadClient=(socketUrl,esbuild_cssFileName2)=>{let socket=new WebSocket(socketUrl);function reloadLink(file){let split=file.includes("/")?file.split("/"):file.split("\\");let fname=split[split.length-1];var links=document.getElementsByTagName("link");for(var cl in links){var link=links[cl];if(!file||link.href?.includes(fname)){let href=link.getAttribute("href").split("?")[0];let newHref=href+="";link.setAttribute("href",newHref)}}}function reloadAsset(file,reloadscripts,isJs){let split=file.includes("/")?file.split("/"):file.split("\\");let fname=split[split.length-1];let elements=document.querySelectorAll("[src]");let found=false;for(const s of elements){if(s.src.includes(fname)){if(s.tagName==="SCRIPT"&&!reloadscripts){window.location.reload();return}else{let placeholder=document.createElement("object");s.insertAdjacentElement("afterend",placeholder);s.remove();let elm=s.cloneNode(true);placeholder.insertAdjacentElement("beforebegin",elm);placeholder.remove();found=true}}}if(!found)window.location.reload()}socket.addEventListener("message",ev=>{let message=ev.data;if(typeof message==="string"&&message.startsWith("{")){message=JSON.parse(message)}if(message.file){let f=message.file;let rs=message.reloadscripts;if(f.endsWith("html")||f.endsWith("xml")||f.endsWith("wasm")){window.location.reload()}else if(f.endsWith("css")){if(!esbuild_cssFileName2.endsWith("css"))esbuild_cssFileName2+=".css";reloadLink(esbuild_cssFileName2)}else if(f.endsWith("js")||f.endsWith("ts")||f.endsWith("jsx")||f.endsWith("tsx")||f.endsWith("vue")){reloadAsset(f,rs)}else{reloadLink(f);reloadAsset(f)}}});socket.addEventListener("close",()=>{const interAttemptTimeoutMilliseconds=100;const maxDisconnectedTimeMilliseconds=3e3;const maxAttempts=Math.round(maxDisconnectedTimeMilliseconds/interAttemptTimeoutMilliseconds);let attempts=0;const reloadIfCanConnect=()=>{attempts++;if(attempts>maxAttempts){console.error("Could not reconnect to dev server.");return}socket=new WebSocket(socketUrl);socket.onerror=er=>{console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`)};socket.addEventListener("error",()=>{setTimeout(reloadIfCanConnect,interAttemptTimeoutMilliseconds)});socket.addEventListener("open",()=>{location.reload()})};reloadIfCanConnect()})};return` +var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var require_sjcl=__commonJS({"services/e2ee/sjcl.js"(exports,module2){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module2&&module2.exports){try{H=require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4(()=>{"use strict";var e={n:t2=>{var s2=t2&&t2.__esModule?()=>t2.default:()=>t2;return e.d(s2,{a:s2}),s2},d:(t2,s2)=>{for(var i2 in s2)e.o(s2,i2)&&!e.o(t2,i2)&&Object.defineProperty(t2,i2,{enumerable:true,get:s2[i2]})},o:(e2,t2)=>Object.prototype.hasOwnProperty.call(e2,t2),r:e2=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e2,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e2,"__esModule",{value:true})}},t={};e.r(t),e.d(t,{Channel:()=>f,Session:()=>u,createChannel:()=>v,createSession:()=>p});const s=require("http"),i=require("events");var r=e.n(i);class n extends r(){addListener(e2,t2){return super.addListener(e2,t2)}prependListener(e2,t2){return super.prependListener(e2,t2)}prependOnceListener(e2,t2){return super.prependOnceListener(e2,t2)}on(e2,t2){return super.on(e2,t2)}once(e2,t2){return super.once(e2,t2)}emit(e2,...t2){return super.emit(e2,...t2)}off(e2,t2){return super.off(e2,t2)}removeListener(e2,t2){return super.removeListener(e2,t2)}}const o=e2=>JSON.stringify(e2),a=/(\r\n|\r|\n)/g,h=/\n+$/g,l=e2=>{let t2=e2;return t2=t2.replace(a,"\n"),t2=t2.replace(h,""),t2},d=require("crypto");let c;c=d.randomUUID?()=>(0,d.randomUUID)():()=>(0,d.randomBytes)(4).toString("hex");class u extends n{constructor(e2,t2,i2={}){var r2,n2,a2,h2,d2,u2,p2;super(),this.lastId="",this.isConnected=false,this.state={},this.buffer="",this.initialize=()=>{var e3,t3,i3;const r3=`http://${this.req.headers.host}${this.req.url}`,n3=new URL(r3).searchParams;if(this.trustClientEventId){const s2=null!==(i3=null!==(t3=null!==(e3=this.req.headers["last-event-id"])&&void 0!==e3?e3:n3.get("lastEventId"))&&void 0!==t3?t3:n3.get("evs_last_event_id"))&&void 0!==i3?i3:"";this.lastId=s2}const o2={};this.res instanceof s.ServerResponse?(o2["Content-Type"]="text/event-stream",o2["Cache-Control"]="private, no-cache, no-store, no-transform, must-revalidate, max-age=0",o2.Connection="keep-alive",o2.Pragma="no-cache",o2["X-Accel-Buffering"]="no"):(o2["content-type"]="text/event-stream",o2["cache-control"]="private, no-cache, no-store, no-transform, must-revalidate, max-age=0",o2.pragma="no-cache",o2["x-accel-buffering"]="no");for(const[e4,t4]of Object.entries(this.headers))o2[e4]=null!=t4?t4:"";this.res.writeHead(this.statusCode,o2),n3.has("padding")&&this.comment(" ".repeat(2049)).dispatch(),n3.has("evs_preamble")&&this.comment(" ".repeat(2056)).dispatch(),null!==this.initialRetry&&this.retry(this.initialRetry).dispatch(),this.flush(),null!==this.keepAliveInterval&&(this.keepAliveTimer=setInterval(this.keepAlive,this.keepAliveInterval)),this.isConnected=true,this.emit("connected")},this.onDisconnected=()=>{this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.isConnected=false,this.emit("disconnected")},this.writeField=(e3,t3)=>{const s2=this.sanitize(t3);return this.buffer+=e3+":"+s2+"\n",this},this.keepAlive=()=>{this.comment().dispatch().flush()},this.data=e3=>{const t3=this.serialize(e3);return this.writeField("data",t3),this},this.id=(e3="")=>(this.writeField("id",e3),this.lastId=e3,this),this.retry=e3=>{const t3=e3.toString();return this.writeField("retry",t3),this},this.comment=(e3="")=>(this.writeField("",e3),this),this.dispatch=()=>(this.buffer+="\n",this),this.flush=()=>(this.res.write(this.buffer),this.buffer="",this),this.push=(e3,t3="message",s2=c())=>(this.event(t3).id(s2).data(e3).dispatch().flush(),this.emit("push",e3,t3,s2),this),this.stream=async(e3,t3={})=>{const{eventName:s2="stream"}=t3;return new Promise((t4,i3)=>{e3.on("data",e4=>{let t5;t5=Buffer.isBuffer(e4)?e4.toString():e4,this.push(t5,s2)}),e3.once("end",()=>t4(true)),e3.once("close",()=>t4(true)),e3.once("error",e4=>i3(e4))})},this.iterate=async(e3,t3={})=>{const{eventName:s2="iteration"}=t3;for await(const t4 of e3)this.push(t4,s2)},this.req=e2,this.res=t2,this.serialize=null!==(r2=i2.serializer)&&void 0!==r2?r2:o,this.sanitize=null!==(n2=i2.sanitizer)&&void 0!==n2?n2:l,this.trustClientEventId=null===(a2=i2.trustClientEventId)||void 0===a2||a2,this.initialRetry=null===i2.retry?null:null!==(h2=i2.retry)&&void 0!==h2?h2:2e3,this.keepAliveInterval=null===i2.keepAlive?null:null!==(d2=i2.keepAlive)&&void 0!==d2?d2:1e4,this.statusCode=null!==(u2=i2.statusCode)&&void 0!==u2?u2:200,this.headers=null!==(p2=i2.headers)&&void 0!==p2?p2:{},this.req.once("close",this.onDisconnected),setImmediate(this.initialize)}event(e2){return this.writeField("event",e2),this}}const p=(...e2)=>new Promise(t2=>{const s2=new u(...e2);s2.once("connected",()=>{t2(s2)})});class f extends n{constructor(){super(),this.state={},this.sessions=new Set,this.broadcast=(e2,t2="message",s2={})=>{const i2=c();let r2;r2=s2.filter?Array.from(this.sessions).filter(s2.filter):this.sessions;for(const s3 of r2)s3.push(e2,t2,i2);return this.emit("broadcast",e2,t2,i2),this}}get activeSessions(){return Array.from(this.sessions)}get sessionCount(){return this.sessions.size}register(e2){if(this.sessions.has(e2))return this;if(!e2.isConnected)throw new Error("Cannot register a non-active session.");return e2.once("disconnected",()=>{this.emit("session-disconnected",e2),this.deregister(e2)}),this.sessions.add(e2),this.emit("session-registered",e2),this}deregister(e2){return this.sessions.has(e2)?(this.sessions.delete(e2),this.emit("session-deregistered",e2),this):this}}const v=(...e2)=>new f(...e2);return t})())}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module2){"use strict";var{Duplex}=require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream2(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err2){called=true;callback(err2)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module2.exports=createWebSocketStream2}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module2){"use strict";module2.exports={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module2){"use strict";var{EMPTY_BUFFER}=require_constants();function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module2.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module2){"use strict";var zlib=require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate=class{constructor(options,isServer,maxPayload){this._maxPayload=maxPayload|0;this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._isServer=!!isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&!params.client_max_window_bits){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin)data2=data2.slice(0,data2.length-4);this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module2.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;err[kStatusCode]=1007;this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module2){"use strict";var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}module2.exports={isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=require("utf-8-validate");module2.exports.isValidUTF8=function(buf){return buf.length<150?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module2){"use strict";var{Writable}=require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var Receiver2=class extends Writable{constructor(options={}){super();this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._state=GET_INFO;this._loop=false}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=buf.slice(n)}n-=buf.length}while(n>0);return dst}startLoop(cb){let err;this._loop=true;do{switch(this._state){case GET_INFO:err=this.getInfo();break;case GET_PAYLOAD_LENGTH_16:err=this.getPayloadLength16();break;case GET_PAYLOAD_LENGTH_64:err=this.getPayloadLength64();break;case GET_MASK:this.getMask();break;case GET_DATA:err=this.getData(cb);break;default:this._loop=false;return}}while(this._loop);cb(err)}getInfo(){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){this._loop=false;return error(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3")}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){this._loop=false;return error(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1")}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){this._loop=false;return error(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1")}if(!this._fragmented){this._loop=false;return error(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE")}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){this._loop=false;return error(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE")}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){this._loop=false;return error(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN")}if(compressed){this._loop=false;return error(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1")}if(this._payloadLength>125){this._loop=false;return error(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}}else{this._loop=false;return error(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE")}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){this._loop=false;return error(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK")}}else if(this._masked){this._loop=false;return error(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK")}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else return this.haveLength()}getPayloadLength16(){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);return this.haveLength()}getPayloadLength64(){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){this._loop=false;return error(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);return this.haveLength()}haveLength(){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){this._loop=false;return error(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes7)return this.controlMessage(data);if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}return this.dataMessage()}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){return cb(error(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}this._fragments.push(buf)}const er=this.dataMessage();if(er)return cb(er);this.startLoop(cb)})}dataMessage(){if(this._fin){const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else{data=fragments}this.emit("message",data,true)}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){this._loop=false;return error(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8")}this.emit("message",buf,false)}}this._state=GET_INFO}controlMessage(data){if(this._opcode===8){this._loop=false;if(data.length===0){this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else if(data.length===1){return error(RangeError,"invalid payload length 1",true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){return error(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE")}const buf=data.slice(2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){return error(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8")}this.emit("conclude",code,buf);this.end()}}else if(this._opcode===9){this.emit("ping",data)}else{this.emit("pong",data)}this._state=GET_INFO}};module2.exports=Receiver2;function error(ErrorCtor,message,prefix,statusCode,errorCode){const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,error);err.code=errorCode;err[kStatusCode]=statusCode;return err}}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module2){"use strict";var net=require("net");var tls=require("tls");var{randomFillSync}=require("crypto");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER}=require_constants();var{isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var Sender2=class{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._deflating=false;this._queue=[]}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{randomFillSync(mask,0,4)}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else{buf.set(data,2)}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender2.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender2.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(this._deflating){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender2.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;if(perMessageDeflate){const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(this._deflating){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}else{this.sendFrame(Sender2.frame(data,{[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1:false}),cb)}}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender2.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._deflating=true;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");if(typeof cb==="function")cb(err);for(let i=0;i{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension].concat(Object.keys(params).map(k=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map(v=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module2.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module2){"use strict";var EventEmitter=require("events");var https2=require("https");var http2=require("http");var net=require("net");var tls=require("tls");var{randomBytes,createHash}=require("crypto");var{Readable}=require("stream");var{URL:URL2}=require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver2=require_receiver();var Sender2=require_sender();var{BINARY_TYPES,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var closeTimeout=30*1e3;var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket3.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});this._sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._socket=socket;receiver[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);socket.setTimeout(0);socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket3.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket3.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket3.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket3.CLOSED)return;if(this.readyState===WebSocket3.CONNECTING){const msg="WebSocket was closed before the connection was established";return abortHandshake(this,this._req,msg)}if(this.readyState===WebSocket3.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=WebSocket3.CLOSING;this._sender.close(code,data,!this._isServer,err=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),closeTimeout)}pause(){if(this.readyState===WebSocket3.CONNECTING||this.readyState===WebSocket3.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket3.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket3.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket3.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket3.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket3.CONNECTING||this.readyState===WebSocket3.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket3.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket3.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket3.CLOSED)return;if(this.readyState===WebSocket3.CONNECTING){const msg="WebSocket was closed before the connection was established";return abortHandshake(this,this._req,msg)}if(this._socket){this._readyState=WebSocket3.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener;WebSocket3.prototype.removeEventListener=removeEventListener;module2.exports=WebSocket3;function initAsClient(websocket,address,protocols,options){const opts={protocolVersion:protocolVersions[1],maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address;websocket._url=address.href}else{try{parsedUrl=new URL2(address)}catch(e){throw new SyntaxError(`Invalid URL: ${address}`)}websocket._url=address}const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request=isSecure?https2.request:http2.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=isSecure?tlsConnect:netConnect;opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate(opts.perMessageDeflate!==true?opts.perMessageDeflate:{},false,opts.maxPayload);opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key2,value]of Object.entries(headers)){options.headers[key2.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",res=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;if(res.headers.upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{generateMask:opts.generateMask,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket3.CLOSING;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket3.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);cb(err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}websocket.emit("error",err)}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];websocket.pong(data,!websocket._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;let chunk;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&(chunk=websocket._socket.read())!==null){websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module2){"use strict";var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i{const body=http2.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(req.headers.upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(!key||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==8&&version!==13){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate(this.options.perMessageDeflate,true,this.options.maxPayload);try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}};module2.exports=WebSocketServer2;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http2.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r +`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message){if(server.listenerCount("wsClientError")){const err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message)}}}});var index_node_exports={};__export(index_node_exports,{CMDService:()=>CMDService,E2EEService:()=>E2EEService,ECSService:()=>ECSService,Graph:()=>Graph,GraphNode:()=>GraphNode,HTTPbackend:()=>HTTPbackend,Router:()=>Router,SSEbackend:()=>SSEbackend,Service:()=>Service,SessionsService:()=>SessionsService,WSSbackend:()=>WSSbackend,animate:()=>animate,backprop:()=>backprop,bindListener:()=>bindListener,branching:()=>branching,getAllProperties:()=>getAllProperties,instanceObject:()=>instanceObject,isNativeClass:()=>isNativeClass,isTypedArray:()=>isTypedArray,loaders:()=>loaders,loop:()=>loop,recursivelyAssign:()=>recursivelyAssign2,spliceTypedArray:()=>spliceTypedArray,state:()=>state,substitute__operator:()=>substitute__operator,transformListenerResult:()=>transformListenerResult,triggerListenerOncreate:()=>triggerListenerOncreate,unsafeRoutes:()=>unsafeRoutes});module.exports=__toCommonJS(index_node_exports);var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function instanceObject(obj){let props=getAllProperties(obj);let instance={};for(const key of props){instance[key]=obj[key]}return instance}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x){return ArrayBuffer.isView(x)&&Object.prototype.toString.call(x)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path3.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path3=["this"];function clear(){refs.clear();parents.length=0;path3.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path3.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path3.length=idx;--idx;parents[idx]=value;path3[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path3.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var ECSService=class extends Service{constructor(options){super(options);this.entities={};this.systems={};this.entityMap=new Map;this.entityKeyMap=new Map;this.order=[];this.animating=false;this.entityCt=0;this.systemCt=0;this.updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};this.animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};this.stop=()=>{this.animating=false};this.start=filter=>{this.animateEntities(filter)};this.addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};this.addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};this.addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};this.setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};this.removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};this.removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};this.setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};this.setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};this.bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j{this.removeEntity(t)})}filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}};var import_sjcl=__toESM(require_sjcl());var E2EEService=class extends Service{constructor(options,keys,secureKeys,secret){super(options);this.name="e2ee";this.securedKeys=false;this.addKey=(key,_id)=>{if(!_id)_id=`key${Math.floor(Math.random()*1e15)}`;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));decrypted[_id]={key,_id};this.encryptedkeys=import_sjcl.default.encrypt(this.secret,decrypted).cipher;return this.encryptedkeys}else this.keys[_id]={key,_id};return this.keys[_id]};this.encryptRoute=(message,keyId)=>{if(typeof message==="object")message=JSON.stringify(message);let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){message=import_sjcl.default.encrypt(this.secret,decrypted[keyId].key).cipher}}else{if(this.keys[keyId]){if(!key)key=keyId;message=this.encrypt(message,key)}}message={route:"decryptRoute",args:[message,keyId]};return message};this.decryptRoute=(message,keyId)=>{let decryptedMessage=message;if(typeof message==="object"){if(!keyId){if(typeof message.keyId==="string")keyId=message.keyId}if(keyId){let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=import_sjcl.default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message.args,key)}}}else{let key;if(this.securedKeys&&this.secret&&this.encryptedkeys){let decrypted=JSON.parse(import_sjcl.default.decrypt(this.secret,this.encryptedkeys));if(decrypted[keyId]?.key){decryptedMessage=import_sjcl.default.decrypt(this.secret,decrypted[keyId].key);return decryptedMessage}}else{if(this.keys[keyId])key=this.keys[keyId].key;if(key)decryptedMessage=this.decrypt(message,key)}}return decryptedMessage};this.transmit=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.encryptRoute(message,keyId);return this.handleServiceMessage(message)};this.receive=(message,keyId)=>{if(!keyId){keyId=Object.keys(this.keys)[0]}message=this.decryptRoute(message,keyId);if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(typeof message.method==="string"){return this.handleMethod(message.route,message.method,message.args)}else if(typeof message.route==="string"){return this.handleServiceMessage(message)}else if(typeof message.node==="string"||message.node instanceof GraphNode){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}}else return message};if(keys){if(secureKeys&&secret){this.securedKeys=true;this.encryptedkeys=import_sjcl.default.encrypt(secret,JSON.stringify(keys)).cipher;this.secret=secret}else Object.assign(this.keys,keys)}this.setTree(this)}static generateSecret(){return import_sjcl.default.codec.base64.fromBits(import_sjcl.default.random.randomWords(8,10))}encrypt(message,key){message=import_sjcl.default.encrypt(key,message).cipher;return message}decrypt(message,key){message=import_sjcl.default.decrypt(key,message);return message}};var http=__toESM(require("http"));var https=__toESM(require("https"));var fs=__toESM(require("fs"));var path=__toESM(require("path"));var HTTPbackend=class extends Service{constructor(options,settings){super(options);this.name="http";this.debug=false;this.servers={};this.mimeTypes={".html":"text/html",".htm":"text/html",".js":"text/javascript",".css":"text/css",".json":"application/json",".txt":"text/plain",".png":"image/png",".jpg":"image/jpg",".jpeg":"image/jpg",".gif":"image/gif",".svg":"image/svg+xml",".xhtml":"application/xhtml+xml",".bmp":"image/bmp",".wav":"audio/wav",".mp3":"audio/mpeg",".mp4":"video/mp4",".xml":"application/xml",".webm":"video/webm",".webp":"image/webp",".weba":"audio/webm",".woff":"font/woff","woff2":"font/woff2",".ttf":"application/font-ttf",".eot":"application/vnd.ms-fontobject",".otf":"application/font-otf",".wasm":"application/wasm",".zip":"application/zip",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".tif":"image/tiff",".sh":"application/x-sh",".csh":"application/x-csh",".rar":"application/vnd.rar",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".odt":"application/vnd.oasis.opendocument.text",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odp":"application/vnd.oasis.opendocument.presentation",".mpeg":"video/mpeg",".mjs":"text/javascript",".cjs":"text/javascript",".jsonld":"application/ld+json",".jar":"application/java-archive",".ico":"image/vnd.microsoft.icon",".gz":"application/gzip","epub":"application/epub+zip",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".csv":"text/csv",".avi":"video/x-msvideo",".aac":"audio/aac",".mpkg":"application/vnd.apple.installer+xml",".oga":"audio/ogg",".ogv":"video/ogg","ogx":"application/ogg",".php":"application/x-httpd-php",".rtf":"application/rtf",".swf":"application/x-shockwave-flash",".7z":"application/x-7z-compressed",".3gp":"video/3gpp"};this.onStarted=(protocol,host,port)=>{console.log(`\u{1F431} Node server running at + ${protocol}://${host}:${port}/`)};this.setupServer=(options={protocol:"http",host:"localhost",port:8080,startpage:"index.html"},requestListener,onStarted)=>{if(options.pages){for(const key in options.pages){if(typeof options.pages[key]==="string"){this.addPage(`${options.port}/${key}`,options.pages[key])}else if(typeof options.pages[key]==="object"){if(options.pages[key].template){options.pages[key].get=options.pages[key].template}if(key!=="_all")this.setTree({[`${options.port}/${key}`]:options.pages[key]})}}}if(options.protocol==="https"){return this.setupHTTPSserver(options,requestListener,onStarted)}else return this.setupHTTPserver(options,requestListener,onStarted)};this.open=this.setupServer;this.setupHTTPserver=(options={host:"localhost",port:8080,startpage:"index.html",errpage:void 0},requestListener,onStarted=()=>{this.onStarted("http",options.host,options.port)})=>{const host=options.host;const port=options.port;options.protocol="http";if(!host||!port)return;const address=`${host}:${port}`;if(this.servers[address])this.terminate(this.servers[address]);if(!("keepState"in options))options.keepState=true;const served={server:void 0,type:"httpserver",address,...options};if(!requestListener)requestListener=(request,response)=>{let received={args:{request,response},method:request.method,served};let url=request.url.slice(1);if(!url)url="/";if(options.pages){if(typeof options.pages[url]==="object"){if(options.pages[url].onrequest){if(typeof options.pages[url].onrequest==="string"){options.pages[url].onrequest=this.__node.nodes.get(url.onrequest)}if(typeof options.pages[url].onrequest==="object"){if(options.pages[url].onrequest.__operator){options.pages[url].onrequest.__operator(options.pages[url],request,response)}}else if(typeof options.pages[url].onrequest==="function"){options.pages[url].onrequest(this,this.__node.nodes.get(options.port+"/"+url),request,response)}}if(options.pages[url].redirect){url=options.pages[url].redirect;received.redirect=url}}}received.route=url;this.receive(received)};const server=http.createServer(requestListener);served.server=server;served.terminate=()=>{this.terminate(served)};served.service=this;this.servers[address]=served;served._id=options._id?options._id:address;return new Promise((resolve,reject)=>{server.on("error",err=>{console.error("Server error:",err.toString());reject(err)});server.listen(port,host,()=>{onStarted();if(served.onopen)served.onopen(served);resolve(served)})})};this.setupHTTPSserver=(options={host:"localhost",port:8080,startpage:"index.html",certpath:"cert.pem",keypath:"key.pem",passphrase:"encryption",errpage:void 0},requestListener,onStarted=()=>{this.onStarted("https",options.host,options.port)})=>{const host=options.host;const port=options.port;options.protocol="https";if(!host||!port||!options.certpath||!options.keypath)return;if(this.servers[`${host}:${port}`])this.terminate(this.servers[`${host}:${port}`]);var opts={key:fs.readFileSync(options.keypath),cert:fs.readFileSync(options.certpath),passphrase:options.passphrase};if(!("keepState"in options))options.keepState=true;const address=`${host}:${port}`;const served={server:void 0,type:"httpserver",address,...options};if(!requestListener)requestListener=(request,response)=>{let received={args:{request,response},method:request.method,served};let url=request.url.slice(1);if(!url)url="/";if(options.pages){if(typeof options.pages[url]==="object"){if(options.pages[url].redirect){url=options.pages[url].redirect;received.redirect=url}if(options.pages[url].onrequest){if(typeof options.pages[url].onrequest==="string"){options.pages[url].onrequest=this.__node.nodes.get(options.pages[url].onrequest)}if(typeof options.pages[url].onrequest==="object"){if(options.pages[url].onrequest.__operator){options.pages[url].onrequest.__operator(options.pages[url],request,response)}}else if(typeof options.pages[url].onrequest==="function"){options.pages[url].onrequest(this,options.pages[url],request,response)}}}}received.route=url;this.receive(received)};const server=https.createServer(opts,requestListener);served.server=server;served.terminate=()=>{this.terminate(served)};served.service=this;this.servers[address]=served;served._id=options._id?options._id:address;return new Promise((resolve,reject)=>{server.on("error",err=>{console.error("Server error:",err.toString());reject(err)});server.listen(port,host,()=>{onStarted();if(served.onopen)served.onopen(served);resolve(served)})})};this.transmit=(message,options,ondata,onend)=>{let input=message;if(typeof input==="object")input=JSON.stringify(input);if(typeof options==="string"&&message)return this.POST(options,message);else if(typeof options==="string")return this.GET(options);if(!options){let server=this.servers[Object.keys(this.servers)[0]];options={protocol:server.protocol,host:server.host,port:server.port,method:"POST",path:message.route,headers:{"Content-Type":"application/json","Content-Length":input.length}}}else if(!options.headers){options.headers={"Content-Type":"application/json","Content-Length":input.length}}return this.request(options,input,ondata,onend)};this.withResult=(response,result,message)=>{if(result&&!response.writableEnded&&!response.destroyed){let mimeType="text/plain";if(typeof result==="string"){let extname2=path.extname(result);if(extname2&&fs.existsSync(path.join(process.cwd(),result))){mimeType=this.mimeTypes[extname2]||"application/octet-stream";result=fs.readFileSync(path.join(process.cwd(),result));if(mimeType==="text/html"&&(message.served?.pages?._all||message.served?.pages?.[message.route])){result=this.injectPageCode(result.toString(),message.route,message.served)}}if(typeof result==="string"&&result.includes("<")&&result.includes(">")&&result.indexOf("<")")){if(message?.served?.pages?._all||message?.served?.pages?.[message.route]){result=this.injectPageCode(result,message.route,message.served)}response.writeHead(200,{"Content-Type":"text/html"});response.end(result,"utf-8");return}}else if(typeof result==="object"){result=JSON.stringify(result);mimeType="application/json"}response.writeHead(200,{"Content-Type":mimeType});response.end(result,"utf-8")}};this.injectPageCode=(templateString,url,served)=>{if(served?.pages?.[url]?.inject){if(typeof served.pages[url].inject==="object")templateString=this.buildPage(served.pages[url].inject,templateString);else if(typeof served.pages[url].inject==="function")templateString+=served.pages[url].inject();else if(typeof served.pages[url].inject==="string"||typeof served.pages[url].inject==="number")templateString+=served.pages[url].inject}if(served?.pages?._all?.inject){if(typeof served.pages._all.inject==="object")templateString=this.buildPage(served.pages._all.inject,templateString);else if(typeof served.pages._all.inject==="function")templateString+=served.pages._all.inject();else if(typeof served.pages._all.inject==="string"||typeof served.pages._all.inject==="number")templateString+=served.pages._all.inject}return templateString};this.receive=message=>{const request=message.args.request;const response=message.args.response;const method=message.method;const served=message.served;if(this.debug)console.log(request.method,request.url);let result=new Promise((resolve,reject)=>{response.on("error",err=>{if(!response.writableEnded||!response.destroyed){response.statusCode=400;response.end(void 0,void 0,()=>{reject(err)})}});let getFailed=()=>{if(response.writableEnded||response.destroyed)reject(requestURL);if(requestURL=="./"||requestURL==served?.startpage){let template=`

Brains@Play Server

`;if(served?.pages?._all||served?.pages?.error){template=this.injectPageCode(template,message.route,served)}response.writeHead(200,{"Content-Type":"text/html"});response.end(template,"utf-8",()=>{resolve(template)});if(served?.keepState)this.setState({[served.address]:template})}else if(this.debug)console.log(`File ${requestURL} does not exist on path!`);response.writeHead(500);response.end(void 0,void 0,()=>{reject(requestURL)})};if(method==="GET"||method==="get"){var requestURL="."+request.url;if(requestURL=="./"&&served?.startpage){requestURL=served.startpage}if((request.url!=="/"||served?.startpage)&&fs.existsSync(path.join(process.cwd(),requestURL))){if(response.writableEnded||response.destroyed)reject(requestURL);fs.readFile(path.join(process.cwd(),requestURL),(error,content)=>{if(error){if(error.code=="ENOENT"){if(served?.errpage){fs.readFile(served.errpage,(er,content2)=>{response.writeHead(404,{"Content-Type":"text/html"});if(served.pages?._all||served.pages?.error){content2=this.injectPageCode(content2.toString(),message.route,served)}response.end(content2,"utf-8");reject(content2)})}else{response.writeHead(404,{"Content-Type":"text/html"});let content2=`

Error: ${error.code}

`;if(served?.pages?._all||served?.pages?.[message.route]){content2=this.injectPageCode(content2.toString(),message.route,served)}response.end(content2,"utf-8",()=>{reject(error.code)})}}else{response.writeHead(500);response.end("Something went wrong: "+error.code+" ..\n","utf-8",()=>{reject(error.code)})}}else{var extname2=String(path.extname(requestURL)).toLowerCase();var contentType=this.mimeTypes[extname2]||"application/octet-stream";if(contentType==="text/html"&&(served?.pages?._all||served?.pages?.[message.route])){content=this.injectPageCode(content.toString(),message.route,served)}response.writeHead(200,{"Content-Type":contentType});response.end(content,"utf-8",()=>{resolve(content)})}})}else if(message.route){let route;if(served){let rt=`${served.port}/${message.route}`;if(this.__node.nodes.get(rt))route=rt}if(!route&&this.__node.nodes.get(message.route))route=message.route;if(route){let res;if(message.method){res=this.handleMethod(route,message.method,void 0)}else if(message.node){res=this.handleGraphNodeCall(message.node,void 0)}else res=this.handleServiceMessage({route,args:void 0,method:message.method});if(res instanceof Promise)res.then(r=>{if(served?.keepState)this.setState({[served.address]:res});this.withResult(response,r,message);resolve(res)});else if(res){if(served?.keepState)this.setState({[served.address]:res});this.withResult(response,res,message);resolve(res)}}else if(message.redirect){response.writeHead(301,{"Location":message.redirect});response.end();resolve(true)}else getFailed()}else getFailed()}else{let body=[];request.on("data",chunk=>{body.push(chunk)}).on("end",()=>{body=Buffer.concat(body).toString();if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}let route,method2,args;if(body?.route){route=this.__node.tree[body.route];method2=body.method;args=body.args;if(!route){if(typeof body.route==="string"){if(body.route.includes("/")&&body.route.length>1)body.route=body.route.split("/").pop()}route=this.__node.tree[body.route]}}if(!route){if(message?.route){let route2=this.__node.tree[message.route];method2=message.method;args=message.args;if(!route2){if(typeof message.route==="string"){if(message.route.includes("/")&&message.route.length>1)message.route=message.route.split("/").pop()}route2=this.__node.tree[message.route]}}}let res=body;if(route){if(body.method){res=this.handleMethod(route,method2,args)}else if(body.node){res=this.handleGraphNodeCall(body.node,body.args)}else res=this.handleServiceMessage({route,args,method:method2});if(res instanceof Promise){res.then(r=>{this.withResult(response,r,message);if(served?.keepState)this.setState({[served.address]:res});resolve(res)})}else{this.withResult(response,res,message);if(served?.keepState)this.setState({[served.address]:res});resolve(res)}}else if(!response.writableEnded||!response.destroyed){response.statusCode=200;response.end(void 0,void 0,()=>{resolve(res)})}else resolve(res)})}}).catch(er=>{console.error("Request Error:",er)});return result};this.request=(options,send,ondata,onend)=>{let client=http;if(options.protocol?.includes("https")){client=https}delete options.protocol;const req=client.request(options,res=>{if(ondata)res.on("data",ondata);if(onend)res.on("end",onend)});if(options.headers){for(const head in options.headers){req.setHeader(head,options.headers[head])}}if(send)req.write(send);req.end();return req};this.POST=(url,data,headers)=>{let urlstring=url;if(urlstring instanceof URL)urlstring=url.toString();let protocol=urlstring.startsWith("https")?"https":"http";let host,port,path3;let split=urlstring.split("/");split.forEach(s=>{if(s.includes(":")){let ss=s.split(":");host=ss[0];port=ss[1]}});if(split.length>3){path3=split.slice(3).join("/")}let req=this.request({protocol,host,port,path:path3,method:"POST",headers},data);return req};this.GET=url=>{return new Promise((resolve,reject)=>{let client=http;let urlstring=url;if(url instanceof URL)urlstring=url.toString();if(urlstring.includes("https")){client=https}client.get(url,resp=>{let chunks=[];resp.on("data",chunk=>{chunks.push(chunk)});resp.on("end",()=>{resolve(Buffer.concat(chunks))})}).on("error",err=>{reject(err)})})};this.terminate=served=>{if(typeof served==="string")served=this.servers[served];if(typeof served==="object"){served.server.close();if(served.onclose)served.onclose(served)}};this.addPage=(path3,template)=>{if(typeof template==="string"){if(!template.includes(""+template+""}if(typeof this.__node.tree[path3]==="object"){this.__node.tree[path3].get=template;this.__node.nodes.get(path3).get=template}else this.setTree({[path3]:{get:template}})};this.addHTML=(path3,template)=>{if(typeof template==="string"){if(!template.includes("<")||!template.includes(">"))template="
"+template+"
"}if(typeof this.__node.tree[path3]==="object"){this.__node.tree[path3].get=template;this.__node.nodes.get(path3).get=template}else this.setTree({[path3]:{get:template}})};this.buildPage=(pageStructure,baseTemplate)=>{let result=``;if(baseTemplate)result+=baseTemplate;let appendTemplate=(obj,r,res)=>{if(typeof obj[r]==="object"){for(const key in obj){appendTemplate(obj,key,res)}}else if(this.__node.tree[r]?.get){let toAdd=this.__node.tree[r]?.get;if(typeof toAdd==="function")toAdd=toAdd(obj[r]);if(typeof toAdd==="string"){let lastDiv=res.lastIndexOf("<");if(lastDiv>0){let end=res.substring(lastDiv);res=res.substring(0,lastDiv)+toAdd+end}res+=toAdd}}else if(typeof this.__node.tree[r]==="function"||this.__node.tree[r]?.__operator){let routeresult;if(this.__node.tree[r]?.__operator)routeresult=this.__node.tree[r].__operator(obj[r]);else routeresult=this.__node.tree[r](obj[r]);if(typeof routeresult==="string"){let lastDiv=res.lastIndexOf("<");if(lastDiv>0){let end=res.substring(lastDiv);res=res.substring(0,lastDiv)+routeresult+end}else res+=routeresult}}else if(typeof this.__node.tree[r]==="string")res+=this.__node.tree[r];return res};if(Array.isArray(pageStructure)){pageStructure.forEach(r=>{result=appendTemplate(pageStructure,r,result)})}else if(typeof pageStructure==="object"){for(const r in pageStructure){result=appendTemplate(pageStructure,r,result)}}else if(typeof pageStructure==="string")result+=pageStructure;else if(typeof pageStructure==="function")result+=pageStructure();return result};this.hotreload=(socketURL=`http://localhost:8080/wss`)=>{if(socketURL instanceof URL)socketURL=socketURL.toString();const HotReloadClient=(url=`http://localhost:8080/wss`)=>{let socket=new WebSocket(url);socket.addEventListener("close",()=>{const interAttemptTimeoutMilliseconds=100;const maxDisconnectedTimeMilliseconds=3e3;const maxAttempts=Math.round(maxDisconnectedTimeMilliseconds/interAttemptTimeoutMilliseconds);let attempts=0;const reloadIfCanConnect=()=>{attempts++;if(attempts>maxAttempts){console.error("Could not reconnect to dev server.");return}socket=new WebSocket(url);socket.onerror=er=>{console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`)};socket.addEventListener("error",()=>{setTimeout(reloadIfCanConnect,interAttemptTimeoutMilliseconds)});socket.addEventListener("open",()=>{location.reload()})};reloadIfCanConnect()})};return` - `};pwa=(pwaName="PWA",cacheExpirationDays=4/24,serviceWorkerUrl="service-worker.js")=>{if(!fs.existsSync(serviceWorkerUrl)){fs.writeFileSync(path.join(process.cwd(),serviceWorkerUrl),defaultServiceWorker(cacheExpirationDays))}if(!fs.existsSync("manifest.webmanifest")){fs.writeFileSync(path.join(process.cwd(),"/manifest.webmanifest"),defaultManifest(pwaName))}function ServiceWorkerInstaller(serviceWorkerUrl2){if(!Array.from(document.head.querySelectorAll("link")).find(elm=>{if(elm.href.includes("manifest"))return true})){document.head.insertAdjacentHTML("beforeend",``)}const isLocalhost=Boolean(window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/));function registerSW(){navigator.serviceWorker.register(serviceWorkerUrl2).then(registration=>{registration.onupdatefound=()=>{const installingWorker=registration.installing;if(installingWorker==null){return}installingWorker.onstatechange=()=>{if(installingWorker.state==="installed"){if(navigator.serviceWorker.controller){console.log("New content is available and will be used when all tabs for this page are closed.")}else{console.log("Content is cached for offline use.")}}}}}).catch(error=>{console.error("Error during service worker registration:",error)})}if("serviceWorker"in navigator)addEventListener("load",()=>{if(isLocalhost){fetch(serviceWorkerUrl2).then(response=>{const contentType=response.headers.get("content-type");if(response.status===404||contentType!=null&&contentType.indexOf("javascript")===-1){navigator.serviceWorker.ready.then(registration=>{registration.unregister().then(()=>{window.location.reload()})})}else{registerSW()}}).catch(()=>{console.log("No internet connection found. App is running in offline mode.")});navigator.serviceWorker.ready.then(()=>{console.log("This web app is being served cache-first by a service worker.")})}else{registerSW()}})}return` - - `}};function getPageOptions(url,received,pages,request,response,port){let pageOptions=pages[url];let key=url;if(!pageOptions){let url2="/"+url;pageOptions=pages[url2];key=url2;if(!pageOptions&&!path.extname(url)){let split=url.split("/");key=split[0]+"/*";if(pages[key]){pageOptions=pages[key];received.route=key;request.url=key}else{let spl=url2.split("/");spl[spl.length-1]="";key=spl.join("/")+"*";if(pages[key]){pageOptions=pages[key];received.route=key;request.url=key}}}else{received.route=url2;request.url=url2}}else{received.route=url;request.url=url}if(typeof pageOptions==="object"){if(pageOptions.redirect){url=pageOptions.redirect;received.redirect=url;received.route=url}if(pageOptions.onrequest){if(typeof pageOptions.onrequest==="string"){pageOptions.onrequest=this.__node.nodes.get(pageOptions.onrequest)}if(typeof pageOptions.onrequest==="object"){if(pageOptions.onrequest.__operator){pageOptions.onrequest.__operator(pageOptions,request,response)}}else if(typeof pageOptions.onrequest==="function"){pageOptions.onrequest(this,this.__node.nodes.get(`${port}/${key}`),request,response)}}}return pageOptions}function getHoursAndMinutes(date){let hours=date.getHours();let minutes=date.getMinutes();hours=hours<10?"0"+hours:hours;minutes=minutes<10?"0"+minutes:minutes;return`${hours}:${minutes}`}var import_better_sse=__toESM(require_build());var SSEbackend=class extends Service{name="sse";debug=false;servers={};eventsources={};connections={servers:this.servers,eventsources:this.eventsources};constructor(options){super(options);this.load(this)}openSSE=options=>{const server=options.server;let path3=options.path;if(this.servers[path3]){return false}const channel=(0,import_better_sse.createChannel)();let sse={type:"sse",channel,sessions:{},requests:{},...options};this.servers[path3]=sse;sse._id=options._id?options._id:path3;const send=(message,eventName,sessionId)=>{return this.transmit(message,path3,eventName,sessionId)};const terminate=()=>{return this.terminate(path3)};let request=(message,method,sessionId,eventName)=>{if(!sessionId){let promises=[];for(const key in sse.sessions){promises.push(this.request(message,path3,key,eventName))}return promises}return this.request(message,path3,method,sessionId,eventName)};let post=(route,args,method,sessionId,eventName)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,path3,eventName,sessionId)};let run=(route,args,method,sessionId,eventName)=>{let r={route,args};if(!sessionId){let promises=[];for(const key in sse.sessions){promises.push(this.request(r,path3,key,eventName))}return promises}return this.request(r,path3,method,sessionId,eventName)};let subscribe=(route,callback,args,key,subInput,sessionId,eventName)=>{return this.subscribeToSSE(route,options.url,callback,args,key,subInput,sessionId,eventName)};let unsubscribe=(route,sub,sessionId,eventName)=>{return run("unsubscribe",[route,sub],void 0,sessionId,eventName)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;let onRequest=(req,response)=>{if(req.url?.includes(path3)){if(req.method==="GET"){if(this.debug)console.log("SSE Request",path3);(0,import_better_sse.createSession)(req,response).then(session=>{channel.register(session);let _id=`sse${Math.floor(Math.random()*1e15)}`;sse.sessions[_id]=session;this.eventsources[_id]={_id,session,served:sse,send:(message,eventName)=>{return send(message,eventName,_id)},request:(message,method,eventName)=>{return request(message,method,_id,eventName)},post:(route,args,method,eventName)=>{return post(route,args,method,_id,eventName)},run:(route,args,method,eventName)=>{return run(route,args,method,_id,eventName)},subscribe:(route,callback)=>{return subscribe(route,callback,void 0,_id)},unsubscribe:(route,sub,eventName)=>{return unsubscribe(route,sub,_id,eventName)},terminate:()=>{delete this.eventsources[_id];delete sse.sessions[_id];return true},onclose:(session2,sse2,_id2,req2,res)=>{if(sse2.onconnectionclose)sse2.onconnectionclose(session2,sse2,_id2,req2,res)},graph:this};session.push(JSON.stringify({route:"setId",args:_id}));session.on("close",()=>{let obj=this.eventsources[_id];let onclose=obj.onclose;delete this.eventsources[_id];if(onclose)obj.onclose(session,sse,_id,req,response)});if(sse.onconnection){sse.onconnection(session,sse,_id,req,response)}})}else{let body=[];req.on("data",chunk=>{body.push(chunk)}).on("end",()=>{body=Buffer.concat(body).toString();if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}let route,method,args,callbackId;if(body?.route||body?.callbackId){method=body.method;args=body.args;callbackId=body.callbackId;if(typeof body.route==="string"){if(body.route.includes("/")&&body.route.length>1)body.route=body.route.split("/").pop();route=this.__node.roots?.[body.route]}}if(route){let res=this.receive({route,args,method})}else if(callbackId&&sse.requests[callbackId]){sse.requests[callbackId](args)}if(this.__node.keepState)this.setState({[path3]:body})})}}};let requestListeners=server.listeners("request");server.removeAllListeners("request");const otherListeners=(req,res)=>{requestListeners.forEach(l=>{l(req,res)})};const sseListener=(req,res)=>{if(req.url)if(req.url.indexOf(path3)>-1){if(!this.servers[path3]){server.removeListener("request",sseListener);server.addListener("request",otherListeners)}onRequest(req,res)}else otherListeners(req,res)};server.addListener("request",sseListener);server.addListener("close",()=>{if(sse.onclose)sse.onclose(sse)});return sse};open=this.openSSE;streamIterable=(path3,iterable,sessionId,eventName="message")=>{let server=this.servers[path3];if(server){if(sessionId){if(server.sessions[sessionId]){return server.sessions[sessionId].iterate(iterable,{eventName})}}else{let promises=[];for(const key in server.sessions){promises.push(server.sessions[key].iterate(iterable))}return promises}}};streamReadable=(path3,readable,sessionId,eventName="message")=>{let server=this.servers[path3];if(server){if(sessionId){if(server.sessions[sessionId]){return server.sessions[sessionId].stream(readable,{eventName})}}else{let promises=[];for(const key in server.sessions){promises.push(server.sessions[key].stream(readable))}return promises}}};transmit=(data,path3,eventName,sessionId)=>{if(!path3&&(typeof data==="object"&&!data.byteLength||typeof data==="number")){if(data?.route){let keys=Object.keys(this.servers);if(keys.length>0){let evs=this.servers[keys[0]];if(evs.channels?.includes(data.route)){path3=evs.path;eventName=data.route}}if(!path3&&data.route){if(this.servers[data.route])path3=data.route}}data=JSON.stringify(data)}if(!path3)path3=Object.keys(this.servers)[0];if(path3&&this.servers[path3]){if(sessionId){if(this.servers[path3].sessions[sessionId]?.isConnected){this.servers[path3].sessions[sessionId].push(data,eventName)}else if(this.servers[path3].sessions[sessionId]){delete this.servers[path3].sessions[sessionId];return false}}else this.servers[path3].channel.broadcast(data,eventName);return true}return false};request=(message,path3,method,sessionId,eventName)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,path3,callbackId,sessionId]};if(method)req.method=method;let sse=this.servers[path3];let callback=result=>{res(result)};sse.requests[callbackId]=callback;if(sse){if(sessionId){if(sse.sessions[sessionId])sse.sessions[sessionId].push(JSON.stringify(req),eventName)}else sse.channel.broadcast(JSON.stringify(req),eventName)}})};runRequest=(message,path3,callbackId,sessionId)=>{let res=this.receive(message);if(path3){let sse=this.servers[path3];if(sse){if(res instanceof Promise){res.then(r=>{if(sessionId){if(sse.sessions[sessionId]){sse.sessions[sessionId].push(JSON.stringify({args:r,callbackId}))}}else{sse.channel.broadcast(JSON.stringify({args:r,callbackId}))}})}else{if(sessionId){if(sse.sessions[sessionId]){sse.sessions[sessionId].push(JSON.stringify({args:res,callbackId}))}}else sse.channel.broadcast(JSON.stringify({args:res,callbackId}))}}}return res};subscribeSSE=(route,path3,args,key,subInput,sessionId,eventName)=>{if(this.restrict?.[route])return void 0;if(this.servers[path3]){return this.subscribe(route,res=>{this.servers[path3].send({args:res,callbackId:route},eventName,sessionId)},args,key,subInput)}};subscribeToSSE=(route,path3,callback,args,key,subInput,sessionId,eventName)=>{if(this.servers[path3]){this.__node.state.subscribeEvent(path3,res=>{if(res?.callbackId===route){if(!callback)this.setState({[path3]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});if(sessionId){if(this.servers[path3].sessions[sessionId]){return this.eventsources[sessionId].run("subscribeSSE",{route:"subscribeSSE",args:[route,path3,args,key,subInput]},void 0,eventName)}}else{let promises=[];for(const k in this.servers[path3].sessions){promises.push(this.eventsources[k].run("subscribeSSE",{route:"subscribeSSE",args:[route,path3,args,key,subInput]},void 0,eventName))}return promises}}};terminate=sse=>{if(typeof sse==="object")delete this.servers[sse.path];else if(typeof sse==="string"){delete this.servers[sse];delete this.eventsources[sse]}return true}};var import_stream=__toESM(require_stream(),1);var import_receiver=__toESM(require_receiver(),1);var import_sender=__toESM(require_sender(),1);var import_websocket=__toESM(require_websocket(),1);var import_websocket_server=__toESM(require_websocket_server(),1);var wrapper_default=import_websocket.default;var WSSbackend=class extends Service{name="wss";debug=false;servers={};sockets={};connections={servers:this.servers,sockets:this.sockets};constructor(options){super(options);this.load(this)}open=options=>{if(options?.server){return this.setupWSS(options)}else return this.openWS(options)};setupWSS=options=>{let port=options.port;let path3=options.path;const server=typeof options.server==="object"?options.server:void 0;let host=options.host;delete options.server;if(!("keepState"in options))options.keepState=true;let opts={};if(options.noServer)opts.noServer=true;else if(port){if(port)opts.port=port}else if(server)opts.server=server;if(options.perMessageDeflate)opts.perMessageDeflate=options.perMessageDeflate;if(typeof options.serverOptions)Object.assign(opts,options.serverOptions);const wss=new import_websocket_server.default(opts);let address="";if(!host&&server){let addr=server.address();if(!port)port=addr.port;address=addr.address}else if(host)address=host;if(port)address+=":"+port;if(path3){if(!path3.startsWith("/"))path3="/"+path3;address+=path3}this.servers[address]={type:"wss",wss,clients:{},address,...options};if(!options.onmessage)options.onmessage=data=>{if(data instanceof Buffer)data=data.toString();if(options.debug){console.log(data)}const result=this.receive(data,wss,this.servers[address]);if(options.keepState)this.setState({[address]:result})};wss.addListener("connection",(ws,request2)=>{if(this.debug)console.log(`New socket connection on ${address}`);let clientId=`socket${Math.floor(Math.random()*1e12)}`;this.servers[address].clients[clientId]=ws;ws.send(JSON.stringify({route:"setId",args:clientId}));this.openWS({socket:ws,address:clientId,_id:clientId,debug:options.debug,onclose:(code,reason)=>{if(this.servers[address].onconnectionclosed)this.servers[address].onconnectionclosed(code,reason,ws,this.servers[address],clientId);delete this.servers[address].clients[clientId]}});if(options.debug){let time=getHoursAndMinutes2(new Date);console.log(time," | ",clientId," | Number of live sockets: ",Object.keys(this.servers[address].clients).length)}if(this.servers[address].onconnection)this.servers[address].onconnection(ws,request2,this.servers[address],clientId)});wss.on("error",err=>{if(this.debug)console.log("Socket Error:",err);if(this.servers[address].onerror)this.servers[address].onerror(err,wss,this.servers[address]);else console.error(err)});let onUpgrade=(request2,socket,head)=>{if(request2.headers&&request2.url){if(this.debug)console.log("Upgrade request at: ",request2.url);let pass=false;if(path3&&request2.url===path3)pass=true;else{let addr=request2.headers.host.split(":")[0];if(port)addr+=":"+port;if(addr===address)pass=true;else{addr+=request2.url.split("?")[0];if(addr===address)pass=true}}if(pass&&this.servers[address]){this.servers[address].wss.handleUpgrade(request2,socket,head,ws=>{if(this.servers[address].onupgrade)this.servers[address].onupgrade(ws,this.servers[address],request2,socket,head);this.servers[address].wss.emit("connection",ws,request2)})}}};if(server)server.addListener("upgrade",onUpgrade);wss.addListener("close",()=>{if(server)server.removeListener("upgrade",onUpgrade);if(this.servers[address].onclose)this.servers[address].onclose(wss,this.servers[address]);else console.log(`wss closed: ${address}`);delete this.servers[address]});let send=(message,socketId)=>{if(typeof message==="object")message=JSON.stringify(message);if(!socketId){for(const key in this.servers[address].clients){this.sockets[key].send(message)}}else return this.sockets[socketId].send(message)};let request=(message,method,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].request(message,method))}return promises}else return this.sockets[socketId].request(message,method)};let post=(route,args,method,socketId)=>{if(!socketId){for(const key in this.servers[address].clients){this.sockets[key].post(route,args,method)}}else return this.sockets[socketId].post(route,args,method)};let run=(route,args,method,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].run(route,args,method))}return promises}else return this.sockets[socketId].run(route,args,method)};let subscribe=(route,callback,socketId,args,key,subInput)=>{if(!socketId){let promises=[];for(const k in this.servers[address].clients){promises.push(this.sockets[k].subscribe(route,callback,args,key,subInput))}return promises}else this.sockets[socketId].subscribe(route,callback,args,key,subInput)};let unsubscribe=(route,sub,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].unsubscribe(route,sub))}return promises}else this.sockets[socketId].unsubscribe(route,sub)};let terminate=socketId=>{if(socketId)return this.terminate(socketId);else return this.terminate(address)};this.servers[address].send=send;this.servers[address].request=request;this.servers[address].post=post;this.servers[address].run=run;this.servers[address].subscribe=subscribe;this.servers[address].unsubscribe=unsubscribe;this.servers[address].terminate=terminate;this.servers[address].graph=this;this.servers[address]._id=options._id?options._id:address;return this.servers[address]};openWS=options=>{if(!options.address){let protocol=options.protocol;if(!protocol)protocol="wss";options.address=`${protocol}://${options.host}`;if(options.port)options.address+=":"+options.port;if(!options.path||options.path?.startsWith("/"))options.address+="/";if(options.path)options.address+=options.path}const address=options.address;let socket;if(options.socket)socket=options.socket;else socket=new wrapper_default(address);if(!("keepState"in options))options.keepState=true;if(options.onmessage){socket.on("message",data=>{this.sockets[address].onmessage(data,socket,this.sockets[address])})}else if(options._id){socket.addListener("message",data=>{if(ArrayBuffer.isView(data))data=data.toString();if(options.debug){console.log("Message from ",options._id,": ",data)}this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}})}else{let socketonmessage=data=>{if(ArrayBuffer.isView(data))data=data.toString();if(data){if(options.debug){console.log("Message from ",address,": ",data)}if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;socket.removeEventListener("message",socketonmessage);socket.on("message",data2=>{if(ArrayBuffer.isView(data2))data2=data2.toString();if(options.debug){console.log("Message from ",this.sockets[address]._id,": ",data2)}this.receive(data2,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data2})}})}}}}this.receive(data,socket,this.sockets[address]);if(options.keepState)this.setState({[address]:data})};socket.addListener("message",socketonmessage);options.onmessage=socketonmessage}socket.addListener("open",()=>{if(this.sockets[address].onopen)this.sockets[address].onopen(socket,this.sockets[address])});socket.addListener("close",(code,reason)=>{let obj=this.sockets[address];let onclose=obj.onclose;delete this.sockets[address];if(onclose)onclose(code,reason,socket,obj)});socket.on("error",er=>{if(this.sockets[address].onerror)this.sockets[address].onerror(er,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},this.sockets[address]._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{let data=ev.data;if(typeof data==="string"&&data.indexOf("{")>-1)data=JSON.parse(data);if(typeof data==="object"){if(data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return this.request(message,socket,this.sockets[address]._id,method)};let subscribe=(route,callback)=>{return this.subscribeToSocket(route,this.sockets[address]._id,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{this.terminate(this.sockets[address]._id)};this.sockets[address]={type:"socket",socket,send,post,request,run,subscribe,unsubscribe,terminate,graph:this,__node:{tag:address},...options};return this.sockets[address]};transmit=(message,ws)=>{if(typeof message==="object"&&(message?.route||message?.node||typeof message.arrayBuffer!=="function"&&typeof message.byteLength!=="number"&&typeof message[0]?.byteLength!=="number")||typeof message==="number")message=JSON.stringify(message);if(!ws){let served=this.servers[Object.keys(this.servers)[0]];if(served)ws=served.wss;else{let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket};}if(ws instanceof import_websocket_server.default){ws.clients.forEach(c=>{c.send(message)})}else if(ws instanceof wrapper_default)ws.send(message)};closeWS=ws=>{if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}else if(typeof ws==="string"){for(const k in this.sockets){if(k.includes(ws)){ws=this.sockets[k].socket;delete this.sockets[k];break}}}if(ws instanceof wrapper_default){if(ws.readyState===ws.OPEN)ws.close()}return true};terminate=ws=>{let str;if(!ws){let served=Object.keys(this.servers);for(const key in served){this.terminate(key)}let sockets=Object.keys(this.sockets);for(const key in sockets){this.terminate(key)}}else if(typeof ws==="string"){str=ws;for(const k in this.servers){if(k.includes(ws)||this.servers[k]._id===ws){ws=this.servers[k].wss;for(const key in this.servers[k].clients){this.closeWS(this.servers[k].clients[key])}delete this.servers[k];break}}if(!ws){for(const k in this.sockets){if(k.includes(ws)||this.sockets[k]._id===ws){ws=this.sockets[k].socket;delete this.sockets[k];break}}}}if(ws instanceof import_websocket_server.default){ws.close(er=>{if(er)console.error(er)})}else if(ws instanceof wrapper_default){if(ws.readyState===ws.OPEN)ws.close();if(this.get(str?str:ws.url))this.remove(str?str:ws.url)}return true};request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(ws){if(typeof ws==="string"){for(const key in this.servers){for(const c in this.servers[key].clients){if(c===ws){ws=this.servers[key].clients[c];break}}}if(!(ws instanceof wrapper_default)){for(const s in this.sockets){if(s===ws){ws=this.sockets[s].socket;break}}}}if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof wrapper_default)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof wrapper_default)ws.send(JSON.stringify(res))}}return res};subscribeSocket=(route,socket,args,key,subInput)=>{if(this.restrict?.[route])return void 0;if(typeof socket==="string"){if(this.sockets[socket])socket=this.sockets[socket].socket;else{for(const prop in this.servers){if(this.servers[prop].clients[socket])socket=this.servers[prop].clients[socket]}}}if(typeof socket==="object"){return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},args,key,subInput)}};subscribeToSocket=(route,socketId,callback,args,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeEvent(socketId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[socketId]:res.args});else if(typeof callback==="string"){this.setState({[callback]:res.args})}else callback(res.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,args,key,subInput]})}}};function getHoursAndMinutes2(date){let hours=date.getHours();let minutes=date.getMinutes();hours=hours<10?"0"+hours:hours;minutes=minutes<10?"0"+minutes:minutes;return`${hours}:${minutes}`}var import_child_process=require("child_process");var import_path=__toESM(require("path"));var CMDService=class extends Service{processes;connections={processes:void 0};subprocessloader={"process":(node,parent,graph,roots,properties)=>{if(node.command){this.createProcess(node)}}};constructor(options){super(options);this.load(this);this.connections.processes=this.processes;if(process?.stdin){process.stdin.on("data",data=>{let str=data.toString();this.receive(str)})}}createProcess=properties=>{let newprocess=properties;if(!newprocess.command)newprocess.command="node";if(!newprocess.args)newprocess.args=[import_path.default.join(process.cwd(),"node_modules","graphscript-node","services","cmd","childprocess.js")];if(newprocess.command){let p;if(!newprocess.options){newprocess.options={shell:true,stdio:"inherit"}}newprocess.controller=new AbortController;newprocess.options=Object.assign({signal:newprocess.controller.signal,env:process.env,cwd:process.cwd()},newprocess.options);if(newprocess.tag)newprocess._id=newprocess.tag;else{newprocess._id=`process${Math.floor(Math.random()*1e15)}`;newprocess.tag=newprocess._id}if(typeof newprocess.command==="string"){if(newprocess.command.includes(".js")){p=(0,import_child_process.fork)(newprocess.command,newprocess.args,newprocess.options)}else p=(0,import_child_process.spawn)(newprocess.command,newprocess.args?newprocess.args:[],newprocess.options);if(p instanceof import_child_process.ChildProcess){if(p.stderr){if(newprocess.onerror){p.stderr.on("data",newprocess.onerror)}else p.stderr.on("data",console.error)}if(p.stdout){if(newprocess.stdout){p.stdout.on("data",newprocess.stdout)}else p.stdout.on("data",data=>{let str=data.toString();this.receive(str);this.setState({[newprocess._id]:str})})}if(newprocess.onclose){p.on("close",newprocess.onclose)}newprocess.process=p;newprocess.controller=new AbortController;newprocess.send=data=>{return p.send(data)};newprocess.request=(message,method)=>{return this.request(message,newprocess._id,method)};newprocess.post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return p.send(JSON.stringify(message))};newprocess.run=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.request(message,newprocess._id)};newprocess.subscribe=(route,callback,args,key,subInput)=>{return this.subscribeToProcess(route,newprocess._id,callback,args,key,subInput)};newprocess.unsubscribe=(route,sub)=>{return newprocess.run("unsubscribe",[route,sub])};this.processes[newprocess._id]=newprocess}}}return newprocess};open=this.createProcess;abort=childprocess=>{if(childprocess.controller)childprocess.controller.abort();else childprocess.kill();return true};send=(childprocess,data)=>{return childprocess.send(data)};request=(message,processId,method)=>{let childprocess=this.processes[processId].process;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let ondata=data=>{let str=data.toString();if(str.includes("{")){let parsed=JSON.parse(str);if(parsed.callbackId===callbackId){childprocess.removeListener("data",ondata);res(parsed.args)}}};childprocess.addListener("data",ondata);childprocess.send(req)})};runRequest=(message,callbackId,childprocess)=>{let res=this.receive(message);if(typeof childprocess==="string")childprocess=this.processes[childprocess].process;if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(childprocess instanceof import_child_process.ChildProcess)childprocess.send(JSON.stringify(res));else process.stdout.write(JSON.stringify(res))})}else{res={args:res,callbackId};if(childprocess instanceof import_child_process.ChildProcess)childprocess.send(JSON.stringify(res));else process.stdout.write(JSON.stringify(res))}return res};subscribeProcess(route,childprocess,args,key,subInput){if(this.restrict?.[route])return void 0;if(typeof childprocess==="string"&&this.processes[childprocess]){childprocess=this.processes[childprocess].process}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{childprocess.send(JSON.stringify({args:r,callbackId:route}))})}else{childprocess.send(JSON.stringify({args:res,callbackId:route}))}},args,key,subInput)}subscribeToProcess(route,processId,callback,args,key,subInput){if(typeof processId==="string"&&this.processes[processId]){this.__node.state.subscribeEvent(processId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[processId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.processes[processId].request(JSON.stringify({route:"subscribeSocket",args:[route,processId,args,key,subInput]}))}}};var SessionsService=class extends Service{name="sessions";users={};sessions={oneWay:{},shared:{}};invites={};constructor(options,users){super(options);this.setLoaders(loaders);this.load(this);if(users)this.users=users}getSessionInfo=(sessionIdOrName,userId)=>{if(!sessionIdOrName){return this.sessions.shared}else{if(this.sessions.oneWay[sessionIdOrName]){let s=this.sessions.oneWay[sessionIdOrName];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{oneWay:{[sessionIdOrName]:s}}}}else if(this.sessions.shared[sessionIdOrName]){return{shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};openOneWaySession=(options={},sourceUserId,listenerUserId)=>{if(!options._id){options._id=`oneWay${Math.floor(Math.random()*1e15)}`;if(this.sessions.oneWay[options._id]){delete options._id;this.openOneWaySession(options,sourceUserId)}}if(options._id&&sourceUserId&&this.users[sourceUserId]){if(sourceUserId){if(!options.settings)options.settings={listener:sourceUserId,source:sourceUserId,propnames:{latency:true},admins:{[sourceUserId]:true},ownerId:sourceUserId};if(!options.settings.listener)options.settings.listener=listenerUserId?listenerUserId:sourceUserId;if(!options.settings.source)options.settings.source=sourceUserId;if(!this.users[sourceUserId].sessions)this.users[sourceUserId].sessions={};this.users[sourceUserId].sessions[options._id]=options}if(!options.data)options.data={};if(options.onopen)options.onopen(options);if(this.sessions.oneWay[options._id]){return this.updateSession(options,sourceUserId)}else if(options.settings?.listener&&options.settings.source)this.sessions.oneWay[options._id]=options}return options};openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;return this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={oneWay:{},shared:{}};if(!options.settings.name)options.name=options.id;if(options.onopen)options.onopen(options);if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};open=(options,userId)=>{if(options.listener)this.openOneWaySession(options,userId);else this.openSharedSession(options,userId)};updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.oneWay[options._id];if(!session)session=this.sessions.shared[options._id];if(session&&userId){if(session.settings&&(session?.settings.source===userId||session.settings.admins?.[userId]||session.settings.moderators?.[userId]||session.settings.ownerId===userId)){return this.recursivelyAssign(session,options)}}else if(options.settings?.source){return this.openOneWaySession(options,userId)}else return this.openSharedSession(options,userId)}return false};joinSession=(sessionId,userId,options,remoteUser=true)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(!sesh)sesh=this.sessions.oneWay[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;sesh.settings.newUser=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options?.source||options?.listener){sesh=this.openOneWaySession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}else if(options){sesh=this.openSharedSession(options,userId);if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"joinSession",args:[sessionId,userId,sesh]})}return sesh}return false};inviteToSession=(session,userInvited,inviteEndpoint,remoteUser=true)=>{if(remoteUser&&this.users[userInvited]?.send){this.users[userInvited]?.send({route:"receiveSessionInvite",args:[session,userInvited,inviteEndpoint]})}else{this.receiveSessionInvite(session,userInvited,inviteEndpoint)}};receiveSessionInvite=(session,userInvited,endpoint)=>{if(!this.invites[userInvited])this.invites[userInvited]={};let id=typeof session==="string"?session:session._id;this.invites[userInvited][id]={session,endpoint};return id};acceptInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;let invite=this.invites[userInvited]?.[id];let endpoint;if(invite){session=invite.session;endpoint=invite.endpoint;delete this.invites[userInvited]?.[id]}return new Promise((res,rej)=>{if(!id)res(false);if(remoteUser&&endpoint&&this.users[endpoint]?.send){let resolved;let timeout=setTimeout(()=>{if(!resolved){this.unsubscribe("joinSession",subbed);rej(new Error("Session join timed out"))}},1e4);let subbed=this.subscribe("joinSession",result=>{if(typeof result==="object"&&result?._id===id){if(result.setting?.users?.includes(userInvited)){this.unsubscribe("joinSession",subbed);resolved=true;if(timeout)clearTimeout(timeout);res(result)}}});this.users[endpoint]?.send({route:"joinSession",args:[id,userInvited,void 0,true]})}else res(this.joinSession(id,userInvited,typeof session==="object"?session:void 0))})};rejectInvite=(session,userInvited,remoteUser=true)=>{let id=typeof session==="string"?session:session._id;if(this.invites[userInvited]?.[id]){let endpoint=this.invites[userInvited][id].endpoint;delete this.invites[userInvited][id];if(remoteUser&&endpoint&&this.users[endpoint]?.send){this.users[endpoint].send({route:"rejectInvite",args:[id,userInvited]})}return true}};leaveSession=(session,userId,clear=true,remoteUser=true)=>{let sessionId;if(typeof session==="string"){sessionId=session;session=this.sessions.oneWay[sessionId];if(!session)session=this.sessions.shared[sessionId]}else sessionId=session._id;if(session){if(this.sessions.oneWay[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.oneWay[sessionId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId]?.sessions[sessionId];delete this.users[userId]?.sessionSubs?.[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){this.swapHost(session,void 0,true);delete session.data.shared[userId]}}if(remoteUser&&this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId,clear]})}else{this.unsubsribeFromSession(session,userId,clear)}}return true}return false};deleteSession=(session,userId,remoteUsers=true)=>{if(typeof session==="string"){let id=session;session=this.sessions.oneWay[id];if(!session)session=this.sessions.shared[id]}if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user]?.sessions)delete this.users[user].sessions[session._id];if(this.users[user]?.sessionSubs)delete this.users[user].sessionSubs[session._id];if(remoteUsers){if(session.users){for(const key in session.users){if(this.users[key]?.send)this.users[key].send({route:"unsubscribeFromSession",args:[session._id,key]})}}else if(session.listener){if(this.users[session.listener]?.send)this.users[session.listener].send({route:"unsubscribeFromSession",args:[session._id,session.listener]})}else if(this.users[userId]?.send){this.users[userId].send({route:"unsubscribeFromSession",args:[session._id,userId]})}}else{this.unsubsribeFromSession(session,user)}}if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.oneWay[session._id];if(session.onclose)session.onclose(session)}}return true};getFirstMatch(obj1,obj2){for(const i in obj1){if(i in obj2)return i}return false}swapHost=(session,newHostId,adoptData=true,remoteUser=true)=>{if(typeof session==="string"){if(this.sessions.oneWay[session])session=this.sessions.oneWay[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){let oldHost=session.settings.host;delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];if(adoptData&&oldHost&&session.settings.inheritHostData!==false){if(session.data?.shared[oldHost]){if(session.data?.shared[oldHost]){session.data.shared[session.settings.host]=Object.assign(session.data.shared[session.settings.host]?session.data.shared[session.settings.host]:{},session.data.shared[oldHost]);if(remoteUser){}}}}return true}return false};subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}let user=this.users[userId];if(!user)return void 0;if(!user.sessionSubs)user.sessionSubs={};if(!user.sessionSubs[session._id])user.sessionSubs[session._id]={};if(onmessage)user.sessionSubs[session._id].onmessage=onmessage;if(onopen)this.sessionSubs[userId][session._id].onopen=onopen;if(onclose)user.sessionSubs[session._id].onclose=onclose;if(typeof onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)this.sessionSubs[userId][session._id].onopen(session,user);this.unsubscribe("joinSession",sub)});user.sessionSubs[session._id].onopenSub=sub}return session};unsubsribeFromSession=(session,userId,clear=true)=>{if(typeof session==="string"){let s=this.sessions.oneWay[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}const clearSessionSubs=(Id,s)=>{let u2=this.users[Id];if(!u2)return void 0;if(u2.sessionSubs?.[s._id]){if(u2.sessionSubs[s._id].onopenSub){this.unsubscribe("joinSession",u2.sessionSubs[s._id].onopenSub)}}if(u2.sessionSubs[s._id].onclose)u2.sessionSubs[s._id].onclose(s,u2);delete u2.sessionSubs[s._id]};if(userId){clearSessionSubs(userId,session)}else{for(const key in this.users){clearSessionSubs(key,session)}}if(clear){if(this.sessions.oneWay[session._id])delete this.sessions.oneWay[session._id];else if(this.sessions.shared[session._id])delete this.sessions.shared[session._id]}};sessionUpdateCheck=(sessionHasUpdate,transmit=true)=>{let updates={oneWay:{},shared:{}};for(const session in this.sessions.oneWay){const sesh=this.sessions.oneWay[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.oneWay[session];continue}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(prop in this.users[sesh.source]){if(this.sessions.oneWay[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(prop in this.users[sesh.source]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.oneWay[session]?.data&&prop in this.sessions.oneWay[session]?.data)delete this.sessions.oneWay[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.oneWay[session].data,updateObj.data);updates.oneWay[sesh._id]=updateObj;if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.onhasupdate(sesh,updateObj)}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const oneWayData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}else if(sesh.settings.newUser){updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;sesh.settings.newUser=false}if(user!==sesh.settings.host){oneWayData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data?.oneWay&&!(user in sesh.data.oneWay)){if(typeof this.users[user][prop]==="object")oneWayData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else oneWayData[user][prop]=this.users[user][prop]}else if(typeof oneWayData[user][prop]==="object"&&sesh.data){if(prop in this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))oneWayData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.oneWay?.[prop]!==this.users[user][prop])oneWayData[user][prop]=this.users[user][prop]}else if(sesh.data?.oneWay?.[user]&&prop in sesh.data?.oneWay?.[user])delete sesh.data.oneWay[user][prop]}if(Object.keys(oneWayData[user]).length===0)delete oneWayData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user]))sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}}}if(Object.keys(oneWayData).length>0){updateObj.data.oneWay=oneWayData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.settings.host===user)this.swapHost(sesh,void 0,true);if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.oneWay?.[user])delete sesh.data.shared[user];updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(prop in this.users[user]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user]?.[prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user]?.[prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]&&prop in sesh.data?.shared[user])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.oneWay){updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){Object.assign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.oneWay){Object.assign(this.sessions.shared[session].data?.oneWay,updateObj.data.oneWay)}if(sessionHasUpdate)sessionHasUpdate(sesh,updateObj);if(sesh.settings.onhasupdate)sesh.settings.onhasupdate(sesh,updateObj)}}if(Object.keys(updates.oneWay).length===0)delete updates.oneWay;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};transmitSessionUpdates=updates=>{let users={};if(updates.oneWay){for(const s in updates.oneWay){let session=this.sessions.oneWay[s];if(session?.settings){let u2=session.settings.listener;if(!users[u2])users[u2]={};users[u2].oneWay[s]=updates.oneWay[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){for(const u2 in session.settings.users){if(!users[u2])users[u2]={};users[u2].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u2 in users){message.args=[u2,users[u2]];if(this.users[u2]?.send)this.users[u2].send(JSON.stringify(message));this.setState({[u2]:Object.create(message)})}return users};receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(user){if(!user.sessions)user.sessions={oneWay:{},shared:{}};if(!user.sessionSubs)user.sessionSubs={}}if(update.oneWay){for(const key in update.oneWay){this.recursivelyAssign(this.sessions.oneWay[key].data,update.oneWay[key].data);if(this.sessions.oneWay[key]?.settings.onmessage)this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key],update.oneWay[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}if(update.shared){for(const key in update.shared){if(update.shared[key].settings.users)this.sessions.shared[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)this.sessions.shared[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.oneWay)this.recursivelyAssign(this.sessions.shared[key].data.oneWay,update.shared[key].data.oneWay);if(update.shared[key].data.shared)this.recursivelyAssign(this.sessions.shared[key].data.shared,update.shared[key].data.shared);if(this.sessions.shared[key]?.settings.onmessage)this.sessions.shared[key].settings.onmessage(this.sessions.shared[key],update.shared[key]);if(user?.sessionSubs[user._id]?.[key]?.onmessage)user.sessionSubs[user._id][key].onmessage(user.sessions[key],update,user)}}return user}};getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};userUpdateCheck=(user,onupdate)=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});if(onupdate){onupdate(user,updateObj)};return updateObj}}return void 0};setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};STREAMLATEST=0;STREAMALLLATEST=1;streamSettings={};streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};setStreamFunc=(name2,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name2].settings[key])this.streamSettings[name2].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name2].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name2].settings[key].callback=callback;if(!this.streamSettings[name2].settings[key].callback)this.streamSettings[name2].settings[key].callback=this.streamFunctions.allLatestValues;return true};addStreamFunc=(name2,callback=data=>{})=>{this.streamFunctions[name2]=callback};setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};removeStream=(streamName,key)=>{if(streamName&&this.streamSettings[streamName]&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}}};var Router=class extends Service{name="router";connections={};sources={};services={};serviceConnections={};users={};userTimeout=1e4;order;constructor(options){super(options);this.load(this);if(options){if(options.order)this.order=options.order;if(options.timeout)this.userTimeout=options.timeout;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}addUser=async(info,connections,config,receiving)=>{let user;if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}if(this.users[info._id]){user=this.users[info._id]}else{user=Object.assign({},info)}if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>this.userTimeout){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}if(!this.users[info._id]){let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let sendAll=(message,...a)=>{let connections2=this.getConnections(user._id,"send");for(const key in connections2)if(connections2[key]?.send)return connections2[key].send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let requestAll=(message,method,...a)=>{let connections2=this.getConnections(user._id,"request");let results=[];for(const key in connections2)if(connections2[key]?.request)results.push(connections2[key].request(message,method,...a));return Promise.all(results)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let postAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"post");for(const key in connections2)if(connections2[key]?.post)connections2[key].post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let runAll=(route,args,method,...a)=>{let connections2=this.getConnections(user._id,"run");let results=[];for(const key in connections2)if(connections2[key]?.run)results.push(connections2[key].run(route,args,method,...a));return Promise.all(results)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let subscribeAll=(route,callback,...a)=>{let connections2=this.getConnections(user._id,"subscribe");let results=[];for(const key in connections2)if(connections2[key]?.post)results.push(connections2[key].subscribe(route,callback,...a));return Promise.all(results)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let unsubscribeAll=(route,subs,...a)=>{let connections2=this.getConnections(user._id,"unsubscribe");let results=[];for(const key in connections2)if(connections2[key]?.post&&subs[key])results.push(connections2[key].unsubscribe(route,subs[key],...a));return Promise.all(results)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;user.sendAll=sendAll;user.requestAll=requestAll;user.postAll=postAll;user.runAll=runAll;user.subscribeAll=subscribeAll;user.unsubscribeAll=unsubscribeAll;user.terminateAll=terminate;this.users[user._id]=user}if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i)=>{if(connections[k]?._id){connectionIds[`${i}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}getConnection=(sourceId,hasMethod,connectionId)=>{if(this.connections[sourceId]){return this.connections[sourceId]}else if(this.sources[sourceId]){if(hasMethod?.includes("All"))return this.users[sourceId];if(connectionId){if(hasMethod){if(this.sources[sourceId][connectionId]?.[hasMethod])return this.sources[sourceId][connectionId]}else if(this.sources[sourceId][connectionId])return this.sources[sourceId][connectionId];else return void 0}else if(this.order){for(let i=0;i{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;if(props){for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}}if(pass){found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}return found}};runConnection=async(userId,method,args,connectionId)=>{let sendTo;if(method.indexOf("All")>-1){sendTo=this.users[userId]}else{sendTo=this.getConnection(userId,method,connectionId)}if(sendTo){let res=sendTo[method](...args);res=await res;return res}};subscribeThroughConnection=(route,remoteRelay,remoteEndpoint,callback,...args)=>{if(typeof remoteRelay==="string"){remoteRelay=this.getConnection(remoteRelay,"run")}if(typeof remoteRelay==="object")return new Promise((res,rej)=>{remoteRelay.run("routeConnections",[route,remoteEndpoint,remoteRelay._id,...args]).then(sub=>{this.__node.state.subscribeEvent(remoteEndpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[remoteEndpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};addConnection=(options,source,autoRemove=true)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.connection=options.connection;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(autoRemove&&settings.source&&this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await connectionHasId(info,this.userTimeout)}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await connectionHasId(connection,this.userTimeout)}if(connection._id)return this.addConnection({connection,service},source)}}};terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}}};function connectionHasId(connection,timeout=1e4){return new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>timeout){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connection timed out:",er)})}0&&(module.exports={CMDService,Callable,E2EEService,ECSService,EventHandler,Graph,GraphNode,HTTPbackend,Router,SSEbackend,Service,SessionsService,WSSbackend,animate,backprop,bindListener,branching,connectionHasId,defaultManifest,defaultServiceWorker,getAllProperties,getCallbackFromString,htmlBodyBoilerPlate,instanceObject,isFunction,isNativeClass,isTypedArray,loaders,loop,methodstrings,nodeTemplates,recursivelyAssign,remoteGraphRoutes,scriptBoilerPlate,spliceTypedArray,state,substitute__operator,transformListenerResult,triggerListenerOncreate,wrapArgs}); + (`+HotReloadClient.toString()+`)('${socketURL}') + <\/script> + `};this.setTree(this);if(settings){if(settings.protocol==="https"){this.setupHTTPSserver(settings)}else this.setupHTTPserver(settings)}}getRequestBody(req){let chunks=[];return new Promise((resolve,reject)=>{req.on("data",chunk=>{chunks.push(chunk)}).on("end",()=>{resolve(Buffer.concat(chunks))}).on("error",er=>{reject(er)})})}};var import_better_sse=__toESM(require_build());var SSEbackend=class extends Service{constructor(options){super(options);this.name="sse";this.debug=false;this.servers={};this.eventsources={};this.connections={servers:this.servers,eventsources:this.eventsources};this.setupSSE=options=>{const server=options.server;let path3=options.path;if(this.servers[path3]){return false}const channel=(0,import_better_sse.createChannel)();let sse={type:"sse",channel,sessions:{},requests:{},...options};this.servers[path3]=sse;sse._id=options._id?options._id:path3;if(!sse.onconnectionclose)sse.onconnectionclose=(session,sse2,id,req,res)=>{delete sse2.sessions[id]};const send=(message,eventName,sessionId)=>{return this.transmit(message,path3,eventName,sessionId)};const terminate=()=>{return this.terminate(path3)};let request=(message,method,sessionId,eventName)=>{if(!sessionId){let promises=[];for(const key in sse.sessions){promises.push(this.request(message,path3,key,eventName))}return promises}return this.request(message,path3,method,sessionId,eventName)};let post=(route,args,method,sessionId,eventName)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,path3,eventName,sessionId)};let run=(route,args,method,sessionId,eventName)=>{let r={route,args};if(!sessionId){let promises=[];for(const key in sse.sessions){promises.push(this.request(r,path3,key,eventName))}return promises}return this.request(r,path3,method,sessionId,eventName)};let subscribe=(route,callback,sessionId)=>{return this.subscribeToSSE(route,options.url,callback,sessionId)};let unsubscribe=(route,sub,sessionId,eventName)=>{return run("unsubscribe",[route,sub],void 0,sessionId,eventName)};sse.send=send;sse.request=request;sse.post=post;sse.run=run;sse.subscribe=subscribe;sse.unsubscribe=unsubscribe;sse.terminate=terminate;sse.graph=this;let onRequest=(req,response)=>{if(req.url?.includes(path3)){if(req.method==="GET"){if(this.debug)console.log("SSE Request",path3);(0,import_better_sse.createSession)(req,response).then(session=>{channel.register(session);let _id=`sse${Math.floor(Math.random()*1e15)}`;sse.sessions[_id]=session;this.eventsources[_id]={_id,session,served:sse,send:(message,eventName)=>{return send(message,eventName,_id)},request:(message,method,eventName)=>{return request(message,method,_id,eventName)},post:(route,args,method,eventName)=>{return post(route,args,method,_id,eventName)},run:(route,args,method,eventName)=>{return run(route,args,method,_id,eventName)},subscribe:(route,callback)=>{return subscribe(route,callback,_id)},unsubscribe:(route,sub,eventName)=>{return unsubscribe(route,sub,_id,eventName)},terminate:()=>{delete this.eventsources[_id];delete sse.sessions[_id];return true},onclose:()=>options.onconnectionclose,graph:this};session.push(JSON.stringify({route:"setId",args:_id}));session.on("close",()=>{if(this.eventsources[_id].onclose)this.eventsources[_id].onclose(session,sse,_id,req,response)});if(sse.onconnection){sse.onconnection(session,sse,_id,req,response)}})}else{let body=[];req.on("data",chunk=>{body.push(chunk)}).on("end",()=>{body=Buffer.concat(body).toString();if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}let route,method,args,callbackId;if(body?.route||body?.callbackId){method=body.method;args=body.args;callbackId=body.callbackId;if(typeof body.route==="string"){if(body.route.includes("/")&&body.route.length>1)body.route=body.route.split("/").pop();route=this.__node.tree[body.route]}}if(route){let res=this.receive({route,args,method})}else if(callbackId&&sse.requests[callbackId]){sse.requests[callbackId](args)}if(this.__node.keepState)this.setState({[path3]:body})})}}};let requestListeners=server.listeners("request");server.removeAllListeners("request");const otherListeners=(req,res)=>{requestListeners.forEach(l=>{l(req,res)})};const sseListener=(req,res)=>{if(req.url)if(req.url.indexOf(path3)>-1){if(!this.servers[path3]){server.removeListener("request",sseListener);server.addListener("request",otherListeners)}onRequest(req,res)}else otherListeners(req,res)};server.addListener("request",sseListener);server.addListener("close",()=>{if(sse.onclose)sse.onclose(sse)});return sse};this.open=this.setupSSE;this.streamIterable=(path3,iterable,sessionId,eventName="message")=>{let server=this.servers[path3];if(server){if(sessionId){if(server.sessions[sessionId]){return server.sessions[sessionId].iterate(iterable,{eventName})}}else{let promises=[];for(const key in server.sessions){promises.push(server.sessions[key].iterate(iterable))}return promises}}};this.streamReadable=(path3,readable,sessionId,eventName="message")=>{let server=this.servers[path3];if(server){if(sessionId){if(server.sessions[sessionId]){return server.sessions[sessionId].stream(readable,{eventName})}}else{let promises=[];for(const key in server.sessions){promises.push(server.sessions[key].stream(readable))}return promises}}};this.transmit=(data,path3,eventName,sessionId)=>{if(!path3&&typeof data==="object"){if(data.route){let keys=Object.keys(this.servers);if(keys.length>0){let evs=this.servers[keys[0]];if(evs.channels?.includes(data.route)){path3=evs.path;eventName=data.route}}if(!path3&&data.route){if(this.servers[data.route])path3=data.route}}data=JSON.stringify(data)}if(!path3)path3=Object.keys(this.servers)[0];if(path3&&this.servers[path3]){if(sessionId){if(this.servers[path3].sessions[sessionId]?.isConnected){this.servers[path3].sessions[sessionId].push(data,eventName)}else if(this.servers[path3].sessions[sessionId]){delete this.servers[path3].sessions[sessionId];return false}}else this.servers[path3].channel.broadcast(data,eventName);return true}return false};this.request=(message,path3,method,sessionId,eventName)=>{return new Promise((res,rej)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,path3,callbackId,sessionId]};if(method)req.method=method;let sse=this.servers[path3];let callback=result=>{res(result)};sse.requests[callbackId]=callback;if(sse){if(sessionId){if(sse.sessions[sessionId])sse.sessions[sessionId].push(JSON.stringify(req),eventName)}else sse.channel.broadcast(JSON.stringify(req),eventName)}})};this.runRequest=(message,path3,callbackId,sessionId)=>{let res=this.receive(message);if(path3){let sse=this.servers[path3];if(sse){if(res instanceof Promise){res.then(r=>{if(sessionId){if(sse.sessions[sessionId]){sse.sessions[sessionId].push(JSON.stringify({args:r,callbackId}))}}else{sse.channel.broadcast(JSON.stringify({args:r,callbackId}))}})}else{if(sessionId){if(sse.sessions[sessionId]){sse.sessions[sessionId].push(JSON.stringify({args:res,callbackId}))}}else sse.channel.broadcast(JSON.stringify({args:res,callbackId}))}}}return res};this.subscribeSSE=(route,path3,sessionId,eventName)=>{if(this.servers[path3]){return this.subscribe(route,res=>{this.servers[path3].send({args:res,callbackId:route},eventName,sessionId)})}};this.subscribeToSSE=(route,path3,callback,sessionId,eventName)=>{if(this.servers[path3]){this.__node.state.subscribeTrigger(path3,res=>{if(res?.callbackId===route){if(!callback)this.setState({[path3]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});if(sessionId){if(this.servers[path3].sessions[sessionId]){return this.eventsources[sessionId].run("subscribeSSE",{route:"subscribeSSE",args:[route,path3]},void 0,eventName)}}else{let promises=[];for(const k in this.servers[path3].sessions){promises.push(this.eventsources[k].run("subscribeSSE",{route:"subscribeSSE",args:[route,path3]},void 0,eventName))}return promises}}};this.terminate=sse=>{if(typeof sse==="object")delete this.servers[sse.path];else if(typeof sse==="string"){delete this.servers[sse];delete this.eventsources[sse]}return true};this.setTree(this)}};var import_stream=__toESM(require_stream(),1);var import_receiver=__toESM(require_receiver(),1);var import_sender=__toESM(require_sender(),1);var import_websocket=__toESM(require_websocket(),1);var import_websocket_server=__toESM(require_websocket_server(),1);var wrapper_default=import_websocket.default;var WSSbackend=class extends Service{constructor(options){super(options);this.name="wss";this.debug=false;this.servers={};this.sockets={};this.connections={servers:this.servers,sockets:this.sockets};this.open=options=>{if(options?.server){return this.setupWSS(options)}else return this.openWS(options)};this.setupWSS=options=>{const host=options.host;const port=options.port;let path3=options.path;const server=options.server;delete options.server;if(!("keepState"in options))options.keepState=true;let opts={host,port};if(typeof options.serverOptions)Object.assign(opts,options.serverOptions);const wss=new import_websocket_server.default(opts);let address=`${host}:${port}/`;if(path3){if(path3.startsWith("/"))path3=path3.substring(1);address+=path3}this.servers[address]={type:"wss",wss,clients:{},address,...options};if(!options.onmessage)options.onmessage=data=>{if(data instanceof Buffer)data=data.toString();const result=this.receive(data,wss,this.servers[address]);if(options.keepState)this.setState({[address]:result})};wss.on("connection",(ws,request2)=>{if(this.debug)console.log(`New socket connection on ${address}`);let clientId=`socket${Math.floor(Math.random()*1e12)}`;this.servers[address].clients[clientId]=ws;ws.send(JSON.stringify({route:"setId",args:clientId}));let info=this.openWS({socket:ws,address:clientId,_id:clientId});if(this.servers[address].onconnection)this.servers[address].onconnection(ws,request2,this.servers[address],clientId);if(this.servers[address].onconnectionclosed)ws.on("close",(code,reason)=>{if(this.servers[address].onconnectionclosed)this.servers[address].onconnectionclosed(code,reason,ws,this.servers[address],clientId)})});wss.on("error",err=>{if(this.debug)console.log("Socket Error:",err);if(this.servers[address].onerror)this.servers[address].onerror(err,wss,this.servers[address]);else console.error(err)});let onUpgrade=(request2,socket,head)=>{if(request2.headers&&request2.url){if(this.debug)console.log("Upgrade request at: ",request2.url);let addr=request2.headers.host.split(":")[0];addr+=":"+port;addr+=request2.url.split("?")[0];if(addr===address&&this.servers[addr]){this.servers[addr].wss.handleUpgrade(request2,socket,head,ws=>{if(this.servers[address].onupgrade)this.servers[address].onupgrade(ws,this.servers[address],request2,socket,head);this.servers[addr].wss.emit("connection",ws,request2)})}}};server.addListener("upgrade",onUpgrade);wss.on("close",()=>{server.removeListener("upgrade",onUpgrade);if(this.servers[address].onclose)this.servers[address].onclose(wss,this.servers[address]);else console.log(`wss closed: ${address}`)});let send=(message,socketId)=>{if(!socketId){for(const key in this.servers[address].clients){this.sockets[key].send(message)}}else return this.sockets[socketId].send(message)};let request=(message,method,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].request(message,method))}return promises}else return this.sockets[socketId].request(message,method)};let post=(route,args,method,socketId)=>{if(!socketId){for(const key in this.servers[address].clients){this.sockets[key].post(route,args,method)}}else return this.sockets[socketId].post(route,args,method)};let run=(route,args,method,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].run(route,args,method))}return promises}else return this.sockets[socketId].run(route,args,method)};let subscribe=(route,callback,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].subscribe(route,callback))}return promises}else this.sockets[socketId].subscribe(route,callback)};let unsubscribe=(route,sub,socketId)=>{if(!socketId){let promises=[];for(const key in this.servers[address].clients){promises.push(this.sockets[key].unsubscribe(route,sub))}return promises}else this.sockets[socketId].unsubscribe(route,sub)};let terminate=socketId=>{if(socketId)return this.terminate(socketId);else return this.terminate(address)};this.servers[address].send=send;this.servers[address].request=request;this.servers[address].post=post;this.servers[address].run=run;this.servers[address].subscribe=subscribe;this.servers[address].unsubscribe=unsubscribe;this.servers[address].terminate=terminate;this.servers[address].graph=this;this.servers[address]._id=options._id?options._id:address;return this.servers[address]};this.openWS=options=>{if(!options.address){let protocol=options.protocol;if(!protocol)protocol="wss";options.address=`${protocol}://${options.host}`;if(options.port)options.address+=":"+options.port;if(!options.path||options.path?.startsWith("/"))options.address+="/";if(options.path)options.address+=options.path}const address=options.address;let socket;if(options.socket)socket=options.socket;else socket=new wrapper_default(address);if(!("keepState"in options))options.keepState=true;if(options.onmessage)socket.on("message",data=>{this.sockets[address].onmessage(data,socket,this.sockets[address])});else if(options._id){socket.on("message",data=>{if(ArrayBuffer.isView(data))data=data.toString();this.receive(data,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data})}})}else{let socketonmessage=data=>{if(ArrayBuffer.isView(data))data=data.toString();if(data){if(typeof data==="string"){let substr=data.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))data=data.replace(/\\/g,"");if(data[0]==='"'){data=data.substring(1,data.length-1)};data=JSON.parse(data);if(data.route==="setId"){this.sockets[address]._id=data.args;socket.removeEventListener("message",socketonmessage);socket.on("message",data2=>{if(ArrayBuffer.isView(data2))data2=data2.toString();this.receive(data2,socket,this.sockets[address]);if(options.keepState){this.setState({[address]:data2})}})}}}}this.receive(data,socket,this.sockets[address]);if(options.keepState)this.setState({[address]:data})};socket.on("message",socketonmessage);options.onmessage=socketonmessage}socket.on("open",()=>{if(this.sockets[address].onopen)this.sockets[address].onopen(socket,this.sockets[address])});socket.on("close",(code,reason)=>{if(this.sockets[address].onclose)this.sockets[address].onclose(code,reason,socket,this.sockets[address])});socket.on("error",er=>{if(this.sockets[address].onerror)this.sockets[address].onerror(er,socket,this.sockets[address])});let send=message=>{return this.transmit(message,socket)};let post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,socket)};let run=(route,args,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},address,callbackId]};if(method)req.args[0].method=method;let onmessage=ev=>{if(typeof ev.data==="string"&&ev.data.indexOf("{")>-1)ev.data=JSON.parse(ev.data);if(typeof ev.data==="object"){if(ev.data.callbackId===callbackId){socket.removeEventListener("message",onmessage);res(ev.data.args)}}};socket.addEventListener("message",onmessage);this.transmit(req,socket)})};let request=(message,method)=>{return this.request(message,socket,address,method)};let subscribe=(route,callback)=>{return this.subscribeToSocket(route,address,callback)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let terminate=()=>{this.terminate(address)};this.sockets[address]={type:"socket",socket,send,post,request,run,subscribe,unsubscribe,terminate,graph:this,...options};return this.sockets[address]};this.transmit=(message,ws)=>{if(typeof message==="object")message=JSON.stringify(message);if(!ws){let served=this.servers[Object.keys(this.servers)[0]];if(served)ws=served.wss;else{let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket};}if(ws instanceof import_websocket_server.default){ws.clients.forEach(c=>{c.send(message)})}else if(ws instanceof wrapper_default)ws.send(message)};this.closeWS=ws=>{if(!ws){let s=this.sockets[Object.keys(this.sockets)[0]];if(s)ws=s.socket}else if(typeof ws==="string"){for(const k in this.sockets){if(k.includes(ws)){ws=this.sockets[k].socket;delete this.sockets[k];break}}}if(ws instanceof wrapper_default){if(ws.readyState===ws.OPEN)ws.close()}return true};this.terminate=ws=>{if(!ws){let served=this.servers[Object.keys(this.servers)[0]];if(served)ws=served.wss}else if(typeof ws==="string"){for(const k in this.servers){if(k.includes(ws)){ws=this.servers[k].wss;for(const key in this.servers[k].clients){this.closeWS(this.servers[k].clients[key])}delete this.servers[k];break}}if(!ws){for(const k in this.sockets){if(k.includes(ws)){ws=this.sockets[k].socket;delete this.sockets[k];break}}}}if(ws instanceof import_websocket_server.default){ws.close(er=>{if(er)console.error(er)})}else if(ws instanceof wrapper_default){if(ws.readyState===ws.OPEN)ws.close()}return true};this.request=(message,ws,_id,method)=>{let callbackId=`${Math.random()}`;let req={route:"runRequest",args:[message,_id,callbackId]};if(method)req.method=method;return new Promise((res,rej)=>{let onmessage=ev=>{let data=ev.data;if(typeof data==="string"){if(data.includes("callbackId"))data=JSON.parse(data)}if(typeof data==="object"){if(data.callbackId===callbackId){ws.removeEventListener("message",onmessage);res(data.args)}}};ws.addEventListener("message",onmessage);ws.send(JSON.stringify(req))})};this.runRequest=(message,ws,callbackId)=>{let res=this.receive(message);if(ws){if(typeof ws==="string"){for(const key in this.servers){for(const c in this.servers[key].clients){if(c===ws){ws=this.servers[key].clients[c];break}}}if(!(ws instanceof wrapper_default)){for(const s in this.sockets){if(s===ws){ws=this.sockets[s].socket;break}}}}if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(ws instanceof wrapper_default)ws.send(JSON.stringify(res))})}else{res={args:res,callbackId};if(ws instanceof wrapper_default)ws.send(JSON.stringify(res))}}return res};this.subscribeSocket=(route,socket,key,subInput)=>{if(typeof socket==="string"){if(this.sockets[socket])socket=this.sockets[socket].socket;else{for(const prop in this.servers){if(this.servers[prop].clients[socket])socket=this.servers[prop].clients[socket]}}}if(typeof socket==="object")return this.subscribe(route,res=>{if(socket.readyState===socket.OPEN){if(res instanceof Promise){res.then(r=>{socket.send(JSON.stringify({args:r,callbackId:route}))})}else{socket.send(JSON.stringify({args:res,callbackId:route}))}}},key,subInput)};this.subscribeToSocket=(route,socketId,callback,key,subInput)=>{if(typeof socketId==="string"&&this.sockets[socketId]){this.__node.state.subscribeTrigger(socketId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[socketId]:res.args});else if(typeof callback==="string"){this.setState({[callback]:res.args})}else callback(res.args)}});return this.sockets[socketId].request({route:"subscribeSocket",args:[route,socketId,key,subInput]})}};this.setTree(this)}};var import_child_process=require("child_process");var import_path=__toESM(require("path"));var CMDService=class extends Service{constructor(options){super(options);this.connections={processes:void 0};this.subprocessloader={"process":(node,parent2,graph,tree,properties)=>{if(node.command){this.createProcess(node)}}};this.createProcess=properties=>{let newprocess=properties;if(!newprocess.command)newprocess.command="node";if(!newprocess.args)newprocess.args=[import_path.default.join(process.cwd(),"node_modules","graphscript-node","services","cmd","childprocess.js")];if(newprocess.command){let p;if(!newprocess.options){newprocess.options={shell:true,stdio:"inherit"}}newprocess.controller=new AbortController;newprocess.options=Object.assign({signal:newprocess.controller.signal,env:process.env,cwd:process.cwd()},newprocess.options);if(newprocess.tag)newprocess._id=newprocess.tag;else{newprocess._id=`process${Math.floor(Math.random()*1e15)}`;newprocess.tag=newprocess._id}if(typeof newprocess.command==="string"){if(newprocess.command.includes(".js")){p=(0,import_child_process.fork)(newprocess.command,newprocess.args,newprocess.options)}else p=(0,import_child_process.spawn)(newprocess.command,newprocess.args?newprocess.args:[],newprocess.options);if(p instanceof import_child_process.ChildProcess){if(p.stderr){if(newprocess.onerror){p.stderr.on("data",newprocess.onerror)}else p.stderr.on("data",console.error)}if(p.stdout){if(newprocess.stdout){p.stdout.on("data",newprocess.stdout)}else p.stdout.on("data",data=>{let str=data.toString();this.receive(str);this.setState({[newprocess._id]:str})})}if(newprocess.onclose){p.on("close",newprocess.onclose)}newprocess.process=p;newprocess.controller=new AbortController;newprocess.send=data=>{return p.send(data)};newprocess.request=(message,method)=>{return this.request(message,newprocess._id,method)};newprocess.post=(route,args,method)=>{let message={route,args};if(method)message.method=method;return p.send(JSON.stringify(message))};newprocess.run=(route,args,method)=>{let message={route,args};if(method)message.method=method;return this.request(message,newprocess._id)};newprocess.subscribe=(route,callback)=>{return this.subscribeToProcess(route,newprocess._id,callback)};newprocess.unsubscribe=(route,sub)=>{return newprocess.run("unsubscribe",[route,sub])};this.processes[newprocess._id]=newprocess}}}return newprocess};this.open=this.createProcess;this.abort=childprocess=>{if(childprocess.controller)childprocess.controller.abort();else childprocess.kill();return true};this.send=(childprocess,data)=>{return childprocess.send(data)};this.request=(message,processId,method)=>{let childprocess=this.processes[processId].process;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let ondata=data=>{let str=data.toString();if(str.includes("{")){let parsed=JSON.parse(str);if(parsed.callbackId===callbackId){childprocess.removeListener("data",ondata);res(parsed.args)}}};childprocess.addListener("data",ondata);childprocess.send(req)})};this.runRequest=(message,callbackId,childprocess)=>{let res=this.receive(message);if(typeof childprocess==="string")childprocess=this.processes[childprocess].process;if(res instanceof Promise){res.then(v=>{res={args:v,callbackId};if(childprocess instanceof import_child_process.ChildProcess)childprocess.send(JSON.stringify(res));else process.stdout.write(JSON.stringify(res))})}else{res={args:res,callbackId};if(childprocess instanceof import_child_process.ChildProcess)childprocess.send(JSON.stringify(res));else process.stdout.write(JSON.stringify(res))}return res};this.setTree(this);this.connections.processes=this.processes;if(process?.stdin){process.stdin.on("data",data=>{let str=data.toString();this.receive(str)})}}subscribeProcess(route,childprocess,key,subInput){if(typeof childprocess==="string"&&this.processes[childprocess]){childprocess=this.processes[childprocess].process}return this.subscribe(route,res=>{if(res instanceof Promise){res.then(r=>{childprocess.send(JSON.stringify({args:r,callbackId:route}))})}else{childprocess.send(JSON.stringify({args:res,callbackId:route}))}},key,subInput)}subscribeToProcess(route,processId,callback,key,subInput){if(typeof processId==="string"&&this.processes[processId]){this.__node.state.subscribeTrigger(processId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[processId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.processes[processId].request(JSON.stringify({route:"subscribeSocket",args:[route,processId,key,subInput]}))}}};var SessionsService=class extends Service{constructor(options,users){super(options);this.name="sessions";this.users={};this.sessions={private:{},shared:{}};this.getSessionInfo=(sessionId,userId)=>{if(!sessionId){return this.sessions.shared}else{if(this.sessions.private[sessionId]){let s=this.sessions.private[sessionId];if(s.settings){if(s.settings.source===userId||s.settings.listener===userId||s.settings.ownerId===userId||s.settings.admins?.[userId]||s.settings.moderators?.[userId])return{private:{[sessionId]:s}}}}else if(this.sessions.shared[sessionId]){return{shared:{[sessionId]:this.sessions.shared[sessionId]}}}else{let res={};for(const id in this.sessions.shared){if(this.sessions.shared[id].settings?.name)res[id]=this.sessions.shared.settings}if(Object.keys(res).length>0)return res}}};this.openPrivateSession=(options={},userId)=>{if(!options._id){options._id=`private${Math.floor(Math.random()*1e15)}`;if(this.sessions.private[options._id]){delete options._id;this.openPrivateSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(userId){if(!options.settings)options.settings={listener:userId,source:userId,propnames:{latency:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.listener)options.settings.listener=userId;if(!options.settings.source)options.settings.source=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}if(!options.data)options.data={};if(this.sessions.private[options._id]){return this.updateSession(options,userId)}else if(options.settings?.listener&&options.settings.source)this.sessions.private[options._id]=options}return options};this.openSharedSession=(options,userId)=>{if(!options._id){options._id=`shared${Math.floor(Math.random()*1e15)}`;if(this.sessions.shared[options._id]){delete options._id;this.openSharedSession(options,userId)}}if(options._id&&userId&&this.users[userId]){if(typeof userId==="string"){if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{[userId]:true},admins:{[userId]:true},ownerId:userId};if(!options.settings.users)options.settings.users={[userId]:true};if(!options.settings.admins)options.settings.admins={[userId]:true};if(!options.settings.ownerId)options.settings.ownerId=userId;if(!this.users[userId].sessions)this.users[userId].sessions={};this.users[userId].sessions[options._id]=options}else if(!options.settings)options.settings={name:"shared",propnames:{latency:true},users:{}};if(!options.data)options.data={private:{},shared:{}};if(!options.settings.name)options.name=options.id;if(this.sessions.shared[options._id]){return this.updateSession(options,userId)}else this.sessions.shared[options._id]=options}return options};this.updateSession=(options,userId)=>{let session;if(options._id){session=this.sessions.private[options._id];if(!session)session=this.sessions.shared[options._id];if(this.sessions.private[options._id]&&userId){let sesh=this.sessions.shared[options._id];if(sesh.settings&&(sesh?.settings.source===userId||sesh.settings.admins?.[userId]||sesh.settings.moderators?.[userId]||sesh.settings.ownerId===userId)){return Object.assign(this.sessions.shared[options._id],options)}}else if(options.settings?.source){return this.openPrivateSession(options,userId)}else return this.openSharedSession(options,userId)}return false};this.joinSession=(sessionId,userId,options)=>{if(!userId&&!this.users[userId])return false;if(!this.users[userId].sessions)this.users[userId].sessions={};let sesh=this.sessions.shared[sessionId];if(sesh?.settings){if(sesh.settings?.banned){if(sesh.settings.banned[userId])return false}if(sesh.settings?.password){if(!options?.settings?.password)return false;if(options.settings.password!==sesh.settings.password)return false}sesh.settings.users[userId]=true;this.users[userId].sessions[sessionId]=sesh;if(options){return this.updateSession(options,userId)};return sesh}else if(options?.source||options?.listener)return this.openPrivateSession(options,userId);else if(options)return this.openSharedSession(options,userId);return false};this.leaveSession=(sessionId,userId,clear=true)=>{let session=this.sessions.private[sessionId];if(!session)session=this.sessions.shared[sessionId];if(session){if(this.sessions.private[sessionId]){if(userId===session.settings.source||userId===session.settings.listener||session.settings.admins?.[userId]||session.settings.moderators?.[userId]){delete this.sessions.private[sessionId];delete this.users[userId].sessions[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId]}}}else if(this.sessions.shared[sessionId]){delete this.sessions.shared.settings.users[userId];delete this.users[userId].sessions[sessionId];if(clear){if(session.settings.admins?.[userId])delete(this.sessions.shared[sessionId].settings?.admins)[userId];if(session.settings.moderators?.[userId])delete(this.sessions.shared[sessionId].settings?.moderators)[userId];if(session.data.shared[userId])delete this.sessions.shared[sessionId].data?.shared[userId];if(session.settings.host===userId){delete session.settings.host;delete session.data.shared;session.data.shared={};this.swapHost(session)}}}return true}return false};this.swapHost=(session,newHostId)=>{if(typeof session==="string"){if(this.sessions.private[session])session=this.sessions.private[session];else if(this.sessions.shared[session])session=this.sessions.shared[session]}if(typeof session==="object"&&session.settings){delete session.settings.host;if(newHostId){if(session.settings.users[newHostId])session.settings.host=newHostId}if(session.settings.ownerId&&!session.settings.host){if(session.settings.users[session.settings.ownerId])session.settings.host=session.settings.ownerId}if(session.settings.admins&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.admins);if(match)session.settings.host=match}if(session.settings.moderators&&!session.settings.host){let match=this.getFirstMatch(session.settings.users,session.settings.moderators);if(match)session.settings.host=match}if(!session.settings.host)session.settings.host=Object.keys(session.settings.users)[0];return true}return false};this.deleteSession=(sessionId,userId)=>{let session=this.sessions.private[sessionId];if(!session)session=this.sessions.shared[sessionId];if(session){if(session.source===userId||session.listener===userId||session.admins?.[userId]||session.ownerId===userId){for(const user in session.settings.users){if(this.users[user].sessions)delete this.users[user].sessions[sessionId]}if(this.sessions.private[sessionId])delete this.sessions.private[sessionId];else if(this.sessions.shared[sessionId])delete this.sessions.private[sessionId]}}return true};this.subscribeToSession=(session,userId,onmessage,onopen,onclose)=>{if(typeof session==="string"){let s=this.sessions.private[session];if(!s)s=this.sessions.shared[session];if(!s)return void 0;session=s}if(typeof session.onopen==="function"){let sub=this.subscribe("joinSession",res=>{if(res._id===session._id)session.onopen(session,userId);this.unsubscribe("joinSession",sub)})}if(typeof session==="object"){if(onmessage)session.onmessage=onmessage;if(onopen)session.onclose=onopen;if(onclose)session.onclose=onclose}return session};this.sessionUpdateCheck=(transmit=true)=>{let updates={private:{},shared:{}};for(const session in this.sessions.private){const sesh=this.sessions.private[session];const updateObj={_id:sesh._id,settings:{listener:sesh.listener,source:sesh.source},data:{}};if(!this.users[sesh.source]){delete this.sessions.private[session];break}if(sesh.settings&&sesh.data){for(const prop in sesh.settings.propnames){if(this.users[sesh.source][prop]){if(this.sessions.private[session].data){if(typeof sesh.data[prop]==="object"){if(this.users[sesh.source][prop]&&(stringifyFast(sesh.data[prop])!==stringifyFast(this.users[sesh.source][prop])||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.users[sesh.source][prop]&&(sesh.data[prop]!==this.users[sesh.source][prop]||!(prop in sesh.data)))updateObj.data[prop]=this.users[sesh.source][prop]}else updateObj.data[prop]=this.users[sesh.source][prop]}else if(this.sessions.private[session]?.data?.[prop])delete this.sessions.private[session].data[prop]}}if(Object.keys(updateObj.data).length>0){this.recursivelyAssign(this.sessions.private[session].data,updateObj.data);updates.private[sesh._id]=updateObj}}for(const session in this.sessions.shared){const sesh=this.sessions.shared[session];const updateObj={_id:sesh._id,settings:{name:sesh.name},data:{}};if(sesh.settings?.host){const privateData={};const sharedData={};for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.private?.[user])delete sesh.data.shared[user];if(sesh.settings.host===user)this.swapHost(sesh);updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}if(user!==sesh.settings.host){privateData[user]={};for(const prop in sesh.settings.propnames){if(this.users[user][prop]){if(sesh.data?.private&&!(user in sesh.data.private)){if(typeof this.users[user][prop]==="object")privateData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else privateData[user][prop]=this.users[user][prop]}else if(typeof privateData[user][prop]==="object"&&sesh.data){if(this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data)))privateData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.private?.[prop]!==this.users[user][prop])privateData[user][prop]=this.users[user][prop]}else if(sesh.data?.private?.[user]?.[prop])delete sesh.data.private[user][prop]}if(Object.keys(privateData[user]).length===0)delete privateData[user]}else{sharedData[user]={};for(const prop in sesh.settings.hostprops){if(this.users[user][prop]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sharedData[user][prop]==="object"&&sesh.data){if(this.users[user][prop]&&(stringifyFast(sesh.data?.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])))sharedData[user][prop]=this.users[user][prop]}else if(this.users[user][prop]&&sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]?.[prop])delete sesh.data.shared[user][prop]}}}if(Object.keys(privateData).length>0){updateObj.data.private=privateData}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}else{const sharedData={};if(sesh.settings?.users){for(const user in sesh.settings.users){if(!this.users[user]){delete sesh.settings.users[user];if(sesh.data?.shared[user])delete sesh.data.shared[user];if(sesh.data?.private?.[user])delete sesh.data.shared[user];if(sesh.settings.host===user)this.swapHost(sesh);updateObj.settings.users=sesh.settings.users;updateObj.settings.host=sesh.settings.host;continue}sharedData[user]={};for(const prop in sesh.settings.propnames){if(this.users[user][prop]){if(sesh.data&&!(user in sesh.data.shared)){if(typeof this.users[user][prop]==="object")sharedData[user][prop]=this.recursivelyAssign({},this.users[user][prop]);else sharedData[user][prop]=this.users[user][prop]}else if(typeof sesh.data?.shared[user][prop]==="object"){if(stringifyFast(sesh.data.shared[user][prop])!==stringifyFast(this.users[user][prop])||!(prop in sesh.data.shared[user])){sharedData[user][prop]=this.users[user][prop]}}else if(sesh.data?.shared[user][prop]!==this.users[user][prop])sharedData[user][prop]=this.users[user][prop]}else if(sesh.data?.shared[user]?.[prop])delete sesh.data.shared[user][prop]}if(Object.keys(sharedData[user]).length===0)delete sharedData[user]}if(Object.keys(sharedData).length>0){updateObj.data.shared=sharedData}}}if(updateObj.data.shared||updateObj.data.private)updates.shared[sesh._id]=updateObj;if(updateObj.data.shared){this.recursivelyAssign(this.sessions.shared[session].data?.shared,updateObj.data.shared)}if(updateObj.data.private){this.recursivelyAssign(this.sessions.shared[session].data?.private,updateObj.data.private)}}if(Object.keys(updates.private).length===0)delete updates.private;if(Object.keys(updates.shared).length===0)delete updates.shared;if(Object.keys(updates).length===0)return void 0;if(transmit)this.transmitSessionUpdates(updates);return updates};this.transmitSessionUpdates=updates=>{let users={};if(updates.private){for(const s in updates.private){let session=this.sessions.private[s];if(session?.settings){let u=session.settings.listener;if(!users[u])users[u]={private:{}};else if(!users[u].private)users[u].private={};users[u].private[s]=updates.private[s]}}}if(updates.shared){for(const s in updates.shared){let session=this.sessions.shared[s];if(session?.settings){let copy;if(session.settings.host){copy=Object.assign({},updates.shared[s]);delete copy.data.private}for(const u in session.settings.users){if(!users[u])users[u]={shared:{}};else if(!users[u].shared)users[u].shared={};if(session.settings.host){if(u!==session.settings.host){users[u].shared[s]=copy}else users[u].shared[s]=updates.shared[s]}else users[u].shared[s]=updates.shared[s]}}}}let message={route:"receiveSessionUpdates",args:null};for(const u in users){message.args=[u,users[u]];if(this.users[u].send)this.users[u].send(JSON.stringify(message));this.setState({[u]:Object.create(message)})}return users};this.receiveSessionUpdates=(origin,update)=>{if(update){if(typeof update==="string")update=JSON.parse(update)}if(typeof update==="object"){let user=this.users[origin];if(!user)return void 0;if(!user.sessions)user.sessions={};if(update.private){for(const key in update.private){if(!user.sessions[key])continue;this.recursivelyAssign(user.sessions[key].data,update.private[key].data);if(user.sessions[key].onmessage)user.sessions[key].onmessage(user.sessions[key],user._id)}}if(update.shared){for(const key in update.shared){if(!user.sessions[key])continue;if(update.shared[key].settings.users)user.sessions[key].settings.users=update.shared[key].settings.users;if(update.shared[key].settings.host)user.sessions[key].settings.host=update.shared[key].settings.host;if(update.shared[key].data.private)this.recursivelyAssign(user.sessions[key].data.private,update.shared[key].data.private);if(update.shared[key].data.shared)this.recursivelyAssign(user.sessions[key].data.shared,update.shared[key].data.shared);if(user.sessions[key].onmessage)user.sessions[key].onmessage(user.sessions[key],user._id)}}return user}};this.getUpdatedUserData=user=>{const updateObj={};for(const key in user.sessions){let s=user.sessions[key];if(s.settings.users[user._id]||s.settings.source===user._id){if(!s.settings.spectators?.[user._id]){if(s.settings.host===user._id){for(const prop in s.settings.hostprops){if(!updateObj[prop]&&prop in user){if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}else{for(const prop in s.settings.propnames){if(!updateObj[prop]&&user[prop]!==void 0){if(s.settings.source){if(typeof user[prop]==="object"&&prop in s.data){if(stringifyFast(s.data[prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data[prop]!==user[prop])updateObj[prop]=user[prop]}else{if(s.data.shared?.[user._id]&&prop in s.data.shared?.[user._id]){if(typeof user[prop]==="object"){if(stringifyFast(s.data.shared[user._id][prop])!==stringifyFast(user[prop]))updateObj[prop]=user[prop]}else if(s.data.shared[user._id][prop]!==user[prop])updateObj[prop]=user[prop]}else updateObj[prop]=user[prop]}}}}}}}return updateObj};this.userUpdateCheck=user=>{if(user.sessions){const updateObj=this.getUpdatedUserData(user);if(Object.keys(updateObj).length>0){let message={route:"setUserProps",args:[user._id,updateObj]};if(user.send)user.send(message);this.setState({[user._id]:message});return updateObj}}return void 0};this.setUserProps=(user,props)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(props){if(typeof props==="string"){props=JSON.parse(props)}}this.recursivelyAssign(user,props);return true};this.STREAMLATEST=0;this.STREAMALLLATEST=1;this.streamSettings={};this.streamFunctions={allLatestValues:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop.slice(setting.lastRead);setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p].slice(setting[p].lastRead);setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}if(Object.keys(result).length===0)result=void 0}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result},latestValue:(prop,setting)=>{let result=void 0;if(Array.isArray(prop)){if(prop.length!==setting.lastRead){result=prop[prop.length-1];setting.lastRead=prop.length}}else if(typeof prop==="object"){result={};for(const p in prop){if(Array.isArray(prop[p])){if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(prop[p].length!==setting[p].lastRead){result[p]=prop[p][prop[p].length-1];setting[p].lastRead=prop[p].length}}else{if(typeof setting==="number")setting={[p]:{lastRead:void 0}};else if(!setting[p])setting[p]={lastRead:void 0};if(setting[p].lastRead!==prop[p]){result[p]=prop[p];setting[p].lastRead=prop[p]}}}}else{if(setting.lastRead!==prop){result=prop;setting.lastRead=prop}}return result}};this.setStreamFunc=(name,key,callback=this.streamFunctions.allLatestValues)=>{if(!this.streamSettings[name].settings[key])this.streamSettings[name].settings[key]={lastRead:0};if(callback===this.STREAMLATEST)this.streamSettings[name].settings[key].callback=this.streamFunctions.latestValue;else if(callback===this.STREAMALLLATEST)this.streamSettings[name].settings[key].callback=this.streamFunctions.allLatestValues;else if(typeof callback==="string")this.streamSettings[name].settings[key].callback=this.streamFunctions[callback];else if(typeof callback==="function")this.streamSettings[name].settings[key].callback=callback;if(!this.streamSettings[name].settings[key].callback)this.streamSettings[name].settings[key].callback=this.streamFunctions.allLatestValues;return true};this.addStreamFunc=(name,callback=data=>{})=>{this.streamFunctions[name]=callback};this.setStream=(object={},settings={},streamName=`stream${Math.floor(Math.random()*1e10)}`,onupdate,onclose)=>{if(settings.keys){if(settings.keys.length===0){let k=Object.keys(object);if(k.length>0){settings.keys=Array.from(k)}}}else{settings.keys=Array.from(Object.keys(object))}this.streamSettings[streamName]={object,settings,onupdate,onclose};this.subscribe(streamName,res=>{if(this.streamSettings[streamName].onupdate)this.streamSettings[streamName].onupdate(res,this.streamSettings[streamName])});settings.keys.forEach(prop=>{if(settings[prop]?.callback)this.setStreamFunc(streamName,prop,settings[prop].callback);else this.setStreamFunc(streamName,prop,settings.callback)});return this.streamSettings[streamName]};this.removeStream=(streamName,key)=>{if(streamName&&!key){if(this.streamSettings[streamName].onclose)this.streamSettings[streamName].onclose(this.streamSettings[streamName]);this.unsubscribe(streamName);delete this.streamSettings[streamName]}else if(key&&this.streamSettings[streamName]?.settings?.keys){let idx=this.streamSettings[streamName].settings.keys.indexOf(key);if(idx>-1)this.streamSettings[streamName].settings.keys.splice(idx,1);if(this.streamSettings[streamName].settings[key])delete this.streamSettings[streamName].settings[key];return true}return false};this.updateStreamData=(streamName,data={})=>{if(this.streamSettings[streamName]){Object.assign(this.streamSettings[streamName].object,data);return this.streamSettings[streamName].object}return false};this.getStreamUpdate=streamName=>{if(!this.streamSettings[streamName])return;let streamUpdate={};this.streamSettings[streamName].settings.keys.forEach(key=>{if(this.streamSettings[streamName].settings[key]){let data=this.streamSettings[streamName].settings[key].callback(this.streamSettings[streamName].object[key],this.streamSettings[streamName].settings[key]);if(data!==void 0)streamUpdate[key]=data}});this.setState({[streamName]:streamUpdate});return streamUpdate};this.getAllStreamUpdates=()=>{let updateObj={};for(const streamName in this.streamSettings){let streamUpdate=this.getStreamUpdate(streamName);Object.assign(updateObj,streamUpdate)}return updateObj};this.streamLoop={__operator:this.getAllStreamUpdates,__node:{loop:10}};this.userUpdateLoop={__operator:this.userUpdateCheck,__node:{loop:10}};this.sessionLoop={__operator:this.sessionUpdateCheck,__node:{loop:10}};this.setLoaders(loaders);this.setTree(this);if(users)this.users=users}getFirstMatch(obj1,obj2){for(const i in obj1){for(const j in obj2){if(i===j)return i}}return false}};var Router=class extends Service{constructor(options){super(options);this.name="router";this.connections={};this.sources={};this.services={};this.serviceConnections={};this.users={};this.addUser=async(info,connections,config,receiving)=>{if(!info._id){info._id=`user${Math.floor(Math.random()*1e15)}`}let user=Object.assign({},info);if(connections){for(const key in connections){if(typeof connections[key]==="object"){if(!connections[key].connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connections[key].connection._id){if(performance.now()-start>3e3){delete connections[key];rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}}}for(const key in connections){connections[key]=this.addConnection(connections[key],user._id)}}if(config){for(const c in config){this.openConnection(config[c].service,config[c],user._id,config[c].args)}}let send=(message,...a)=>{let connection=this.getConnection(user._id,"send");if(connection?.send)return connection.send(message,...a)};let request=(message,method,...a)=>{let connection=this.getConnection(user._id,"request");if(connection?.request)return connection.request(message,method,...a)};let post=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"post");if(connection?.post)return connection.post(route,args,method,...a)};let run=(route,args,method,...a)=>{let connection=this.getConnection(user._id,"run");if(connection?.run)return connection.run(route,args,method,...a)};let subscribe=(route,callback,...a)=>{let connection=this.getConnection(user._id,"subscribe");if(connection?.subscribe)return connection.subscribe(route,callback,...a)};let unsubscribe=(route,sub,...a)=>{let connection=this.getConnection(user._id,"unsubscribe");if(connection?.unsubscribe)return connection.unsubscribe(route,sub,...a)};let terminate=()=>{return this.removeUser(user)};user.send=send;user.request=request;user.post=post;user.run=run;user.subscribe=subscribe;user.unsubscribe=unsubscribe;user.terminate=terminate;this.users[user._id]=user;if(connections&&!receiving){let connectionIds={};let pass=false;Object.keys(connections).map((k,i)=>{if(connections[k]?._id){connectionIds[`${i}`]=connections[k]?._id;pass=true}});if(pass){user.send({route:"addUser",args:[{_id:user._id},connectionIds,void 0,true]})}}return user};this.getConnection=(sourceId,hasMethod)=>{if(this.sources[sourceId]){if(this.order){for(let i=0;i{if(this.sources[sourceId]){if(!props&&!hasMethod)return this.sources[sourceId];let found={};for(const key in this.sources[sourceId]){if(typeof this.sources[sourceId][key]==="object"){if(!this.sources[sourceId][key]._id){for(const k in this.sources[sourceId][key]){if(typeof this.sources[sourceId][key][k]==="object"){let pass=true;if(hasMethod&&!this.sources[sourceId][key][k][hasMethod])pass=false;for(const p in props){if(typeof this.sources[sourceId][key][k][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][k][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][k][p]!==props[p]){pass=false}else{pass=false;break}}if(pass){found[this.sources[sourceId][key][k]._id]=this.sources[sourceId][key][k]}}}}else{let pass=true;if(hasMethod&&!this.sources[sourceId][key][hasMethod])pass=false;for(const p in props){if(typeof this.sources[sourceId][key][p]==="object"&&typeof props[p]==="object"){for(const pp in props[p]){if(props[p][pp]!==this.sources[sourceId][key][p][pp]){pass=false;break}}}else if(this.sources[sourceId][key][p]!==props[p]){pass=false}else{pass=false;break}}if(pass){if(this.getConnection(this.sources[sourceId][key],hasMethod))found[this.sources[sourceId][key]._id]=this.sources[sourceId][key]}}}}}};this.addConnection=(options,source)=>{let settings={};if(typeof options==="string"){if(this.connections[options]){options=this.connections[options]}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][options]){options={connection:this.serviceConnections[j][k][options]};options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}if(typeof options==="string"&&this.__node.nodes.get(options))options={connection:this.__node.nodes.get(options)}}if(!options||typeof options==="string")return void 0;if(source)settings.source=source;if(options.connection instanceof GraphNode){settings.connection=options.connection;let node=settings.connection;settings.send=async message=>{if(message.method){if(Array.isArray(message.args)){return node[message.method]?.(...message.args)}else return node[message.method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.request=async(message,method)=>{if(method){if(Array.isArray(message.args)){return node[method]?.(...message.args)}else return node[method]?.(message.args)}else{if(!node.__operator)return;if(Array.isArray(message.args)){return node.__operator(...message.args)}else return node.__operator(message.args)}};settings.post=async(route,args,method)=>{if(route&&node.__node.graph.get(route)){let n=node.__node.graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.__operator(...args)}else return n.__operator(args)}}else{if(method){if(Array.isArray(args)){return node[method]?.(...args)}else return node[method]?.(args)}else{if(Array.isArray(args)){return node.__operator(...args)}else return node.__operator(args)}}};settings.run=settings.post;settings.subscribe=async callback=>{return node.__subscribe(callback)};settings.unsubscribe=async sub=>{return node.__unsubscribe(sub)};settings.terminate=()=>{node.__node.graph.remove(node);return true};settings.onclose=options.onclose;if(settings.onclose){node.__addOndisconnected(n=>{if(settings.onclose)settings.onclose(settings,n)})}}else if(options.connection instanceof Graph){if(options.connection.__node.nodes.get("open"))settings.service=options.connection;let graph=settings.connection;settings.send=async message=>{if(Array.isArray(message.args))graph.run(message.route,...message.args);else graph.run(message.route,message.args)};settings.request=async(message,method)=>{if(!message.route)return void 0;if(method){if(Array.isArray(message.args)){return graph.__node.nodes.get(message.route)[method]?.(...message.args)}else return graph.__node.nodes.get(message.route)[method]?.(message.args)}else{if(Array.isArray(message.args)){return graph.run(message.route,...message.args)}else return graph.run(message.route,message.args)}};settings.post=async(route,args,method)=>{if(route&&graph.get(route)){let n=graph.get(route);if(method){if(Array.isArray(args)){return n[method]?.(...args)}else return n[method]?.(args)}else{if(Array.isArray(args)){return n.run(...args)}else return n.run(args)}}};settings.run=settings.post;settings.subscribe=async(route,callback)=>{return graph.subscribe(route,callback)};settings.unsubscribe=async(route,sub)=>{return graph.unsubscribe(route,sub)};settings.terminate=n=>{graph.remove(n);return true}}else if(!(options._id&&this.connections[options._id])){let c=options.connection;if(typeof c==="string"){if(this.connections[c])c=this.connections[c];else if(options.service){if(typeof options.service==="string"){options.service=this.services[options.service]}if(typeof options.service==="object"){if(options.service.connections){for(const key in options.service.connections){if(options.service.connections[key][c]){c=options.service.connections[key][c];settings.connectionType=key;settings.connectionsKey=c;break}}}}}else{for(const j in this.serviceConnections){for(const k in this.serviceConnections[j]){if(this.serviceConnections[j][k][c]){c=this.serviceConnections[j][k][c];options.service=j;settings.connectionType=j;settings.connectionsKey=k;break}}}}}if(typeof c!=="object")return void 0;settings._id=c._id;settings.send=c.send;settings.request=c.request;settings.run=c.run;settings.post=c.post;settings.subscribe=c.subscribe;settings.unsubscribe=c.unsubscribe;settings.terminate=c.terminate;settings.onclose=options.onclose;if(settings.onclose){if(!(c.onclose&&settings.onclose.toString()===c.onclose.toString())){let oldonclose=c.onclose;c.onclose=(...args)=>{if(settings.onclose)settings.onclose(settings,...args);if(this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}}else{let oldonclose=c.onclose;c.onclose=(...args)=>{this.removeConnection(settings);if(this.users[settings.source]&&Object.keys(this.sources[settings.source]).length===0){this.removeUser(settings.source,false)}if(oldonclose)oldonclose(...args)}}if(options.service){if(typeof options.service==="string")options.service=this.services[options.service];settings.service=options.service}else if(c.graph)settings.service=c.graph}if(!settings.source&&options.source){settings.source=options.source}else if(!settings.source&&options.service){settings.source=typeof options.service==="object"?options.service?.name:void 0}else if(!settings.source&&(settings.connection instanceof GraphNode||settings.connection instanceof Graph)){settings.source="local";if(!this.order.indexOf("local"))this.order.unshift("local")}if(!settings._id)settings._id=`connection${Math.floor(Math.random()*1e15)}`;if(settings.source){if(!this.sources[settings.source])this.sources[settings.source]={};this.sources[settings.source][settings._id]=settings}if(!this.connections[settings._id])this.connections[settings._id]=settings;return settings};this.removeConnection=(connection,terminate=false)=>{if(typeof connection==="object"&&connection._id)connection=connection._id;if(typeof connection==="string"){if(this.connections[connection]){if(terminate&&this.connections[connection])this.connections[connection].terminate();delete this.connections[connection];for(const key in this.sources){if(this.sources[key][connection])delete this.sources[key][connection];else{for(const k in this.sources[key]){if(this.sources[key][k]?.[connection]){delete this.sources[key][connection]}}}}return true}else if(this.sources[connection]){for(const key in this.sources[connection]){this.removeConnection(this.sources[connection][key],terminate)}return true}}};this.routeService=(service,connections,source,order)=>{this.services[service.name]=service;if(service.__node?.nodes)this.__node.nodes.forEach((n,k)=>{if(!service.__node?.nodes.get(k)){service.__node?.nodes.set(k,n)}else service.__node?.nodes.set(this.name+"."+k,n)});if(service.users)service.users=this.users;if(connections){if(typeof connections==="string")this.addServiceConnections(service,connections,source);else{for(const c in connections){this.addServiceConnections(service,c,source)}}}if(order)this.order=order;else{if(!this.order)this.order=[];this.order.push(service.name)}};this.addServiceConnections=(service,connectionsKey,source)=>{if(typeof service==="string"){service=this.services[service]}if(connectionsKey&&service[connectionsKey]){let newConnections={};if(!this.serviceConnections[service.name])this.serviceConnections[service.name]={};this.serviceConnections[service.name][connectionsKey]=service[connectionsKey];for(const key in service[connectionsKey]){if(!this.connections[key]){newConnections[key]=this.addConnection({connection:service[connectionsKey][key],service},source);newConnections[key].connectionType=connectionsKey}}return newConnections}};this.openConnection=async(service,options,source,...args)=>{if(typeof service==="string"){service=this.services[service]}if(service?.__node.nodes){let connection=service.run("open",options,...args);if(connection instanceof Promise){return connection.then(async info=>{if(!info._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!info._id){if(performance.now()-start>3e3){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}if(info._id)this.addConnection({connection:info,service},source)})}else if(connection){if(!connection._id){await new Promise((res,rej)=>{let start=performance.now();let checker=()=>{if(!connection._id){if(performance.now()-start>3e3){rej(false)}else{setTimeout(()=>{checker()},100)}}else{res(true)}};checker()}).catch(er=>{console.error("Connections timed out:",er)})}if(connection._id)return this.addConnection({connection,service},source)}}};this.terminate=connection=>{if(typeof connection==="string")connection=this.connections[connection];return connection.terminate()};this.subscribeThroughConnection=(route,relay,endpoint,callback,...args)=>{if(typeof relay==="string"){relay=this.getConnection(relay,"run")}if(typeof relay==="object")return new Promise((res,rej)=>{relay.run("routeConnections",[route,endpoint,relay._id,...args]).then(sub=>{this.__node.state.subscribeTrigger(endpoint,res2=>{if(res2?.callbackId===route){if(!callback)this.setState({[endpoint]:res2.args});else if(typeof callback==="string"){this.setState({[callback]:res2.args})}else callback(res2.args)}});res(sub)}).catch(rej)})};this.routeConnections=(route,transmitter,receiver,...args)=>{let rxsrc;if(typeof receiver==="string"){if(this.sources[receiver]){rxsrc=receiver}receiver=this.getConnection(receiver,"send")}if(typeof transmitter==="string"){transmitter=this.getConnection(transmitter,"subscribe")}if(transmitter?.subscribe&&receiver?.send){let res=new Promise((res2,rej)=>{transmitter.subscribe(route,transmitter._id,res3=>{if(!this.connections[receiver._id]&&rxsrc){if(this.sources[rxsrc]){rxsrc=receiver;Object.keys(this.sources[rxsrc]).forEach(k=>{if(this.sources[receiver][k].send){receiver=this.sources[receiver][k]}})}}if(this.connections[receiver._id])receiver.send({callbackId:route,args:res3})},...args).then(sub=>{res2(sub)})});return res}};this.setUserData=(user,data)=>{if(user){if(typeof user==="string"){user=this.users[user];if(!user)return false}}if(data){if(typeof data==="string"){data=JSON.parse(data)}}if(typeof data==="object"){this.recursivelyAssign(user,data);return true}};this.setTree(this);if(options){if(options.order)this.order=options.order;if(options.graph){for(const key in options.graph){let opt=options.graph[key];if(typeof opt==="function")opt=new opt;if(opt?.__node?.nodes){opt.name=key;opt.__node.tag=key;this.addServices({[opt.name]:opt});this.routeService(opt,opt.connections)}else{if(typeof opt?.service==="function")opt.service=new opt.service;if(opt?.service?.__node?.nodes){opt.service.name=key;opt.service.__node.tag=key;this.addServices({[opt.service.name]:opt.service});this.routeService(opt.service)}if(typeof opt?.service==="object"){if(opt.connections){if(Array.isArray(opt.connections)){opt.connections.forEach(k=>{this.addServiceConnections(opt[key].service,k)})}else this.addServiceConnections(opt.service,opt.connections)}if(opt.config){for(const c in opt.config){this.openConnection(opt.service,opt.config[c],opt.config[c].source,opt.config[c].args)}}}}}}}}removeUser(profile,terminate){if(terminate)this.removeConnection(profile,terminate);if(typeof profile==="string")profile=this.users[profile];if(typeof profile==="object"&&profile._id){delete this.users[profile._id];if(profile.onclose)profile.onclose(profile)}return true}};0&&(module.exports={CMDService,E2EEService,ECSService,Graph,GraphNode,HTTPbackend,Router,SSEbackend,Service,SessionsService,WSSbackend,animate,backprop,bindListener,branching,getAllProperties,instanceObject,isNativeClass,isTypedArray,loaders,loop,recursivelyAssign,spliceTypedArray,state,substitute__operator,transformListenerResult,triggerListenerOncreate,unsafeRoutes}); diff --git a/dist/loaders/Loaders.d.ts b/dist/loaders/Loaders.d.ts new file mode 100644 index 00000000..74eb85d5 --- /dev/null +++ b/dist/loaders/Loaders.d.ts @@ -0,0 +1,67 @@ +import { GraphNode, Graph, GraphNodeProperties } from "../Graph"; +/** + * setting nodeA.__node.backward:true propagates operator results to parent + */ +export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** + * + * Specify a timer loop, will stop when node is popped or nodeA.__node.isLooping is set false + * nodeA.__node.loop = 100 will loop the operator every 100 milliseconds + * + * Or + * nodeA.__node.delay will delay the operator by specified millisecond number and resolve the result as a promise + * nodeA.__node.frame will use requestAnimationFrame to call the function and resolve the result as a promise + * + * Use in combination with: + * nodeA.__node.repeat will repeat the operator the specified number of times + * nodeA.__node.recursive will do the same as repeat but will pass in the previous operator call's results + * + * + */ +export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Animations + * + * nodeA.__node.animate = true | () => void, to run the operator or a specified animation function on loop + * + */ +export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Branching operations + * + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * + * nodeA.__listeners['nodeB.x'] = { + * callback:(result)=>void, + * branch:{if:Function|any, then:Function|any|GraphNode} + * } + * + */ +export declare const branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Trigger listeners oncreate with specific arguments + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } + * + */ +export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Trigger listeners oncreate with specific arguments + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } + * + */ +export declare const bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } + * + */ +export declare const transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +export declare const substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; +export declare const loaders: { + backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; +}; diff --git a/dist/src/loaders/html/html.loader.d.ts b/dist/loaders/html/html.loader.d.ts similarity index 60% rename from dist/src/loaders/html/html.loader.d.ts rename to dist/loaders/html/html.loader.d.ts index 3bb97ea3..84628aee 100644 --- a/dist/src/loaders/html/html.loader.d.ts +++ b/dist/loaders/html/html.loader.d.ts @@ -1,13 +1,13 @@ -import { GraphNode, GraphNodeProperties, Graph } from '../../core/Graph'; -export type HTMLNodeProperties = GraphNodeProperties & { +import { GraphNode, GraphNodeProperties, Graph } from '../../Graph'; +export declare type HTMLNodeProperties = GraphNodeProperties & { __props?: HTMLElement; __onresize?: (elm: HTMLElement) => void; __onremove?: (elm: HTMLElement) => void; __onrender?: (elm: HTMLElement) => void; tagName?: string; - parentNode?: string | HTMLElement; + parentNode?: string; style?: Partial; - __template?: string | ((...args: any[]) => string); + __template?: string; __renderonchanged?: (elm: HTMLElement) => void; useShadow?: boolean; __css?: string; @@ -16,4 +16,4 @@ export type HTMLNodeProperties = GraphNodeProperties & { [key: string]: any; }; }; -export declare const htmlloader: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; +export declare const htmlloader: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, tree: any, properties: GraphNodeProperties, key: string) => void; diff --git a/src/extras/dist/src/loaders/index.d.ts b/dist/loaders/index.d.ts similarity index 84% rename from src/extras/dist/src/loaders/index.d.ts rename to dist/loaders/index.d.ts index 229b9ec7..6e6983f2 100644 --- a/src/extras/dist/src/loaders/index.d.ts +++ b/dist/loaders/index.d.ts @@ -1,4 +1,4 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; +import { GraphNode, Graph, GraphNodeProperties } from "../Graph"; /** * setting nodeA.__node.backward:true propagates operator results to parent */ @@ -31,15 +31,11 @@ export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: G export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; /** Branching operations * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} * * nodeA.__listeners['nodeB.x'] = { * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } + * branch:{if:Function|any, then:Function|any|GraphNode} * } * */ @@ -50,7 +46,7 @@ export declare const branching: (node: GraphNode, parent: GraphNode | Graph, gra * */ export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Bind listeners to a specific object instead of the node that owns it +/** Trigger listeners oncreate with specific arguments * * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } * diff --git a/dist/services/EventHandler.d.ts b/dist/services/EventHandler.d.ts new file mode 100644 index 00000000..b6f54f38 --- /dev/null +++ b/dist/services/EventHandler.d.ts @@ -0,0 +1,17 @@ +export declare class EventHandler { + pushToState: {}; + data: {}; + triggers: {}; + constructor(data?: { + [key: string]: any; + }); + setState: (updateObj: { + [key: string]: any; + }) => {}; + setValue: (key: any, value: any) => void; + subscribeTrigger: (key: string, onchange: (res: any) => void) => number; + unsubscribeTrigger: (key: string, sub?: number) => boolean; + subscribeTriggerOnce: (key: string, onchange: (res: any) => void) => void; + getTrigger: (key: any, sub: any) => any; + onRemoved: any; +} diff --git a/src/extras/dist/services/Service.d.ts b/dist/services/Service.d.ts similarity index 74% rename from src/extras/dist/services/Service.d.ts rename to dist/services/Service.d.ts index a5558998..f9db7452 100644 --- a/src/extras/dist/services/Service.d.ts +++ b/dist/services/Service.d.ts @@ -1,27 +1,21 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export type ServiceMessage = { +import { Graph, GraphNode, GraphOptions } from "../Graph"; +export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export declare type ServiceMessage = { route?: string; args?: any; method?: string; node?: string | GraphNode; [key: string]: any; }; -export type ServiceOptions = GraphOptions & { +export declare type ServiceOptions = GraphOptions & { services?: { [key: string]: Service | Function | { [key: string]: any; }; }; - restrict?: { - [key: string]: boolean; - }; }; export declare class Service extends Graph { name: string; - restrict?: { - [key: string]: boolean; - }; constructor(options?: ServiceOptions); addServices: (services: { [key: string]: Function | Graph | Service | { @@ -33,7 +27,7 @@ export declare class Service extends Graph { handleGraphNodeCall(route: string | GraphNode, args: any): any; transmit: (...args: any[]) => any | void; receive: (...args: any[]) => any | void; - pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; + pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; terminate: (...args: any) => void; isTypedArray: typeof isTypedArray; @@ -41,8 +35,6 @@ export declare class Service extends Graph { spliceTypedArray: typeof spliceTypedArray; ping: () => string; echo: (...args: any) => any; - log: (...args: any) => boolean; - error: (...args: any) => boolean; } export declare function isTypedArray(x: any): boolean; export declare const recursivelyAssign: (target: any, obj: any) => any; diff --git a/dist/src/services/cmd/CMD.node.d.ts b/dist/services/cmd/CMD.node.d.ts similarity index 82% rename from dist/src/services/cmd/CMD.node.d.ts rename to dist/services/cmd/CMD.node.d.ts index 6cf50902..f4bc5bd1 100644 --- a/dist/src/services/cmd/CMD.node.d.ts +++ b/dist/services/cmd/CMD.node.d.ts @@ -1,9 +1,8 @@ /// -/// import { ChildProcess, Serializable } from 'child_process'; import { Service, ServiceMessage, ServiceOptions } from '../Service'; -import { Graph, GraphNode, GraphNodeProperties } from '../../core/Graph'; -export type CMDRoute = { +import { Graph, GraphNode, GraphNodeProperties } from '../../Graph'; +export declare type CMDRoute = { command: string | ChildProcess; args?: string[]; options?: { @@ -18,7 +17,7 @@ export type CMDRoute = { onerror?: (error: Error) => void; onclose?: (code: number | null, signal: NodeJS.Signals | null) => void; } & GraphNodeProperties; -export type CMDInfo = { +export declare type CMDInfo = { process: ChildProcess; _id: string; controller: AbortController; @@ -26,7 +25,7 @@ export type CMDInfo = { request: (message: ServiceMessage | any, method?: string) => Promise; post: (route: string, args: any, method?: string) => boolean; run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => number; + subscribe: (route: any, callback?: ((res: any) => void) | string) => number; unsubscribe: (route: any, sub: number) => Promise; } & CMDRoute; export declare class CMDService extends Service { @@ -41,7 +40,7 @@ export declare class CMDService extends Service { processes: any; }; subprocessloader: { - process: (node: CMDRoute & GraphNode, parent: GraphNode, graph: Graph, roots: any, properties: any) => void; + process: (node: CMDRoute & GraphNode, parent: GraphNode, graph: Graph, tree: any, properties: any) => void; }; constructor(options?: ServiceOptions); createProcess: (properties: CMDRoute) => CMDRoute; @@ -50,6 +49,6 @@ export declare class CMDService extends Service { send: (childprocess: ChildProcess, data: Serializable) => boolean; request: (message: ServiceMessage | any, processId: string, method?: string) => Promise; runRequest: (message: any, callbackId: string | number, childprocess?: ChildProcess | string) => any; - subscribeProcess(route: string, childprocess: ChildProcess | string, args?: any[], key?: string, subInput?: boolean): number; - subscribeToProcess(route: string, processId: string, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean): any; + subscribeProcess(route: string, childprocess: ChildProcess | string, key?: string, subInput?: boolean): any; + subscribeToProcess(route: string, processId: string, callback?: ((res: any) => void) | string, key?: string, subInput?: boolean): any; } diff --git a/dist/services/dom/DOM.service.d.ts b/dist/services/dom/DOM.service.d.ts new file mode 100644 index 00000000..27b66e53 --- /dev/null +++ b/dist/services/dom/DOM.service.d.ts @@ -0,0 +1,41 @@ +import { DOMElement } from "./DOMElement"; +import { Graph, GraphNode } from '../../Graph'; +import { Service, ServiceOptions } from "../Service"; +import { CompleteOptions, ElementInfo, ElementProps, ComponentProps, ComponentInfo, CanvasElementProps, CanvasOptions, CanvasElementInfo } from './types/index'; +export declare type DOMRouteProp = ElementProps | ComponentProps | CanvasElementProps; +export declare class DOMService extends Service { + loadDefaultRoutes: boolean; + keepState: boolean; + parentNode: HTMLElement; + name: string; + interpreters: { + md: (template: string, options: ComponentProps) => void; + jsx: (template: any, options: ComponentProps) => void; + }; + domloader: { + dom: (r: DOMRouteProp & GraphNode, parent: GraphNode & DOMRouteProp, graph: Graph, tree: any, props: any, key: string) => void; + }; + constructor(options?: ServiceOptions, parentNode?: HTMLElement, interpreters?: { + [key: string]: (template: string, options: ComponentProps) => void; + }); + elements: { + [key: string]: ElementInfo; + }; + components: { + [key: string]: ComponentInfo | CanvasElementInfo; + }; + templates: { + [key: string]: ComponentProps | CanvasElementProps; + }; + addElement: (options: ElementProps, generateChildElementNodes?: boolean) => ElementInfo; + createElement: (options: ElementProps) => HTMLElement; + updateOptions: (options: any, element: any) => CompleteOptions; + resolveParentNode: (elm: any, parentNode: any, options: any, oncreate?: any) => void; + resolveGraphNode: (element: any, options: any) => GraphNode & DOMRouteProp; + addComponent: (options: ComponentProps, generateChildElementNodes?: boolean) => ComponentInfo; + addCanvasComponent: (options: CanvasOptions) => CanvasElementInfo; + terminate: (element: string | DOMElement | HTMLElement | ComponentInfo | CanvasElementInfo) => boolean; +} +/** + * Usage + */ diff --git a/dist/src/loaders/html/DOMElement.d.ts b/dist/services/dom/DOMElement.d.ts similarity index 61% rename from dist/src/loaders/html/DOMElement.d.ts rename to dist/services/dom/DOMElement.d.ts index f0ad10a8..538004c8 100644 --- a/dist/src/loaders/html/DOMElement.d.ts +++ b/dist/services/dom/DOMElement.d.ts @@ -1,22 +1,27 @@ + +//todo: make this the permanent version so I can stop copying manually each build export function addCustomElement(cls: any, tag: any, extend?: any): void; export function randomId(tag?: string): string; export function parseFunctionFromText(method: any): any; export class DOMElement extends HTMLElement { static get tag(): string; static addElement(tag?: string, cls?: typeof DOMElement, extend?: any): void; + template: ((self: DOMElement, props: any) => (string|HTMLElement)) | string | HTMLElement; + props: {[key:string]:any}; useShadow: boolean; + styles: string; + oncreate: ((self: DOMElement, props: any) => void); + onresize: ((self: DOMElement, props: any) => void)|any; + ondelete: ((self: DOMElement, props: any) => void); + onchanged: ((self: DOMElement, props: any) => void); + renderonchanged: boolean | ((self: DOMElement, props: any) => void); FRAGMENT: any; STYLE: any; attachedShadow: boolean; obsAttributes: string[]; - props: {}; + get observedAttributes(): string[]; attributeChangedCallback: (name: any, old: any, val: any) => void; - onchanged: any; - ONRESIZE: ((ev: any) => void) | ((ev: any) => void); - ondelete: (() => void) | ((props?: {}) => void); - oncreate: any; - renderonchanged: number; - template: any; + ONRESIZE: (ev: any) => void; connectedCallback(): void; delete: () => void; render: (props?: {}) => void; diff --git a/dist/services/dom/html.loader.d.ts b/dist/services/dom/html.loader.d.ts new file mode 100644 index 00000000..b7ad251f --- /dev/null +++ b/dist/services/dom/html.loader.d.ts @@ -0,0 +1,17 @@ +import { GraphNode, GraphNodeProperties, Graph } from '../../Graph'; +export declare type HTMLNodeProperties = GraphNodeProperties & { + __props?: HTMLElement; + __onresize?: (elm: HTMLElement) => void; + __onremove?: (elm: HTMLElement) => void; + __onrender?: (elm: HTMLElement) => void; + tagName?: string; + __template?: string; + __renderonchanged?: (elm: HTMLElement) => void; + useShadow?: boolean; + __css?: string; + __element?: string | HTMLElement; + __attributes?: { + [key: string]: any; + }; +}; +export declare const htmlloader: (node: GraphNode, parent: GraphNode | Graph, graph: Graph, tree: any, properties: GraphNodeProperties, key: string) => void; diff --git a/dist/services/dom/types/canvascomponent.d.ts b/dist/services/dom/types/canvascomponent.d.ts new file mode 100644 index 00000000..af4341d4 --- /dev/null +++ b/dist/services/dom/types/canvascomponent.d.ts @@ -0,0 +1,66 @@ +import { ComponentProps } from "./component"; +import { DOMElement } from "../DOMElement"; +import { Graph, GraphNode, GraphNodeProperties } from "../../../Graph"; +import { ElementProps } from "./element"; +export declare type CanvasElementProps = GraphNodeProperties & { + tagName?: string; + parentNode?: string | HTMLElement; + styles?: string; + onchanged?: (props: any) => void; + id?: string; + canvas?: HTMLCanvasElement; + context: '2d' | 'webgl' | 'webgl2' | 'bitmaprenderer' | 'experimental-webgl' | 'xrpresent' | RenderingContext; + draw: ((element: DOMElement, info: CanvasElementInfo) => void); + width?: string; + height?: string; + onrender?: (element: DOMElement, info?: CanvasElementInfo) => void; + onresize?: (element: DOMElement, info?: CanvasElementInfo) => void; + onremove?: (element: DOMElement, info?: CanvasElementInfo) => void; + renderonchanged?: boolean | ((element: DOMElement, info?: CanvasElementInfo) => void); + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph | ComponentProps | ElementProps | CanvasElementProps; + }; +}; +export declare type CanvasElementInfo = { + element: DOMElement & { + canvas: HTMLCanvasElement; + context: RenderingContext; + }; + draw: ((element: DOMElement, info: CanvasElementInfo) => void); + canvas: HTMLCanvasElement; + context: RenderingContext; + animating: boolean; + animation: any; + width?: string; + height?: string; + style?: string; + class: any; + node: GraphNode; +} & CanvasElementProps; +export declare type CanvasOptions = { + element: DOMElement & { + canvas: HTMLCanvasElement; + context: RenderingContext; + } | HTMLElement; + tagName?: string; + canvas?: HTMLCanvasElement; + context: '2d' | 'webgl' | 'webgl2' | 'bitmaprenderer' | 'experimental-webgl' | 'xrpresent' | RenderingContext; + draw: ((element: DOMElement, info: CanvasElementInfo) => void); + width?: string; + height?: string; + style?: Partial; + parentNode?: string | HTMLElement; + styles?: string; + onrender?: (element: DOMElement, info?: CanvasElementInfo) => void; + onresize?: (element: DOMElement, info?: CanvasElementInfo) => void; + onremove?: (element: DOMElement, info?: CanvasElementInfo) => void; + onchanged?: (props: any) => void; + renderonchanged?: boolean | ((element: DOMElement, info?: CanvasElementInfo) => void); + props?: { + [key: string]: any; + }; + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph | ComponentProps | ElementProps | CanvasElementProps; + }; + id?: string; +} & GraphNodeProperties; diff --git a/dist/services/dom/types/component.d.ts b/dist/services/dom/types/component.d.ts new file mode 100644 index 00000000..c426f21b --- /dev/null +++ b/dist/services/dom/types/component.d.ts @@ -0,0 +1,51 @@ +import { DOMElement } from "../DOMElement"; +import { Graph, GraphNode, GraphNodeProperties } from "../../../Graph"; +import { ElementProps } from "./element"; +import { CanvasElementProps } from "./canvascomponent"; +export declare type ComponentProps = GraphNodeProperties & { + tagName?: string; + template?: string | ((element: DOMElement, props: any) => string | HTMLElement) | HTMLElement; + interpreter?: 'wc' | 'md' | 'jsx'; + parentNode?: string | HTMLElement; + styles?: string; + onrender?: (element: DOMElement, info?: ComponentInfo) => void; + onresize?: (element: DOMElement, info?: ComponentInfo) => void; + ondelete?: (element: DOMElement, info?: ComponentInfo) => void; + onchanged?: (props: any) => void; + renderonchanged?: boolean | ((element: DOMElement, info: ComponentInfo) => void); + innerText?: string; + innerHTML?: string; + id?: string; + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph | ComponentProps | ElementProps | CanvasElementProps; + }; + generateChildElementNodes?: boolean; +}; +export declare type ComponentInfo = { + element: DOMElement; + class: any; + node: GraphNode; + divs?: any[]; +} & ComponentProps; +export declare type ComponentOptions = GraphNodeProperties & { + tagName?: string; + template?: string | ((element: DOMElement, props: any) => string | HTMLElement) | HTMLElement; + parentNode?: string | HTMLElement; + styles?: string; + useShadow?: boolean; + onrender?: (element: DOMElement, info?: ComponentInfo) => void; + onresize?: (element: DOMElement, info?: ComponentInfo) => void; + onremove?: (element: DOMElement, info?: ComponentInfo) => void; + onchanged?: (props: any) => void; + renderonchanged?: boolean | ((element: DOMElement, info: ComponentInfo) => void); + props?: { + [key: string]: any; + }; + innerText?: string; + innerHTML?: string; + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph | ComponentProps | ElementProps | CanvasElementProps; + }; + id?: string; + interpreter?: 'wc' | 'md' | 'jsx'; +}; diff --git a/dist/services/dom/types/element.d.ts b/dist/services/dom/types/element.d.ts new file mode 100644 index 00000000..c109b15e --- /dev/null +++ b/dist/services/dom/types/element.d.ts @@ -0,0 +1,46 @@ +import { Graph, GraphNode, GraphNodeProperties } from "../../../Graph"; +import { CanvasElementProps } from "./canvascomponent"; +import { ComponentProps } from "./component"; +export declare type ElementProps = GraphNodeProperties & { + tagName?: string; + element?: HTMLElement; + style?: Partial; + attributes?: { + [key: string]: any; + }; + parentNode?: string | HTMLElement; + onrender?: (element: HTMLElement, info: ElementInfo) => void; + onresize?: (ev: any, element: HTMLElement, info: ElementInfo) => void; + ondelete?: (element: HTMLElement, info: ElementInfo) => void; + innerText?: string; + innerHTML?: string; + id?: string; + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph | ComponentProps | ElementProps | CanvasElementProps; + }; + generateChildElementNodes?: boolean; +}; +export declare type ElementInfo = { + element: HTMLElement; + node: GraphNode; + parentNode: HTMLElement; + divs: any[]; +} & ElementProps; +export declare type ElementOptions = GraphNodeProperties & { + tagName?: string; + element?: HTMLElement; + style?: Partial; + attributes?: { + [key: string]: any; + }; + parentNode?: string | HTMLElement; + onrender?: (element: HTMLElement, info: ElementInfo) => void; + onresize?: (ev: any, element: HTMLElement, info: ElementInfo) => void; + onremove?: (element: HTMLElement, info: ElementInfo) => void; + innerText?: string; + innerHTML?: string; + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph | ComponentProps | ElementProps | CanvasElementProps; + }; + id?: string; +}; diff --git a/dist/services/dom/types/general.d.ts b/dist/services/dom/types/general.d.ts new file mode 100644 index 00000000..32639327 --- /dev/null +++ b/dist/services/dom/types/general.d.ts @@ -0,0 +1,7 @@ +import { ElementOptions } from './element'; +import { ComponentOptions } from './component'; +import { CanvasOptions } from './canvascomponent'; +export declare type CompleteOptions = { + parentNode: HTMLElement; + id: string; +} & (CanvasOptions | ComponentOptions | ElementOptions); diff --git a/dist/services/dom/types/index.d.ts b/dist/services/dom/types/index.d.ts new file mode 100644 index 00000000..abbc62c5 --- /dev/null +++ b/dist/services/dom/types/index.d.ts @@ -0,0 +1,4 @@ +export * from './canvascomponent'; +export * from './component'; +export * from './element'; +export * from './general'; diff --git a/dist/src/services/e2ee/E2EE.service.d.ts b/dist/services/e2ee/E2EE.service.d.ts similarity index 100% rename from dist/src/services/e2ee/E2EE.service.d.ts rename to dist/services/e2ee/E2EE.service.d.ts diff --git a/src/services/e2ee/sjcl.d.ts b/dist/services/e2ee/sjcl.d.ts similarity index 100% rename from src/services/e2ee/sjcl.d.ts rename to dist/services/e2ee/sjcl.d.ts diff --git a/dist/src/services/ecs/ECS.service.d.ts b/dist/services/ecs/ECS.service.d.ts similarity index 92% rename from dist/src/services/ecs/ECS.service.d.ts rename to dist/services/ecs/ECS.service.d.ts index cb3252b8..aefca013 100644 --- a/dist/src/services/ecs/ECS.service.d.ts +++ b/dist/services/ecs/ECS.service.d.ts @@ -1,11 +1,11 @@ -import { GraphNode, GraphNodeProperties } from '../../core/Graph'; +import { GraphNode, GraphNodeProperties } from '../../Graph'; import { Service, ServiceOptions } from '../Service'; -export type EntityProps = { +export declare type EntityProps = { components: { [key: string]: any; }; } & (GraphNodeProperties | GraphNode); -export type SystemProps = (GraphNodeProperties & { +export declare type SystemProps = (GraphNodeProperties & { __operator: (entities: { [key: string]: Entity; }) => any; @@ -16,13 +16,13 @@ export type SystemProps = (GraphNodeProperties & { }; setupEntity: (entity: Entity) => Entity; }) | GraphNode; -export type Entity = { +export declare type Entity = { components: { [key: string]: any; }; [key: string]: any; } & GraphNode; -export type System = { +export declare type System = { __operator: (entities: { [key: string]: Entity; }) => any; @@ -40,7 +40,7 @@ export type System = { }; entityKeys: string[]; } & GraphNode; -export type ECSOptions = { +export declare type ECSOptions = { entities: { [key: string]: EntityProps; }; diff --git a/dist/src/services/http/HTTP.browser.d.ts b/dist/services/http/HTTP.browser.d.ts similarity index 97% rename from dist/src/services/http/HTTP.browser.d.ts rename to dist/services/http/HTTP.browser.d.ts index 556840b4..e9d49021 100644 --- a/dist/src/services/http/HTTP.browser.d.ts +++ b/dist/services/http/HTTP.browser.d.ts @@ -1,5 +1,5 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type RequestOptions = { +export declare type RequestOptions = { method: string; url: string | URL; data?: Document | string | Blob | BufferSource | FormData | URLSearchParams; diff --git a/dist/src/services/http/HTTP.node.d.ts b/dist/services/http/HTTP.node.d.ts similarity index 64% rename from dist/src/services/http/HTTP.node.d.ts rename to dist/services/http/HTTP.node.d.ts index 5e0dc480..c985f2d4 100644 --- a/dist/src/services/http/HTTP.node.d.ts +++ b/dist/services/http/HTTP.node.d.ts @@ -1,14 +1,10 @@ /// -/// -/// -/// import { Service, ServiceMessage, ServiceOptions } from "../Service"; import * as http from 'http'; import * as https from 'https'; import * as path from 'path'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export * from './boilerplate/index'; -export type ServerProps = { +import { GraphNode, GraphNodeProperties } from "../../Graph"; +export declare type ServerProps = { host: string; port: number; certpath?: string; @@ -18,37 +14,30 @@ export type ServerProps = { errpage?: string; pages?: { [key: 'all' | string]: string | ({ - headers?: { - [key: string]: any; - }; template?: string; onrequest?: GraphNode | string | ((self: HTTPbackend, node: GraphNode, request: http.IncomingMessage, response: http.ServerResponse) => void); redirect?: string; inject?: { - [key: string]: any; - } | any[] | string | ((...args: any) => any); + [key: string]: {} | null; + } | string[] | string | ((...args: any) => any); } & GraphNodeProperties); }; protocol?: 'http' | 'https'; type?: 'httpserver' | string; keepState?: boolean; onopen?: (served: ServerInfo) => void; - onerror?: (er: Error, served: ServerInfo) => void; onclose?: (served: ServerInfo) => void; - onupgrade?: (request: any, socket: any, head: any, served: ServerInfo) => void; - timeout?: number; _id?: string; - debug?: boolean; [key: string]: any; }; -export type ServerInfo = { +export declare type ServerInfo = { server: https.Server | http.Server; address: string; terminate: () => void; graph: HTTPbackend; _id: string; } & ServerProps; -export type ReqOptions = { +export declare type ReqOptions = { protocol: 'http' | 'https' | string; host: string; port: number; @@ -70,15 +59,18 @@ export declare class HTTPbackend extends Service { mimeTypes: { [key: string]: string; }; - constructor(options?: ServiceOptions, settings?: ServerProps); - onStarted: (protocol: 'http' | 'https' | string, host: string, port: number) => void; - setupServer: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => void; - open: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => void; - setupHTTPserver: (options?: (ServerProps & { + constructor(options?: ServiceOptions, settings?: { + host?: string; + port?: number; + protocol?: 'http' | 'https'; certpath?: string; keypath?: string; - passphrase?: string; - }), requestListener?: http.RequestListener, onStarted?: () => void) => Promise; + }); + onStarted: (protocol: 'http' | 'https' | string, host: string, port: number) => void; + setupServer: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => Promise; + open: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => Promise; + setupHTTPserver: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => Promise; + setupHTTPSserver: (options?: ServerProps, requestListener?: http.RequestListener, onStarted?: () => void) => Promise; transmit: (message: any | ServiceMessage, options: string | { protocol: 'http' | 'https' | string; host: string; @@ -100,12 +92,7 @@ export declare class HTTPbackend extends Service { method?: string; served?: ServerInfo; }) => void; - injectPageCode: (templateString: string, url: string, served: ServerInfo) => { - templateString: string; - headers: { - [key: string]: any; - }; - }; + injectPageCode: (templateString: string, url: string, served: ServerInfo) => string; receive: (message: { route: string; args: { @@ -117,11 +104,6 @@ export declare class HTTPbackend extends Service { served?: ServerInfo; redirect?: string; }) => Promise; - responseOnErrorPromiseHandler: (response: http.ServerResponse, reject: any, err: any) => void; - getFailedPromiseHandler: (resolve: any, reject: any, requestURL: any, message: any, response: http.ServerResponse, served: any) => void; - handleBufferedPostBodyPromiseHandler: (resolve: any, body: any, message: any, response: http.ServerResponse, served: any) => void; - onRequestFileReadPromiseHandler: (error: any, content: any, resolve: any, reject: any, requestURL: any, response: http.ServerResponse, message: any, served: ServerInfo) => void; - responsePromiseHandler: (resolve: any, reject: any, message: any, request: http.IncomingMessage, response: http.ServerResponse, method: string, served: ServerInfo) => void; request: (options: ReqOptions | any, send?: any, ondata?: (chunk: any) => void, onend?: () => void) => http.ClientRequest; POST: (url: string | URL, data: any, headers?: { [key: string]: any; @@ -136,6 +118,5 @@ export declare class HTTPbackend extends Service { buildPage: (pageStructure: string | string[] | { [key: string]: any; } | ((...args: any) => any), baseTemplate: string) => string; - hotreload: (socketURL?: string | URL, esbuild_cssFileName?: string) => string; - pwa: (pwaName?: string, cacheExpirationDays?: number, serviceWorkerUrl?: string) => string; + hotreload: (socketURL?: string | URL) => string; } diff --git a/dist/src/services/router/Router.d.ts b/dist/services/router/Router.d.ts similarity index 73% rename from dist/src/services/router/Router.d.ts rename to dist/services/router/Router.d.ts index 3d6e0348..67171855 100644 --- a/dist/src/services/router/Router.d.ts +++ b/dist/services/router/Router.d.ts @@ -1,6 +1,6 @@ -import { Graph, GraphNode } from "../../core/Graph"; +import { Graph, GraphNode } from "../../Graph"; import { Service, ServiceOptions } from "../Service"; -export type User = { +export declare type User = { _id: string; send: (...args: any[]) => any; request: (...args: any[]) => Promise | Promise[] | undefined; @@ -8,19 +8,11 @@ export type User = { run: (...args: any[]) => Promise | Promise[] | undefined; subscribe: (...args: any[]) => Promise | Promise[] | undefined; unsubscribe: (...args: any[]) => Promise | Promise[] | undefined; - sendAll?: (...args: any[]) => any; - requestAll?: (...args: any[]) => Promise | undefined; - postAll?: (...args: any[]) => void; - runAll?: (...args: any[]) => Promise | undefined; - subscribeAll?: (...args: any[]) => Promise | undefined; - unsubscribeAll?: (...args: any[]) => Promise | undefined; terminate: (...args: any[]) => boolean; - onmessage?: (...args: any[]) => void; - onerror?: (...args: any[]) => void; - onclose?: ((user: User) => void) | ((...args: any[]) => void); + onclose?: (user: User) => void; [key: string]: any; }; -export type ConnectionProps = { +export declare type ConnectionProps = { connection: GraphNode | Graph | { [key: string]: any; } | string; @@ -28,7 +20,7 @@ export type ConnectionProps = { source?: string; onclose?: (connection: ConnectionInfo, ...args: any[]) => void; }; -export type ConnectionInfo = { +export declare type ConnectionInfo = { connection: GraphNode | Graph | { [key: string]: any; }; @@ -41,12 +33,12 @@ export type ConnectionInfo = { request?: (message: any, method?: any, ...a: any[]) => Promise | Promise[]; post?: (route: any, args?: any, method?: string, ...a: any[]) => void; run?: (route: any, args?: any, method?: string, ...a: any[]) => Promise | Promise[]; - subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | undefined; + subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | Promise[] | undefined; unsubscribe?: (route: any, sub: number, ...arrayBuffer: any[]) => Promise | Promise[]; terminate: (...a: any[]) => boolean; onclose?: (connection: ConnectionInfo, ...args: any[]) => void; }; -export type RouterOptions = { +export declare type RouterOptions = { graph?: { [key: string]: Service | Graph | any | { service: Service | Graph | any; @@ -64,7 +56,6 @@ export type RouterOptions = { }; }; }; - timeout?: number; order?: string[]; [key: string]: any; } & ServiceOptions; @@ -91,7 +82,6 @@ export declare class Router extends Service { users: { [key: string]: User; }; - userTimeout: number; order: string[]; constructor(options?: RouterOptions); addUser: (info: { @@ -113,11 +103,11 @@ export declare class Router extends Service { _id: string; [key: string]: any; }, terminate?: boolean): boolean; - getConnection: (sourceId: string, hasMethod?: string, connectionId?: string) => User | ConnectionInfo | undefined; - getConnections: (sourceId: string, hasMethod?: string, props?: {}) => {}; - runConnection: (userId: string, method: 'run' | 'post' | 'subscribe' | 'unsubscribe' | 'terminate' | 'send' | 'request' | 'runAll' | 'postAll' | 'subscribeAll' | 'unsubscribeAll' | 'sendAll' | 'requestAll', args: any[], connectionId?: string) => Promise; - subscribeThroughConnection: (route: string, remoteRelay: string | ConnectionInfo, remoteEndpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; - addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string, autoRemove?: boolean) => ConnectionInfo; + getConnection: (sourceId: string, hasMethod?: string) => ConnectionInfo | undefined; + getConnections: (sourceId: string, hasMethod?: string, props?: {}) => { + [key: string]: ConnectionInfo; + }; + addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string) => ConnectionInfo; removeConnection: (connection: string | ConnectionInfo | { [key: string]: any; _id: string; @@ -128,12 +118,9 @@ export declare class Router extends Service { [key: string]: any; }, source?: string, ...args: any[]) => Promise; terminate: (connection: string | ConnectionInfo) => boolean; + subscribeThroughConnection: (route: string, relay: string | ConnectionInfo, endpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; routeConnections: (route: string, transmitter: string | ConnectionInfo, receiver: string | ConnectionInfo, ...args: any[]) => Promise; setUserData: (user: string | User, data: string | { [key: string]: any; }) => boolean; } -export declare function connectionHasId(connection: { - _id?: string; - [key: string]: any; -}, timeout?: number): Promise; diff --git a/dist/services/sessions/sessions.service.d.ts b/dist/services/sessions/sessions.service.d.ts new file mode 100644 index 00000000..e960fc6f --- /dev/null +++ b/dist/services/sessions/sessions.service.d.ts @@ -0,0 +1,199 @@ +import { Service, ServiceOptions } from "../Service"; +import { User } from "../router/Router"; +export declare type PrivateSessionProps = { + _id?: string; + settings?: { + listener: string; + source: string; + propnames: { + [key: string]: boolean; + }; + admins?: { + [key: string]: boolean; + }; + moderators?: { + [key: string]: boolean; + }; + password?: string; + ownerId?: string; + onopen?: (session: PrivateSessionProps) => void; + onmessage?: (session: PrivateSessionProps) => void; + onclose?: (session: PrivateSessionProps) => void; + [key: string]: any; + }; + data?: { + [key: string]: any; + }; + lastTransmit?: string | number; + [key: string]: any; +}; +export declare type SessionUser = { + _id: string; + sessions: { + [key: string]: any; + }; + [key: string]: any; +} & Partial; +export declare type SharedSessionProps = { + _id?: string; + settings?: { + name: string; + propnames: { + [key: string]: boolean; + }; + users?: { + [key: string]: boolean; + }; + host?: string; + hostprops?: { + [key: string]: boolean; + }; + admins?: { + [key: string]: boolean; + }; + moderators?: { + [key: string]: boolean; + }; + spectators?: { + [key: string]: boolean; + }; + banned?: { + [key: string]: boolean; + }; + password?: string; + ownerId?: string; + onopen?: (session: SharedSessionProps) => void; + onmessage?: (session: SharedSessionProps) => void; + onclose?: (session: SharedSessionProps) => void; + [key: string]: any; + }; + data?: { + shared: { + [key: string]: { + [key: string]: any; + }; + }; + private?: { + [key: string]: any; + }; + [key: string]: any; + }; + lastTransmit?: string | number; + [key: string]: any; +}; +export declare type StreamInfo = { + [key: string]: { + object: { + [key: string]: any; + }; + settings: { + keys?: string[]; + callback?: 0 | 1 | Function; + lastRead?: number; + [key: string]: any; + }; + onupdate?: (data: any, streamSettings: any) => void; + onclose?: (streamSettings: any) => void; + }; +}; +export declare class SessionsService extends Service { + name: string; + users: { + [key: string]: SessionUser; + }; + sessions: { + private: { + [key: string]: PrivateSessionProps; + }; + shared: { + [key: string]: SharedSessionProps; + }; + }; + constructor(options?: ServiceOptions, users?: { + [key: string]: SessionUser; + }); + getSessionInfo: (sessionId?: string, userId?: string) => { + [key: string]: SharedSessionProps; + }; + openPrivateSession: (options?: PrivateSessionProps, userId?: string) => any; + openSharedSession: (options: SharedSessionProps, userId?: string) => any; + updateSession: (options: PrivateSessionProps | SharedSessionProps, userId?: string) => any; + joinSession: (sessionId: string, userId: string, options?: SharedSessionProps | PrivateSessionProps) => any; + leaveSession: (sessionId: string, userId: string, clear?: boolean) => boolean; + getFirstMatch(obj1: { + [key: string]: any; + }, obj2: { + [key: string]: any; + }): string | false; + swapHost: (session: PrivateSessionProps | SharedSessionProps | string, newHostId?: string) => boolean; + deleteSession: (sessionId: string, userId: string) => boolean; + subscribeToSession: (session: SharedSessionProps | PrivateSessionProps | string, userId: string, onmessage?: (session: SharedSessionProps | PrivateSessionProps, userId: string) => void, onopen?: (session: SharedSessionProps | PrivateSessionProps, userId: string) => void, onclose?: (session: SharedSessionProps | PrivateSessionProps, userId: string) => void) => PrivateSessionProps | SharedSessionProps; + sessionUpdateCheck: (transmit?: boolean) => any; + transmitSessionUpdates: (updates: { + private: { + [key: string]: any; + }; + shared: { + [key: string]: any; + }; + }) => {}; + receiveSessionUpdates: (origin: any, update: string | { + private: { + [key: string]: any; + }; + shared: { + [key: string]: any; + }; + }) => SessionUser; + getUpdatedUserData: (user: SessionUser) => {}; + userUpdateCheck: (user: SessionUser) => {}; + setUserProps: (user: string | SessionUser, props: string | { + [key: string]: any; + }) => boolean; + STREAMLATEST: number; + STREAMALLLATEST: number; + streamSettings: StreamInfo; + streamFunctions: any; + setStreamFunc: (name: string, key: string, callback?: 0 | 1 | Function) => boolean; + addStreamFunc: (name: any, callback?: (data: any) => void) => void; + setStream: (object?: {}, settings?: { + keys?: string[]; + callback?: Function; + }, streamName?: string, onupdate?: (update: any, settings: any) => void, onclose?: (settings: any) => void) => { + object: { + [key: string]: any; + }; + settings: { + [key: string]: any; + keys?: string[]; + callback?: 0 | Function | 1; + lastRead?: number; + }; + onupdate?: (data: any, streamSettings: any) => void; + onclose?: (streamSettings: any) => void; + }; + removeStream: (streamName: any, key: any) => boolean; + updateStreamData: (streamName: any, data?: {}) => false | { + [key: string]: any; + }; + getStreamUpdate: (streamName: string) => {}; + getAllStreamUpdates: () => {}; + streamLoop: { + __operator: () => {}; + __node: { + loop: number; + }; + }; + userUpdateLoop: { + __operator: (user: SessionUser) => {}; + __node: { + loop: number; + }; + }; + sessionLoop: { + __operator: (transmit?: boolean) => any; + __node: { + loop: number; + }; + }; +} diff --git a/dist/src/services/sse/SSE.browser.d.ts b/dist/services/sse/SSE.browser.d.ts similarity index 86% rename from dist/src/services/sse/SSE.browser.d.ts rename to dist/services/sse/SSE.browser.d.ts index 46111a03..982722ad 100644 --- a/dist/src/services/sse/SSE.browser.d.ts +++ b/dist/services/sse/SSE.browser.d.ts @@ -1,5 +1,5 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type EventSourceProps = { +export declare type EventSourceProps = { url: string; events: { message?: (ev: any, sseinfo?: EventSourceInfo) => void; @@ -17,13 +17,13 @@ export type EventSourceProps = { _id?: string; keepState?: boolean; }; -export type EventSourceInfo = { +export declare type EventSourceInfo = { source: EventSource; send: (message: any) => any; request: (message: any, method?: string) => Promise; post: (route: any, args?: any) => void; run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => any; + subscribe: (route: any, callback?: ((res: any) => void) | string) => any; unsubscribe: (route: any, sub: number) => Promise; terminate: () => void; graph: SSEfrontend; @@ -45,7 +45,7 @@ export declare class SSEfrontend extends Service { transmit: (message: any | ServiceMessage, url: string | URL) => Promise; request: (message: ServiceMessage | any, url: string, method?: string, sessionId?: string) => Promise; runRequest: (message: any, url: string | any, callbackId: string | number, sessionId?: string) => any; - subscribeSSE: (route: string, url: string, args?: any[], key?: string, subInput?: boolean) => number; - subscribeToSSE: (route: string, url: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, sessionId?: string) => Promise; + subscribeSSE: (route: string, url: string, key?: string, subInput?: boolean) => any; + subscribeToSSE: (route: string, url: string, callback?: string | ((res: any) => void), sessionId?: string, key?: string, subInput?: boolean) => Promise; terminate: (sse: EventSourceInfo | EventSource | string) => void; } diff --git a/dist/src/services/sse/SSE.node.d.ts b/dist/services/sse/SSE.node.d.ts similarity index 79% rename from dist/src/services/sse/SSE.node.d.ts rename to dist/services/sse/SSE.node.d.ts index f4adbc3a..211b47ee 100644 --- a/dist/src/services/sse/SSE.node.d.ts +++ b/dist/services/sse/SSE.node.d.ts @@ -1,12 +1,10 @@ /// -/// -/// import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import { Session, Channel } from 'better-sse'; +import { Session, SessionState, Channel } from 'better-sse'; import http from 'http'; import https from 'https'; import { Readable } from "node:stream"; -export type SSEProps = { +export declare type SSEProps = { server: http.Server | https.Server; path: string; channels?: string[]; @@ -17,10 +15,10 @@ export type SSEProps = { _id?: string; [key: string]: any; }; -export type SSEChannelInfo = { +export declare type SSEChannelInfo = { channel: Channel>; sessions: { - [key: string]: Session; + [key: string]: Session; }; requests: { [key: string]: Function; @@ -29,21 +27,21 @@ export type SSEChannelInfo = { request: (message: any, method?: string, sessionId?: string, eventName?: string) => Promise | Promise[]; post: (route: any, args?: any, method?: string, sessionId?: string, eventName?: string) => void; run: (route: any, args?: any, method?: string, sessionId?: string, eventName?: string) => Promise | Promise[]; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => Promise | Promise[] | undefined; + subscribe: (route: any, callback?: ((res: any) => void) | string, sessionId?: string) => Promise | Promise[] | undefined; unsubscribe: (route: any, sub: number, sessionId?: string, eventName?: string) => Promise | Promise[]; terminate: () => boolean; _id: string; graph: SSEbackend; } & SSEProps; -export type SSEClientInfo = { +export declare type SSEClientInfo = { _id: string; - session: Session; + session: Session; served: SSEChannelInfo; send: (message: any, eventName?: string) => any; request: (message: any, method?: string, eventName?: string) => Promise; post: (route: any, args?: any, method?: string, eventName?: string) => void; run: (route: any, args?: any, method?: string, eventName?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => any; + subscribe: (route: any, callback?: ((res: any) => void) | string) => any; unsubscribe: (route: any, sub: number, eventName?: string) => Promise; terminate: () => boolean; onclose?: (session: any, sseinfo: any, _id: string, req: http.IncomingMessage, res: http.ServerResponse) => void; @@ -67,14 +65,14 @@ export declare class SSEbackend extends Service { }; }; constructor(options?: ServiceOptions); - openSSE: (options: SSEProps) => false | SSEChannelInfo; + setupSSE: (options: SSEProps) => false | SSEChannelInfo; open: (options: SSEProps) => false | SSEChannelInfo; streamIterable: (path: string, iterable: Iterable | AsyncIterable, sessionId?: string, eventName?: string) => Promise | Promise[]; streamReadable: (path: string, readable: Readable, sessionId?: string, eventName?: string) => Promise | Promise[]; transmit: (data: string | ServiceMessage, path?: string, eventName?: string, sessionId?: string) => boolean; request: (message: any, path: string, method?: string, sessionId?: string, eventName?: string) => Promise; runRequest: (message: any, path: string, callbackId: string | number, sessionId?: string) => any; - subscribeSSE: (route: string, path: string, args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => number; - subscribeToSSE: (route: string, path: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, sessionId?: string, eventName?: string) => Promise | Promise[]; + subscribeSSE: (route: string, path: string, sessionId?: string, eventName?: string) => any; + subscribeToSSE: (route: string, path: string, callback?: string | ((res: any) => void), sessionId?: string, eventName?: string) => Promise | Promise[]; terminate: (sse: string | SSEChannelInfo) => boolean; } diff --git a/dist/services/unsafe/Unsafe.service.d.ts b/dist/services/unsafe/Unsafe.service.d.ts new file mode 100644 index 00000000..fecbf4b8 --- /dev/null +++ b/dist/services/unsafe/Unsafe.service.d.ts @@ -0,0 +1,25 @@ +export declare const unsafeRoutes: { + setRoute: (fn: string | (() => any), fnName?: string) => boolean; + setNode: (fn: string | (() => any), fnName?: string) => boolean; + setMethod: (route: string, fn: string | (() => any), fnName?: string) => boolean; + assignRoute: (route: string, source: { + [key: string]: any; + }) => void; + transferClass: (classObj: any, className?: string) => false | { + route: string; + args: any[]; + }; + receiveClass: (stringified: string, className?: string) => boolean; + setGlobal: (key: string, value: any) => boolean; + assignGlobalObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setValue: (key: string, value: any) => boolean; + assignObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setGlobalFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToGlobalObject: (globalObjectName: string, fn: any, fnName: any) => boolean; + setFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToObject: (objectName: string, fn: any, fnName: any) => boolean; +}; diff --git a/dist/src/services/utils.d.ts b/dist/services/utils.d.ts similarity index 50% rename from dist/src/services/utils.d.ts rename to dist/services/utils.d.ts index 9efee154..38516f95 100644 --- a/dist/src/services/utils.d.ts +++ b/dist/services/utils.d.ts @@ -1,12 +1,6 @@ -export declare let recursivelyStringifyFunctions: (obj: { - [key: string]: any; -}) => {}; -export declare function getFnParamNames(fn: any): any; -export declare let getFunctionHead: (methodString: any) => any; export declare function parseFunctionFromText(method?: string): any; export declare function reconstructObject(json?: string | { [x: string]: any; }): any; export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyWithFunctionsAndCircularRefs: (obj: any, space?: any) => string; export declare const stringifyFast: (obj: any, space?: any) => string; diff --git a/dist/services/webrtc/WebRTC.browser.d.ts b/dist/services/webrtc/WebRTC.browser.d.ts new file mode 100644 index 00000000..807da0b1 --- /dev/null +++ b/dist/services/webrtc/WebRTC.browser.d.ts @@ -0,0 +1,77 @@ +import { Service, ServiceMessage, ServiceOptions } from "../Service"; +export declare type WebRTCProps = { + _id?: string; + channels?: { + [key: string]: (true | RTCDataChannelInit | RTCDataChannel); + }; + config?: RTCConfiguration; + hostdescription?: RTCSessionDescriptionInit | string; + peerdescription?: RTCSessionDescriptionInit | string; + offer?: RTCOfferOptions; + hostcandidates?: { + [key: string]: RTCIceCandidate; + }; + peercandidates?: { + [key: string]: RTCIceCandidate; + }; + answer?: RTCAnswerOptions; + ontrack?: (ev: RTCTrackEvent) => void; + onicecandidate?: (ev: RTCPeerConnectionIceEvent) => void; + onicecandidateerror?: (ev: Event) => void; + onnegotiationneeded?: (ev: Event) => void; + ondatachannel?: (ev: RTCDataChannelEvent) => void; + ondata?: (ev: MessageEvent, channel: RTCDataChannel, room: any) => void; + onconnectionstatechange?: (ev: Event) => void; + oniceconnectionstatechange?: (ev: Event) => void; + onclose?: (rtc: WebRTCInfo) => void; +}; +export declare type WebRTCInfo = { + _id: string; + rtc: RTCPeerConnection; + send: (message: any) => void; + request: (message: any, method?: string) => Promise; + post: (route: any, args?: any) => void; + run: (route: any, args?: any, method?: string) => Promise; + subscribe: (route: any, callback?: ((res: any) => void) | string) => Promise; + unsubscribe: (route: any, sub: number) => Promise; + terminate: () => boolean; + graph: WebRTCfrontend; +} & WebRTCProps; +export declare class WebRTCfrontend extends Service { + name: string; + rtc: { + [key: string]: WebRTCInfo; + }; + iceServers: { + urls: string[]; + }[]; + connections: { + rtc: { + [key: string]: WebRTCInfo; + }; + }; + constructor(options?: ServiceOptions, iceServers?: { + urls: string[]; + }[]); + createStream: (options: { + [key: string]: { + track: MediaStreamTrack | MediaTrackConstraints; + onended: (ev: any) => void; + onmute: (ev: any) => void; + onunmute: (ev: any) => void; + }; + }) => MediaStream; + openRTC: (options?: WebRTCProps) => Promise; + addIceCandidate(rtc: RTCPeerConnection, candidate: RTCIceCandidate): Promise; + answerPeer(rtc: RTCPeerConnection, options: WebRTCProps): Promise; + addUserMedia: (rtc: RTCPeerConnection, options?: MediaStreamConstraints) => any[]; + addTrack: (rtc: RTCPeerConnection, track: MediaStreamTrack, stream: MediaStream) => boolean; + removeTrack: (rtc: RTCPeerConnection, sender: RTCRtpSender) => boolean; + addDataChannel: (rtc: RTCPeerConnection, name: string, options?: RTCDataChannelInit) => RTCDataChannel; + transmit: (data: ServiceMessage | any, id?: string, channel?: string | RTCDataChannel) => boolean; + terminate: (rtc: RTCPeerConnection | WebRTCInfo | string) => boolean; + request: (message: ServiceMessage | any, channel: RTCDataChannel, _id: string, method?: string) => Promise; + runRequest: (message: any, channel: RTCDataChannel | string, callbackId: string | number) => any; + subscribeRTC: (route: string, rtcId: string, channel: string | RTCDataChannel) => any; + subscribeToRTC: (route: string, rtcId: string, channelId: string, callback?: string | ((res: any) => void)) => Promise; +} diff --git a/dist/src/services/worker/ProxyListener.d.ts b/dist/services/worker/ProxyListener.d.ts similarity index 74% rename from dist/src/services/worker/ProxyListener.d.ts rename to dist/services/worker/ProxyListener.d.ts index 104c3c8b..dc6e2c02 100644 --- a/dist/src/services/worker/ProxyListener.d.ts +++ b/dist/services/worker/ProxyListener.d.ts @@ -1,8 +1,7 @@ -declare function focusEventHandler(event: any, sendFn: any): void; -declare function wheelEventHandler(event: any, sendFn: any, preventDefault: any): void; -declare function preventDefaultHandler(event: any, sendFn: any, preventDefault: any): void; -declare function touchEventHandler(event: any, sendFn: any, preventDefault: any): void; -declare function filteredKeydownEventHandler(event: any, sendFn: any, preventDefault: any): void; +declare function wheelEventHandler(event: any, sendFn: any): void; +declare function preventDefaultHandler(event: any): void; +declare function touchEventHandler(event: any, sendFn: any): void; +declare function filteredKeydownEventHandler(event: any, sendFn: any): void; export declare const eventHandlers: { contextmenu: typeof preventDefaultHandler; mousedown: (event: any, sendFn: any) => void; @@ -11,19 +10,13 @@ export declare const eventHandlers: { pointerdown: (event: any, sendFn: any) => void; pointermove: (event: any, sendFn: any) => void; pointerup: (event: any, sendFn: any) => void; - pointerlockchange: (event: any, sendFn: any) => void; - webkitpointerlockchange: (event: any, sendFn: any) => void; - focus: typeof focusEventHandler; - blur: typeof focusEventHandler; - pointerout: (event: any, sendFn: any) => void; touchstart: typeof touchEventHandler; touchmove: typeof touchEventHandler; touchend: typeof touchEventHandler; wheel: typeof wheelEventHandler; keydown: typeof filteredKeydownEventHandler; - keyup: typeof filteredKeydownEventHandler; }; -export declare function initProxyElement(element: any, worker: any, id: any, preventDefault?: boolean): any; +export declare function initProxyElement(element: any, worker: any, id: any): any; export declare class EventDispatcher { __listeners: any; addEventListener(type: any, listener: any): void; @@ -55,7 +48,6 @@ export declare class ElementProxyReceiver extends EventDispatcher { }; handleEvent: (data: any) => void; focus(): void; - blur(): void; } export declare class ProxyManager { targets: any; diff --git a/dist/src/services/worker/Subprocess.d.ts b/dist/services/worker/Subprocess.d.ts similarity index 73% rename from dist/src/services/worker/Subprocess.d.ts rename to dist/services/worker/Subprocess.d.ts index 97eea0a8..9963fd85 100644 --- a/dist/src/services/worker/Subprocess.d.ts +++ b/dist/services/worker/Subprocess.d.ts @@ -1,5 +1,4 @@ import { WorkerInfo, WorkerService } from './Worker.service'; -import { GraphNodeProperties } from '../../core/Graph'; export declare type Subprocess = (context: SubprocessContext, data: { [key: string]: any; } | any) => { @@ -102,32 +101,17 @@ export declare const subprocessRoutes: { runSubprocess: (data: { [key: string]: any; }, _id?: string) => any; - transferNode: (properties: string | Function | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), connection: any, name?: string) => any; - setNode: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - })) => any; - proxyRemoteNode: (name: string, connection: any) => Promise; - makeNodeTransferrable: (properties: GraphNodeProperties, name?: string) => {}; - setTemplate: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), name?: string) => string | false; - loadFromTemplate: (templateName: string, name?: string) => any; - setMethod: (route: string, fn: string | (() => any), methodKey?: string) => boolean; - assignNode: (nodeTag: string, source: { + setRoute: (fn: string | (() => any), fnName?: string) => boolean; + setNode: (fn: string | (() => any), fnName?: string) => boolean; + setMethod: (route: string, fn: string | (() => any), fnName?: string) => boolean; + assignRoute: (route: string, source: { [key: string]: any; }) => void; - getNodeProperties: (nodeTag: string) => {}; - transferClass: (classObj: any, connection: any, className?: string) => any; + transferClass: (classObj: any, className?: string) => false | { + route: string; + args: any[]; + }; receiveClass: (stringified: string, className?: string) => boolean; - transferFunction: (fn: Function, connection: any, fnName?: string) => any; setGlobal: (key: string, value: any) => boolean; assignGlobalObject: (target: string, source: { [key: string]: any; @@ -137,5 +121,7 @@ export declare const subprocessRoutes: { [key: string]: any; }) => boolean; setGlobalFunction: (fn: any, fnName?: string) => boolean; - setGraphFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToGlobalObject: (globalObjectName: string, fn: any, fnName: any) => boolean; + setFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToObject: (objectName: string, fn: any, fnName: any) => boolean; }; diff --git a/dist/services/worker/Worker.node.service.d.ts b/dist/services/worker/Worker.node.service.d.ts new file mode 100644 index 00000000..38cb8c46 --- /dev/null +++ b/dist/services/worker/Worker.node.service.d.ts @@ -0,0 +1,62 @@ +import { Service, Routes, ServiceMessage, ServiceOptions } from "../Service"; +import Worker from 'web-worker'; +import { GraphNodeProperties } from "../../Graph"; +export declare type WorkerRoute = { + worker?: WorkerInfo; + workerUrl?: string | URL | Blob; + workerId?: string; + transferFunctions?: { + [key: string]: Function; + }; + transferClasses?: { + [key: string]: Function; + }; + parentRoute?: string; + callback?: string; +} & GraphNodeProperties & WorkerProps; +export declare type WorkerProps = { + worker: WorkerInfo; + workerUrl?: string | URL | Blob; + url?: URL | string | Blob; + _id?: string; + port?: MessagePort; + onmessage?: (ev: any) => void; + onerror?: (ev: any) => void; +}; +export declare type WorkerInfo = { + worker: Worker; + send: (message: any, transfer?: any) => void; + request: (message: any, transfer?: any, method?: string) => Promise; + post: (route: any, args?: any, transfer?: any) => void; + run: (route: any, args?: any, transfer?: any, method?: string) => Promise; + subscribe: (route: any, callback?: ((res: any) => void) | string) => any; + unsubscribe: (route: any, sub: number) => Promise; +} & WorkerProps & WorkerRoute; +export declare class WorkerService extends Service { + name: string; + workers: { + [key: string]: WorkerInfo; + }; + threadRot: number; + constructor(options?: ServiceOptions); + customRoutes: ServiceOptions["customRoutes"]; + customChildren: ServiceOptions["customChildren"]; + addWorker: (options: { + url?: URL | string | Blob; + port?: MessagePort; + _id?: string; + onmessage?: (ev: any) => void; + onerror?: (ev: any) => void; + }) => WorkerInfo; + toObjectURL: (scriptTemplate: string) => string; + transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: any) => any; + terminate: (worker: Worker | MessagePort | string) => boolean; + establishMessageChannel: (worker: Worker | string | MessagePort, worker2?: Worker | string | MessagePort) => string | false; + request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; + runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number) => any; + subscribeWorker: (route: string, worker: Worker | string | MessagePort) => number; + subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void)) => Promise; + transferFunction(worker: WorkerInfo, fn: Function, fnName?: string): Promise; + transferClass(worker: WorkerInfo, cls: Function, className?: string): Promise; + routes: Routes; +} diff --git a/src/extras/dist/src/services/worker/Worker.service.d.ts b/dist/services/worker/Worker.service.d.ts similarity index 71% rename from src/extras/dist/src/services/worker/Worker.service.d.ts rename to dist/services/worker/Worker.service.d.ts index 730d0214..fe064cf3 100644 --- a/src/extras/dist/src/services/worker/Worker.service.d.ts +++ b/dist/services/worker/Worker.service.d.ts @@ -1,9 +1,10 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; import Worker from 'web-worker'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export type WorkerRoute = { +import { GraphNode, GraphNodeProperties } from "../../Graph"; +export declare type WorkerRoute = { worker?: WorkerInfo; workerUrl?: string | URL | Blob; + workerId?: string; transferFunctions?: { [key: string]: Function; }; @@ -19,7 +20,7 @@ export type WorkerRoute = { initArgs?: any[]; initTransfer?: any[]; } & GraphNodeProperties & WorkerProps; -export type WorkerProps = { +export declare type WorkerProps = { worker?: WorkerInfo; workerUrl?: string | URL | Blob; url?: URL | string | Blob; @@ -29,13 +30,13 @@ export type WorkerProps = { onerror?: (ev: any) => void; onclose?: (worker: Worker | MessagePort) => void; }; -export type WorkerInfo = { +export declare type WorkerInfo = { worker: Worker | MessagePort; send: (message: any, transfer?: any) => void; - request: (message: any, method?: string, transfer?: any) => Promise; - post: (route: any, args?: any, method?: string, transfer?: any) => void; - run: (route: any, args?: any, method?: string, transfer?: any) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; + request: (message: any, transfer?: any, method?: string) => Promise; + post: (route: any, args?: any, transfer?: any) => void; + run: (route: any, args?: any, transfer?: any, method?: string) => Promise; + subscribe: (route: any, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; unsubscribe: (route: any, sub: number) => Promise; start: (route?: any, portId?: string, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; stop: (route?: string, portId?: string) => Promise; @@ -49,7 +50,7 @@ export type WorkerInfo = { }; }; terminate: () => boolean; - postMessage: (message: any, transfer?: any[]) => void; + postMessage: (message: any, transfer: any[]) => void; graph: WorkerService; _id: string; } & WorkerProps & WorkerRoute; @@ -61,7 +62,7 @@ export declare class WorkerService extends Service { threadRot: number; connections: any; constructor(options?: ServiceOptions); - loadWorkerRoute: (node: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; + loadWorkerRoute: (rt: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; workerloader: any; addDefaultMessageListener: () => void; postMessage: (message: any, target: string, transfer?: Transferable[]) => void; @@ -72,24 +73,18 @@ export declare class WorkerService extends Service { onmessage?: (ev: any) => void; onerror?: (ev: any) => void; }) => WorkerInfo; - open: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - close: () => void; toObjectURL: (scriptTemplate: string) => string; getTransferable(message: any): any; transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: StructuredSerializeOptions) => any; - terminate: (worker: Worker | MessagePort | string | WorkerInfo) => boolean; + terminate: (worker: Worker | MessagePort | string) => boolean; establishMessageChannel: (worker: Worker | string | MessagePort | WorkerInfo, worker2?: Worker | string | MessagePort | WorkerInfo) => string | false; request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number) => any; - subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => number; - subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; + subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, blocking?: boolean, key?: string, subInput?: boolean) => any; + subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), blocking?: boolean, key?: string, subInput?: boolean) => Promise; triggerSubscription: (route: string, workerId: string, result: any) => Promise; - pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, args?: any[], key?: any, subInput?: boolean, blocking?: boolean) => Promise; + pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, blocking?: boolean) => Promise; unpipeWorkers: (sourceRoute: string, sourceWorker: WorkerInfo | string, sub?: number) => Promise; + transferFunction(worker: WorkerInfo, fn: Function, fnName?: string): Promise; + transferClass(worker: WorkerInfo, cls: Function, className?: string): Promise; } diff --git a/dist/src/services/worker/WorkerCanvas.d.ts b/dist/services/worker/WorkerCanvas.d.ts similarity index 80% rename from dist/src/services/worker/WorkerCanvas.d.ts rename to dist/services/worker/WorkerCanvas.d.ts index a4526480..45d0d374 100644 --- a/dist/src/services/worker/WorkerCanvas.d.ts +++ b/dist/services/worker/WorkerCanvas.d.ts @@ -1,5 +1,5 @@ import { initProxyElement } from './ProxyListener'; -export type WorkerCanvasTransferProps = { +export declare type WorkerCanvasTransferProps = { canvas: HTMLCanvasElement; context?: string; _id?: string; @@ -11,10 +11,10 @@ export type WorkerCanvasTransferProps = { animating?: boolean; [key: string]: any; }; -export type CanvasProps = { +export declare type CanvasProps = { canvas: any; context?: string | CanvasRenderingContext2D | WebGL2RenderingContext | WebGLRenderingContext; - _id: string; + _id?: string; width?: number; height?: number; draw?: string | ((self: any, canvas: any, context: any) => void); @@ -22,26 +22,25 @@ export type CanvasProps = { init?: string | ((self: any, canvas: any, context: any) => void); clear?: string | ((self: any, canvas: any, context: any) => void); animating?: boolean; - preventDefault?: boolean; [key: string]: any; }; -export type CanvasControls = { +export declare type CanvasControls = { _id: string; - draw: (props?: any, transfer?: any) => void; + draw: (props?: any) => void; update: (props: { [key: string]: any; - }, transfer?: any) => void; + }) => void; clear: () => void; init: () => void; stop: () => void; start: () => void; - set: (newDrawProps: CanvasProps, transfer?: any) => void; + set: (newDrawProps: CanvasProps) => void; }; -export type WorkerCanvasControls = { +export declare type WorkerCanvasControls = { worker: Worker | MessagePort; terminate: () => void; } & CanvasControls; -export type WorkerCanvas = { +export declare type WorkerCanvas = { graph: any; canvas: any; context?: CanvasRenderingContext2D | WebGL2RenderingContext | WebGLRenderingContext; @@ -50,20 +49,16 @@ export type WorkerCanvas = { update?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context'], input: any) => void); init?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); clear?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); - stop: () => void; - start: () => void; - set: (newDrawProps: CanvasProps, transfer?: any) => void; - terminate: () => void; animating: boolean; [key: string]: any; }; export declare function Renderer(options: CanvasProps & { - worker?: Worker | string | Blob | MessagePort | true; + worker?: Worker | string | Blob | MessagePort; route?: string; -}): string | CanvasControls | Promise; +}): string | CanvasControls; export declare function transferCanvas(worker: Worker | MessagePort, options: WorkerCanvasTransferProps, route?: string): WorkerCanvasControls; export declare function setDraw(settings: CanvasProps, _id?: string): string; -export declare function setupCanvas(options: CanvasProps): string | CanvasControls | Promise; +export declare function setupCanvas(options: CanvasProps): string | CanvasControls; export declare function drawFrame(props?: { [key: string]: any; }, _id?: string): string; @@ -74,8 +69,7 @@ export declare function setProps(props?: { [key: string]: any; }, _id?: string): string; export declare function startAnim(_id?: string, draw?: string | ((this: any, canvas: any, context: any) => void)): string; -export declare function stopAnim(_id: string): string; -export declare function getCanvas(_id?: string): any; +export declare function stopAnim(_id?: string): string; export declare const workerCanvasRoutes: { Renderer: typeof Renderer; transferCanvas: typeof transferCanvas; @@ -88,7 +82,6 @@ export declare const workerCanvasRoutes: { setProps: typeof setProps; startAnim: typeof startAnim; stopAnim: typeof stopAnim; - getCanvas: typeof getCanvas; initProxyElement: typeof initProxyElement; makeProxy: (id: any, elm?: any) => any; handleProxyEvent: (data: any, id: any) => any; diff --git a/dist/services/wss/WSS.browser.d.ts b/dist/services/wss/WSS.browser.d.ts new file mode 100644 index 00000000..682d05f4 --- /dev/null +++ b/dist/services/wss/WSS.browser.d.ts @@ -0,0 +1,48 @@ +import { Service, ServiceMessage, ServiceOptions } from "../Service"; +export declare type WebSocketProps = { + host: string; + port: number; + path?: string; + onmessage?: (data: string | ArrayBufferLike | Blob | ArrayBufferView, ws: WebSocket, wsinfo: WebSocketInfo) => void; + onopen?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; + onclose?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; + onerror?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; + protocol?: 'ws' | 'wss'; + keepState?: boolean; + type?: 'socket'; + _id?: string; + [key: string]: any; +}; +export declare type WebSocketInfo = { + socket: WebSocket; + address: string; + send: (message: any) => void; + request: (message: any, method?: string) => Promise; + post: (route: any, args?: any) => void; + run: (route: any, args?: any, method?: string) => Promise; + subscribe: (route: any, callback?: ((res: any) => void) | string) => any; + unsubscribe: (route: any, sub: number) => Promise; + terminate: () => boolean; + _id?: string; + graph: WSSfrontend; +} & WebSocketProps; +export declare class WSSfrontend extends Service { + name: string; + sockets: { + [key: string]: WebSocketInfo; + }; + connections: { + sockets: { + [key: string]: WebSocketInfo; + }; + }; + constructor(options?: ServiceOptions); + openWS: (options?: WebSocketProps) => WebSocketInfo; + open: (options?: WebSocketProps) => WebSocketInfo; + transmit: (data: string | ArrayBufferLike | Blob | ArrayBufferView | ServiceMessage, ws: WebSocket) => boolean; + terminate: (ws: WebSocket | string) => boolean; + request: (message: ServiceMessage | any, ws: WebSocket, _id: string, method?: string) => Promise; + runRequest: (message: any, ws: WebSocket | string, callbackId: string | number) => any; + subscribeSocket: (route: string, socket: WebSocket | string, key?: string, subInput?: boolean) => any; + subscribeToSocket: (route: string, socketId: string, callback?: string | ((res: any) => void), key?: string, subInput?: boolean) => Promise; +} diff --git a/dist/src/services/wss/WSS.node.d.ts b/dist/services/wss/WSS.node.d.ts similarity index 80% rename from dist/src/services/wss/WSS.node.d.ts rename to dist/services/wss/WSS.node.d.ts index 3417b055..ff71cb3a 100644 --- a/dist/src/services/wss/WSS.node.d.ts +++ b/dist/services/wss/WSS.node.d.ts @@ -1,18 +1,13 @@ /// -/// -/// import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import WebSocket, { PerMessageDeflateOptions, WebSocketServer } from 'ws'; +import WebSocket, { WebSocketServer } from 'ws'; import http from 'http'; import https from 'https'; -import { GraphNodeProperties } from "../../core/Graph"; -export type SocketServerProps = { - server?: http.Server | https.Server | true; - port?: 7000 | number; - path?: 'wss' | 'hotreload' | 'python' | string; - noServer?: boolean; - host?: 'localhost' | '127.0.0.1' | string; - perMessageDeflate?: PerMessageDeflateOptions; +export declare type SocketServerProps = { + server: http.Server | https.Server; + host: 'localhost' | '127.0.0.1' | string; + port: 7000 | number; + path: 'wss' | 'hotreload' | 'python' | string; onmessage?: (data: any, ws: WebSocket, serverinfo: SocketServerInfo) => void; onclose?: (wss: WebSocketServer, serverinfo: SocketServerInfo) => void; onconnection?: (ws: WebSocket, request: http.IncomingMessage, serverinfo: SocketServerInfo, clientId: string) => void; @@ -21,11 +16,9 @@ export type SocketServerProps = { onupgrade?: (ws: WebSocket, serverinfo: SocketServerInfo, request: http.IncomingMessage, socket: any, head: Buffer) => void; keepState?: boolean; type?: 'wss'; - debug?: boolean; - serverOptions?: WebSocket.ServerOptions; [key: string]: any; -} & GraphNodeProperties; -export type SocketServerInfo = { +}; +export declare type SocketServerInfo = { wss: WebSocketServer; clients: { [key: string]: WebSocket; @@ -40,13 +33,12 @@ export type SocketServerInfo = { terminate: (socketId?: string) => boolean; graph: WSSbackend; } & SocketServerProps; -export type SocketProps = { +export declare type SocketProps = { host?: string; port?: number; path?: string; socket?: WebSocket; address?: string; - debug?: boolean; serverOptions?: WebSocket.ServerOptions; onmessage?: (data: string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[], ws: WebSocket, wsinfo: SocketProps) => void; onopen?: (ws: WebSocket, wsinfo: SocketProps) => void; @@ -56,15 +48,15 @@ export type SocketProps = { type?: 'socket'; _id?: string; keepState?: boolean; -} & GraphNodeProperties; -export type SocketInfo = { +}; +export declare type SocketInfo = { socket: WebSocket; address?: string; send: (message: any) => void; request: (message: any, method?: string) => Promise; post: (route: any, args?: any, method?: string) => void; run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => any; + subscribe: (route: any, callback?: ((res: any) => void) | string) => any; unsubscribe: (route: any, sub: number) => Promise; terminate: () => void; graph: WSSbackend; @@ -95,6 +87,6 @@ export declare class WSSbackend extends Service { terminate: (ws: WebSocketServer | WebSocket | string) => boolean; request: (message: ServiceMessage | any, ws: WebSocket, _id: string, method?: string) => Promise; runRequest: (message: any, ws: WebSocket | string, callbackId: string | number) => any; - subscribeSocket: (route: string, socket: WebSocket | string, args?: any[], key?: string, subInput?: boolean) => number; - subscribeToSocket: (route: string, socketId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => Promise; + subscribeSocket: (route: string, socket: WebSocket | string, key?: string, subInput?: boolean) => any; + subscribeToSocket: (route: string, socketId: string, callback?: string | ((res: any) => void), key?: string, subInput?: boolean) => Promise; } diff --git a/dist/src/core/EventHandler.d.ts b/dist/src/core/EventHandler.d.ts deleted file mode 100644 index 2f00b243..00000000 --- a/dist/src/core/EventHandler.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -export declare class EventHandler { - data: { - [key: string]: any; - }; - triggers: { - [key: string]: { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - }; - ctr: number; - constructor(data?: { - [key: string]: any; - }); - setState: (updateObj: { - [key: string]: any; - }) => { - [key: string]: any; - }; - setValue: (key: any, value: any) => void; - triggerEvent: (key: any, value: any) => void; - subscribeState: (onchange: (res: any) => void) => number; - unsubscribeState: (sub: number) => boolean; - subscribeEvent: (key: string, onchange: (res: any) => void, refObject?: { - [key: string]: any; - }, refKey?: string) => number; - unsubscribeEvent: (key: string, sub?: number) => boolean; - subscribeEventOnce: (key: string, onchange: (res: any) => void) => any; - getEvent: (key: any, sub?: any) => { - [key: string]: any; - sub: number; - onchange: Function; - } | { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - getSnapshot: () => void; - onRemoved: (trigger: { - sub: number; - onchange: Function; - }) => void; -} diff --git a/dist/src/core/Graph.d.ts b/dist/src/core/Graph.d.ts deleted file mode 100644 index f77b09bd..00000000 --- a/dist/src/core/Graph.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { EventHandler } from "./EventHandler"; -export declare const state: EventHandler; -export type GraphNodeProperties = { - __props?: Function | { - [key: string]: any; - } | GraphNodeProperties | GraphNode; - __operator?: ((...args: any[]) => any) | string; - __children?: { - [key: string]: any; - }; - __listeners?: { - [key: string]: true | string | ((result: any) => void) | { - __callback: string | ((result: any) => void) | true; - subInput?: boolean; - [key: string]: any; - }; - } | { - [key: string]: ((result: any) => void) | true | string; - }; - __onconnected?: ((node: any) => void | ((node: any) => void)[]); - __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); - __node?: { - tag?: string; - state?: EventHandler; - [key: string]: any; - }; - __args?: any[]; - __callable?: boolean; - [key: string]: any; -}; -export type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; -export type Roots = { - [key: string]: any; -}; -export type GraphOptions = { - roots?: Roots; - loaders?: { - [key: string]: Loader | { - init?: Loader; - connected?: (node: any) => void; - disconnected?: (node: any) => void; - }; - }; - state?: EventHandler; - mapGraphs?: false; - [key: string]: any; -}; -export type argObject = { - __input?: string | ((...args: any[]) => any); - __callback: string | ((...args: any[]) => any); - __args?: any[]; - __output?: string | argObject | ((...args: any[]) => any); -}; -export type Listener = { - __callback?: string; - __args?: (argObject | Function | string)[]; - sub: number; - node: GraphNode; - graph: Graph; - source?: string; - key?: string; - target?: string; - tkey?: string; - arguments?: Function[]; - subInput?: boolean; - onchange: Function; -}; -export declare class Callable extends Function { - __bound: Callable; - __call: ((...args: any[]) => any); - [key: string]: any; - constructor(); -} -export declare class GraphNode { - __node: { - tag: string; - unique: string; - state: EventHandler; - [key: string]: any; - }; - __children?: { - [key: string]: GraphNode; - }; - __parent?: Graph | GraphNode; - __operator?: any; - __listeners?: any; - __props?: any; - __args: any[]; - [key: string]: any; - constructor(properties: GraphNodeProperties, parent?: { - [key: string]: any; - }, graph?: Graph); - get __graph(): any; - set __graph(graph: any); - __setProperties: (properties: any, parent: any, graph: any) => void; - __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, target?: string, tkey?: string, args?: any[], callbackStr?: string) => any; - __unsubscribe: (sub?: number, key?: string, unsubInput?: boolean) => boolean; - __setOperator: (fn: (...args: any[]) => any) => any; - __addLocalState: (props?: { - [key: string]: any; - }, key?: string) => void; - __proxyObject: (obj: any) => void; - __addOnconnected(callback: (node: any) => void): void; - __addOndisconnected(callback: (node: any) => void): void; - __callConnected(node?: this): void; - __callDisconnected(node?: this): void; -} -export declare class Graph { - [key: string]: any; - __node: { - tag: string; - unique: string; - state: EventHandler; - nodes: Map; - roots: { - [key: string]: any; - }; - mapGraphs?: boolean; - [key: string]: any; - }; - constructor(options?: GraphOptions); - init: (options?: GraphOptions) => void; - load: (roots: { - [key: string]: any; - }, overwrite?: boolean) => { - [key: string]: any; - }; - setLoaders: (loaders: { - [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, props: any, key: string) => void; - }, replace?: boolean) => any; - runLoaders: (node: any, parent: any, properties: any, key: any) => void; - add: (properties: any, parent?: GraphNode | string, overwrite?: boolean) => GraphNode; - recursiveSet: (originCpy: any, parent: any, listeners: any, origin: any, overwrite?: boolean) => any; - remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; - run: (node: string | GraphNode, ...args: any[]) => any; - /** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners: (listeners: { - [key: string]: { - [key: string]: any; - }; - }) => void; - clearListeners: (node: GraphNode | string, listener?: string) => void; - get: (tag: string) => any; - getByUnique: (unique: string) => any; - set: (tag: string, node: GraphNode) => Map; - delete: (tag: string) => boolean; - list: () => string[]; - getListener: (nodeTag: string, key?: string, sub?: number) => Listener; - getProps: (node: GraphNode | string, getInitial?: boolean) => void; - subscribe: (nodeEvent: GraphNode | string, onEvent: string | GraphNode | ((...res: any) => void), args?: any[], key?: string | undefined, subInput?: boolean, target?: string | GraphNode, tkey?: string) => number; - unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; - setState: (update: { - [key: string]: any; - }) => void; -} -export declare function getAllProperties(obj: any): any[]; -export declare function instanceObject(obj: any): any; -export declare function isNativeClass(thing: any): boolean; -export declare function isFunction(x: any): "function" | "class" | "async" | "arrow" | ""; -export declare let getCallbackFromString: (a: any, graph: any) => (...inp: any[]) => any; -export declare const wrapArgs: (callback: any, argOrder: any, graph: any) => { - __callback: any; - __args: any[]; -}; diff --git a/dist/src/loaders/html/html.d.ts b/dist/src/loaders/html/html.d.ts deleted file mode 100644 index b7261cfd..00000000 --- a/dist/src/loaders/html/html.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -export declare function html(strings: TemplateStringsArray, ...args: any[]): (elm?: HTMLElement) => HTMLElement | DocumentFragment; -/** - * - * let htmlfunction = html`` //e.g. some html - * htmlfunction(document.body); //append the template string to the desired element, or just return the prepared template element - * - * Syntax highlighting with lit-html plugin: https://open-vsx.org/extension/meganrogge/template-string-converter - - // Example usage of the html function - document.addEventListener("DOMContentLoaded", () => { - const app = document.getElementById('app'); - - const title = document.createElement('h1'); - title.textContent = "Welcome to HTML Function Test"; - - const paragraph = document.createElement('p'); - paragraph.textContent = "This is a paragraph element created using native DOM API."; - - // Creating HTML structure using the html function - const content = html` -
-

This is a test

- ${title} -

This is a paragraph element created using the html function.

- ${paragraph} -
- `(); - - app.appendChild(content); - }); - -*/ -export declare function xml(strings: TemplateStringsArray, ...args: any[]): (elm?: Node, namespace?: string) => string; -/** Test: - * - * - const testXmlFunction = () => { - const namespace = "http://www.example.com/test"; - const resultContainer = document.createElement('div'); - - const testElement = document.createElementNS(namespace, 'testElement'); - testElement.textContent = "Test Content"; - - const xmlAppender = xml`Hello, ${'World'}! This is a ${testElement}.`; - const xmlString = xmlAppender(resultContainer, namespace); - - resultContainer.innerHTML += `
${xmlString}
`; - - console.log(xmlString); - document.body.appendChild(resultContainer); - }; - - testXmlFunction(); - * - * - */ diff --git a/dist/src/loaders/html/wc.loader.d.ts b/dist/src/loaders/html/wc.loader.d.ts deleted file mode 100644 index 26a594dc..00000000 --- a/dist/src/loaders/html/wc.loader.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { GraphNode, GraphNodeProperties, Graph } from '../../core/Graph'; -export { HTMLNodeProperties } from './html.loader'; -export declare const wchtmlloader: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; diff --git a/dist/src/loaders/methodstrings.d.ts b/dist/src/loaders/methodstrings.d.ts deleted file mode 100644 index 978aabc8..00000000 --- a/dist/src/loaders/methodstrings.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function methodstrings(node: any): void; diff --git a/dist/src/services/Service.d.ts b/dist/src/services/Service.d.ts deleted file mode 100644 index a5558998..00000000 --- a/dist/src/services/Service.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export type ServiceMessage = { - route?: string; - args?: any; - method?: string; - node?: string | GraphNode; - [key: string]: any; -}; -export type ServiceOptions = GraphOptions & { - services?: { - [key: string]: Service | Function | { - [key: string]: any; - }; - }; - restrict?: { - [key: string]: boolean; - }; -}; -export declare class Service extends Graph { - name: string; - restrict?: { - [key: string]: boolean; - }; - constructor(options?: ServiceOptions); - addServices: (services: { - [key: string]: Function | Graph | Service | { - [key: string]: any; - }; - }) => void; - handleMethod: (route: string, method: string, args?: any) => any; - handleServiceMessage(message: ServiceMessage): any; - handleGraphNodeCall(route: string | GraphNode, args: any): any; - transmit: (...args: any[]) => any | void; - receive: (...args: any[]) => any | void; - pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; - pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; - terminate: (...args: any) => void; - isTypedArray: typeof isTypedArray; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray: typeof spliceTypedArray; - ping: () => string; - echo: (...args: any) => any; - log: (...args: any) => boolean; - error: (...args: any) => boolean; -} -export declare function isTypedArray(x: any): boolean; -export declare const recursivelyAssign: (target: any, obj: any) => any; -export declare function spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; diff --git a/dist/src/services/http/boilerplate/index.d.ts b/dist/src/services/http/boilerplate/index.d.ts deleted file mode 100644 index 9e5b4a36..00000000 --- a/dist/src/services/http/boilerplate/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare function htmlBodyBoilerPlate(html: string | string[]): string; -export declare function scriptBoilerPlate(scripts: string | string[]): string; -export declare const defaultServiceWorker: (cacheExpirationDays?: number) => string; -export declare const defaultManifest: (pwaName?: string) => string; diff --git a/dist/src/services/remote/remote.routes.d.ts b/dist/src/services/remote/remote.routes.d.ts deleted file mode 100644 index cabf37e7..00000000 --- a/dist/src/services/remote/remote.routes.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -export declare const nodeTemplates: {}; -export declare const remoteGraphRoutes: { - transferNode: (properties: string | Function | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), connection: any | Worker | WebSocket, name?: string) => any; - setNode: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), name?: string) => any; - makeNodeTransferrable: (properties: GraphNodeProperties, name?: string) => {}; - getListenerJSON: () => any; - makeRootTransferrable: () => {}; - setTemplate: (properties: string | (() => any) | (GraphNodeProperties & { - __methods?: { - [key: string]: string | Function; - }; - }), name?: string) => string | false; - loadFromTemplate: (templateName: string, name?: string, properties?: { - [key: string]: any; - }) => any; - setMethod: (nodeTag: string, fn: string | (() => any), methodKey?: string) => boolean; - assignNode: (nodeTag: string, source: { - [key: string]: any; - }) => void; - getNodeProperties: (nodeTag: string) => {}; - proxyRemoteNode: (name: string, connection: any) => Promise; - transferClass: (classObj: any, connection: any | Worker | WebSocket, className?: string) => any; - receiveClass: (stringified: string, className?: string) => boolean; - transferFunction: (fn: Function, connection: any | Worker | WebSocket, fnName?: string) => any; - setGlobal: (key: string, value: any) => boolean; - assignGlobalObject: (target: string, source: { - [key: string]: any; - }) => boolean; - setValue: (key: string, value: any) => boolean; - assignObject: (target: string, source: { - [key: string]: any; - }) => boolean; - setGlobalFunction: (fn: any, fnName?: string) => boolean; - setGraphFunction: (fn: any, fnName?: string) => boolean; -}; diff --git a/dist/src/services/sessions/sessions.service.d.ts b/dist/src/services/sessions/sessions.service.d.ts deleted file mode 100644 index 2ee6d805..00000000 --- a/dist/src/services/sessions/sessions.service.d.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { Service, ServiceOptions } from "../Service"; -import { User } from "../router/Router"; -/** - * Sessions are a way to run a loop that monitors data structures to know procedurally when and what to update - * - * OneWaySession: source sends props to listener, define listener, source default is creating user - * SharedSession: two modes: - * Hosted: Host receives props from all users based on propnames, users receive hostprops - * Shared: All users receive the same props based on their own updates - * - * There's also these older stream API functions that are more pure for monitoring objects/arrays and updating new data e.g. out of a buffer. - * Need to esplain/demo all that too.... @@__@@ - */ -export type OneWaySessionProps = { - _id?: string; - settings?: { - listener: string; - source: string; - propnames: { - [key: string]: boolean; - }; - admins?: { - [key: string]: boolean; - }; - moderators?: { - [key: string]: boolean; - }; - password?: string; - ownerId?: string; - onopen?: (session: OneWaySessionProps) => void; - onhasupdate?: (session: OneWaySessionProps, updated: any) => void; - onmessage?: (session: OneWaySessionProps, updated: any) => void; - onclose?: (session: OneWaySessionProps) => void; - [key: string]: any; - }; - data?: { - [key: string]: any; - }; - lastTransmit?: string | number; - [key: string]: any; -}; -export type SessionUser = { - _id: string; - sessions: { - [key: string]: any; - }; - sessionSubs: { - [key: string]: { - onopenSub?: number; - onmessage?: (session: SharedSessionProps, update: any, user: SessionUser) => void; - onopen?: (session: SharedSessionProps, user: SessionUser) => void; - onclose?: (session: SharedSessionProps, user: SessionUser) => void; - }; - }; - [key: string]: any; -} & User; -export type SharedSessionProps = { - _id?: string; - settings?: { - name: string; - propnames: { - [key: string]: boolean; - }; - users?: { - [key: string]: boolean; - }; - host?: string; - hostprops?: { - [key: string]: boolean; - }; - inheritHostData?: boolean; - admins?: { - [key: string]: boolean; - }; - moderators?: { - [key: string]: boolean; - }; - spectators?: { - [key: string]: boolean; - }; - banned?: { - [key: string]: boolean; - }; - password?: string; - ownerId?: string; - onhasupdate?: (session: SharedSessionProps, updated: any) => void; - onopen?: (session: SharedSessionProps) => void; - onmessage?: (session: SharedSessionProps, updated: any) => void; - onclose?: (session: SharedSessionProps) => void; - [key: string]: any; - }; - data?: { - shared: { - [key: string]: { - [key: string]: any; - }; - }; - oneWay?: { - [key: string]: any; - }; - [key: string]: any; - }; - lastTransmit?: string | number; - [key: string]: any; -}; -export type StreamInfo = { - [key: string]: { - object: { - [key: string]: any; - }; - settings: { - keys?: string[]; - callback?: 0 | 1 | Function; - lastRead?: number; - [key: string]: any; - }; - onupdate?: (data: any, streamSettings: any) => void; - onclose?: (streamSettings: any) => void; - }; -}; -export declare class SessionsService extends Service { - name: string; - users: { - [key: string]: SessionUser; - }; - sessions: { - oneWay: { - [key: string]: OneWaySessionProps; - }; - shared: { - [key: string]: SharedSessionProps; - }; - }; - invites: { - [key: string]: { - [key: string]: { - session: OneWaySessionProps | SharedSessionProps | string; - endpoint?: string; - }; - }; - }; - constructor(options?: ServiceOptions, users?: { - [key: string]: SessionUser; - }); - getSessionInfo: (sessionIdOrName?: string, userId?: string) => {}; - openOneWaySession: (options?: OneWaySessionProps, sourceUserId?: string, listenerUserId?: string) => any; - openSharedSession: (options: SharedSessionProps, userId?: string) => any; - open: (options: any, userId?: string) => void; - updateSession: (options: OneWaySessionProps | SharedSessionProps, userId?: string) => any; - joinSession: (sessionId: string, userId: string, options?: SharedSessionProps | OneWaySessionProps, remoteUser?: boolean) => SharedSessionProps | OneWaySessionProps | false; - inviteToSession: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, inviteEndpoint?: string, remoteUser?: boolean) => void; - receiveSessionInvite: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, endpoint?: string) => string; - acceptInvite: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, remoteUser?: boolean) => Promise; - rejectInvite: (session: OneWaySessionProps | SharedSessionProps | string, userInvited: string, remoteUser?: boolean) => boolean; - leaveSession: (session: OneWaySessionProps | SharedSessionProps | string, userId: string, clear?: boolean, remoteUser?: boolean) => boolean; - deleteSession: (session: string | OneWaySessionProps | SharedSessionProps, userId: string, remoteUsers?: boolean) => boolean; - getFirstMatch(obj1: { - [key: string]: any; - }, obj2: { - [key: string]: any; - }): string | false; - swapHost: (session: OneWaySessionProps | SharedSessionProps | string, newHostId?: string, adoptData?: boolean, remoteUser?: boolean) => boolean; - subscribeToSession: (session: SharedSessionProps | OneWaySessionProps | string, userId: string, onmessage?: (session: SharedSessionProps | OneWaySessionProps, update: any, user: SessionUser) => void, onopen?: (session: SharedSessionProps | OneWaySessionProps, user: SessionUser) => void, onclose?: (session: SharedSessionProps | OneWaySessionProps, user: SessionUser) => void) => OneWaySessionProps | SharedSessionProps; - unsubsribeFromSession: (session: SharedSessionProps | OneWaySessionProps | string, userId?: string, clear?: boolean) => any; - sessionUpdateCheck: (sessionHasUpdate?: (session: OneWaySessionProps | SharedSessionProps, update: { - shared?: any; - oneWay?: any; - }) => void, transmit?: boolean) => any; - transmitSessionUpdates: (updates: { - oneWay: { - [key: string]: any; - }; - shared: { - [key: string]: any; - }; - }) => {}; - receiveSessionUpdates: (origin: any, update: string | { - oneWay: { - [key: string]: any; - }; - shared: { - [key: string]: any; - }; - }) => SessionUser; - getUpdatedUserData: (user: SessionUser) => {}; - userUpdateCheck: (user: SessionUser, onupdate?: (user: SessionUser, updateObj: { - [key: string]: any; - }) => void) => {}; - setUserProps: (user: string | SessionUser, props: string | { - [key: string]: any; - }) => boolean; - userUpdateLoop: { - __operator: (user: SessionUser, onupdate?: (user: SessionUser, updateObj: { - [key: string]: any; - }) => void) => {}; - __node: { - loop: number; - }; - }; - sessionLoop: { - __operator: (sessionHasUpdate?: (session: OneWaySessionProps | SharedSessionProps, update: { - shared?: any; - oneWay?: any; - }) => void, transmit?: boolean) => any; - __node: { - loop: number; - }; - }; - STREAMLATEST: number; - STREAMALLLATEST: number; - streamSettings: StreamInfo; - streamFunctions: any; - setStreamFunc: (name: string, key: string, callback?: 0 | 1 | Function) => boolean; - addStreamFunc: (name: any, callback?: (data: any) => void) => void; - setStream: (object?: {}, settings?: { - keys?: string[]; - callback?: Function; - }, streamName?: string, onupdate?: (update: any, settings: any) => void, onclose?: (settings: any) => void) => { - object: { - [key: string]: any; - }; - settings: { - [key: string]: any; - keys?: string[]; - callback?: 0 | Function | 1; - lastRead?: number; - }; - onupdate?: (data: any, streamSettings: any) => void; - onclose?: (streamSettings: any) => void; - }; - removeStream: (streamName: any, key: any) => boolean; - updateStreamData: (streamName: any, data?: {}) => false | { - [key: string]: any; - }; - getStreamUpdate: (streamName: string) => {}; - getAllStreamUpdates: () => {}; - streamLoop: { - __operator: () => {}; - __node: { - loop: number; - }; - }; -} diff --git a/dist/src/services/webrtc/WebRTC.browser.d.ts b/dist/src/services/webrtc/WebRTC.browser.d.ts deleted file mode 100644 index 74a711f8..00000000 --- a/dist/src/services/webrtc/WebRTC.browser.d.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type WebRTCProps = { - _id?: string; - channels?: { - [key: string]: (true | RTCDataChannelInit | RTCDataChannel); - }; - config?: RTCConfiguration; - description?: RTCSessionDescription | string; - offer?: RTCOfferOptions; - hostcandidates?: { - [key: string]: RTCIceCandidate; - }; - peercandidates?: { - [key: string]: RTCIceCandidate; - }; - candidates?: { - [key: string]: RTCIceCandidate; - }; - answer?: RTCAnswerOptions; - ontrack?: (ev: RTCTrackEvent) => void; - removetrack?: (ev: MediaStreamTrackEvent) => void; - onicecandidate?: (ev: RTCPeerConnectionIceEvent) => void; - onicecandidateerror?: (ev: Event) => void; - onnegotiationneeded?: (ev: Event, description: RTCSessionDescription) => void; - ondatachannel?: (ev: RTCDataChannelEvent) => void; - ondata?: (ev: MessageEvent, channel: RTCDataChannel, room: any) => void; - onconnectionstatechange?: (ev: Event) => void; - oniceconnectionstatechange?: (ev: Event) => void; - onclose?: (rtc: WebRTCInfo) => void; - caller?: string; - remoteId?: string; - [key: string]: any; -}; -export type WebRTCInfo = { - _id: string; - rtc: RTCPeerConnection; - senders?: (RTCRtpSender | undefined)[]; - receivers?: (RTCRtpReceiver | undefined)[]; - streams?: (MediaStream | undefined)[]; - polite?: boolean; - videoSender?: RTCRtpSender; - audioSender?: RTCRtpSender; - videoStream?: MediaStream; - audioStream?: MediaStream; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, channelId?: string) => Promise; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => boolean; - graph: WebRTCfrontend; -} & WebRTCProps; -export declare class WebRTCfrontend extends Service { - name: string; - rtc: { - [key: string]: WebRTCInfo; - }; - unanswered: { - [key: string]: WebRTCProps; - }; - iceServers: RTCIceServer[]; - connections: { - rtc: { - [key: string]: WebRTCInfo; - }; - }; - constructor(options?: ServiceOptions, iceServers?: RTCIceServer[]); - openRTC: (options?: WebRTCProps) => Promise; - open: (options?: WebRTCProps) => Promise; - addIceCandidate: (rtc: RTCPeerConnection | string, candidate: RTCIceCandidate) => Promise; - receiveCallInformation: (options: WebRTCProps) => Promise; - answerCall: (options: WebRTCProps | string) => Promise; - rejectCall: (options: WebRTCProps | string) => boolean; - negotiateCall: (rtc: RTCPeerConnection | string, description: string | RTCSessionDescription, polite?: boolean) => Promise; - createOffer(rtc: RTCPeerConnection | string, options: WebRTCProps | string): Promise; - createAnswer(rtc: RTCPeerConnection | string, options: WebRTCProps | string): Promise; - answerPeer: (rtc: RTCPeerConnection | string, options: WebRTCProps | string) => Promise; - createStream: (options: { - [key: string]: { - track: MediaStreamTrack | MediaTrackConstraints; - onended: (ev: any) => void; - onmute: (ev: any) => void; - onunmute: (ev: any) => void; - }; - }) => MediaStream; - addUserMedia: (rtc: RTCPeerConnection, options?: MediaStreamConstraints, info?: WebRTCInfo) => Promise; - addTrack: (rtc: RTCPeerConnection, track: MediaStreamTrack, stream: MediaStream) => RTCRtpSender; - removeTrack: (rtc: RTCPeerConnection, sender: RTCRtpSender) => boolean; - addDataChannel: (rtc: RTCPeerConnection, name: string, options?: RTCDataChannelInit) => RTCDataChannel; - enableAudio: (call: WebRTCInfo, audioOptions?: boolean | (MediaTrackConstraints & { - deviceId?: string; - })) => Promise; - enableVideo: (call: WebRTCInfo, videoOptions?: (MediaTrackConstraints & { - deviceId?: string; - optional?: { - minWidth: number; - }[]; - }), includeAudio?: boolean | (MediaTrackConstraints & { - deviceId?: string; - })) => Promise; - disableAudio(call: WebRTCInfo): void; - disableVideo(call: WebRTCInfo): void; - transmit: (data: ServiceMessage | any, id?: string, channel?: string | RTCDataChannel) => boolean; - terminate: (rtc: RTCPeerConnection | WebRTCInfo | string) => boolean; - request: (message: ServiceMessage | any, channel: RTCDataChannel, _id: string, method?: string) => Promise; - runRequest: (message: any, channelOrRtcId: RTCDataChannel | string, callbackId: string | number) => any; - subscribeRTC: (route: string, rtcId: string, args?: any[], key?: string, subInput?: boolean, channel?: string | RTCDataChannel) => number; - subscribeToRTC: (route: string, rtcId: string, channelId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => Promise; -} diff --git a/dist/src/services/wss/WSS.browser.d.ts b/dist/src/services/wss/WSS.browser.d.ts deleted file mode 100644 index e232e404..00000000 --- a/dist/src/services/wss/WSS.browser.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -export type WSSRoute = { - socket?: WebSocketInfo; - transferFunctions?: { - [key: string]: Function; - }; - transferClasses?: { - [key: string]: Function; - }; - parentRoute?: string; - callback?: string; - stopped?: boolean; - blocking?: boolean; - init?: string; - initArgs?: any[]; -} & GraphNodeProperties & WebSocketProps; -export type WebSocketProps = { - host: string; - port: number; - path?: string; - debug?: boolean; - onmessage?: (data: string | ArrayBufferLike | Blob | ArrayBufferView, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onopen?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onclose?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onerror?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - protocol?: 'ws' | 'wss'; - keepState?: boolean; - type?: 'socket'; - _id?: string; - [key: string]: any; -} & GraphNodeProperties; -export type WebSocketInfo = { - socket: WebSocket; - address: string; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean) => any; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => boolean; - _id?: string; - graph: WSSfrontend; -} & WebSocketProps & GraphNode; -export declare class WSSfrontend extends Service { - name: string; - sockets: { - [key: string]: WebSocketInfo & GraphNode; - }; - connections: { - sockets: { - [key: string]: { - socket: WebSocket; - address: string; - send: (message: any) => void; - request: (message: any, method?: string) => Promise; - post: (route: any, args?: any) => void; - run: (route: any, args?: any, method?: string) => Promise; - subscribe: (route: any, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => any; - unsubscribe: (route: any, sub: number) => Promise; - terminate: () => boolean; - _id?: string; - graph: WSSfrontend; - } & { - [key: string]: any; - host: string; - port: number; - path?: string; - debug?: boolean; - onmessage?: (data: string | ArrayBufferView | ArrayBufferLike | Blob, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onopen?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onclose?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - onerror?: (ev: any, ws: WebSocket, wsinfo: WebSocketInfo) => void; - protocol?: "ws" | "wss"; - keepState?: boolean; - type?: "socket"; - _id?: string; - } & GraphNodeProperties & GraphNode; - }; - }; - constructor(options?: ServiceOptions); - loadWebSocketRoute: (node: WebSocketProps & GraphNode) => WebSocketInfo; - socketloader: { - websockets: (node: WebSocketProps & GraphNode, parent: WebSocketProps & GraphNode, graph: WSSfrontend, roots: any) => void; - }; - openWS: (options?: WebSocketProps) => WebSocketInfo; - open: (options?: WebSocketProps) => WebSocketInfo; - transmit: (data: string | ArrayBufferLike | Blob | ArrayBufferView | ServiceMessage, ws: WebSocket) => boolean; - terminate: (ws: WebSocket | string) => boolean; - request: (message: ServiceMessage | any, ws: WebSocket, _id: string, method?: string) => Promise; - runRequest: (message: any, ws: WebSocket | string, callbackId: string | number) => any; - subscribeSocket: (route: string, socket: WebSocket | string, args?: any[], key?: string, subInput?: boolean) => number; - subscribeToSocket: (route: string, socketId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean) => Promise; -} diff --git a/docs/Graph.md b/docs/Graph.md index dc371f39..ce697bf9 100644 --- a/docs/Graph.md +++ b/docs/Graph.md @@ -5,7 +5,7 @@ The Graph and GraphNode classes are an implementation of the acyclic graphs and ### First Steps -To create a Graph, simply declare an object as your "roots" or your program hierarchy with lists of node definitions, then load it into the graph. After that your nodes become interactive through both the definition objects and through accessors on the Graph instance. +To create a Graph, simply declare an object as your "tree" or your program hierarchy with lists of node definitions, then load it into the graph. After that your nodes become interactive through both the definition objects and through accessors on the Graph instance. ```ts @@ -40,12 +40,12 @@ let nodeB = { } }; -let roots = { +let tree = { nodeA, nodeB }; -let graph = new Graph({ roots }); +let graph = new Graph({tree}); nodeB.x += 1; //should trigger nodeA listener 'nodeB.x' @@ -70,19 +70,18 @@ Graph nodes can have many properties, and even more if you specify loaders on th ```ts type GraphNodeProperties = { - __props?:Function|{[key:string]:any}|GraphNodeProperties|GraphNode, //Proxy objects or from a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. + __props?:Function|GraphNodeProperties, //a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. __operator?:((...args:any[])=>any)|string, //The 'main' function of the graph node, children will call this function if triggered by a parent. Functions passed as graphnodeproperties become the operator which can set state. - __children?:{[key:string]:any}, //child nodes belonging to this node, e.g. for propagating results - __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true, subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs + __children?:{[key:string]:GraphNodeProperties}, //child nodes belonging to this node, e.g. for propagating results + __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true,subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs __onconnected?:((node)=>void|((node)=>void)[]), //what happens once the node is created? __ondisconnected?:((node)=>void|((node)=>void)[]), //what happens when the node is deleted? __node?:{ //node specific properties, can contain a lot more things tag?:string, state?:EventHandler, //by default has a global shared state + inputState?:boolean //we can track inputs on a node, subscribe to state with 'input' on the end of the tag or 'tag.prop' [key:string]:any }, - __args?:any[], //can structure input arguments, include '__result' when generically calling operators for where to pass the original input in in a set of arguments - __callable?:boolean, //we can have the graphnode return itself as a callable function with private properties [key:string]:any } ``` @@ -96,7 +95,6 @@ When a node is subscribed to it enhances itself with getters and setters that al The `__operator` is where default functions for nodes are stored. This lets you pass class methods in for instance as node definitions and then they can gain state and listener access across the program. Arrow functions on classes are nice because they will remain bound to their parent class instance even when applied to nodes. We use this extensively to subscribe across remote endpoints to outputs of specific methods or arbitrary states e.g. a game state. -The `__callable` property will be applied to nodes when functions are provided as property definitions, this means nodes will appear as if they are functions and all properties will be private (but still there and subscribable on trees!). This can help you make your node trees look more functional and call operators like `node(1)`. ### Graph Options @@ -107,13 +105,13 @@ type Loader = ( node:GraphNode, parent:Graph|GraphNode, graph:Graph, - roots:any, + tree:any, properties:GraphNodeProperties, key:string )=>void; type GraphOptions = { - roots?:{[key:string]:any}, //node definitions, the 'forest' + tree?:{[key:string]:any}, loaders?:{ [key:string]:Loader | { init?:Loader, @@ -147,7 +145,7 @@ Here is a bigger graph from [`examples/graph`](../examples/graph/): import {Graph, loaders} from 'graphscript' -let roots = { +let tree = { nodeA: { x:5, @@ -211,7 +209,7 @@ let roots = { }; let graph = new Graph({ - roots, + tree, loaders }); diff --git a/docs/Service.md b/docs/Service.md index b968b988..b4c6c431 100644 --- a/docs/Service.md +++ b/docs/Service.md @@ -18,7 +18,7 @@ import worker from 'graphscript/services/worker/Worker' //includes Math loaded a //This is a useless example of running math callbacks through workers // in a quick chain then feeding the output to the document body. let workers = new WorkerService({ - roots:{ + tree:{ worker1:{ workerUrl:worker, callback:'log10' diff --git a/docs/services/cmd/cmd.service.md b/docs/services/cmd/cmd.service.md index add66f63..7717b34e 100644 --- a/docs/services/cmd/cmd.service.md +++ b/docs/services/cmd/cmd.service.md @@ -34,10 +34,10 @@ type CMDInfo = { import { CMDService } from "./CMD.node"; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; const service = new CMDService({ - routes:[remoteGraphRoutes] + routes:[unsafeRoutes] }); //now we can send/receive messages console.log("Child process listening...") @@ -51,10 +51,10 @@ Then create childprocess.js in your root (for this example) ```ts import { CMDService } from "./CMD.node"; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; const service = new CMDService({ - routes:[remoteGraphRoutes] + routes:[unsafeRoutes] }); //now we can send/receive messages console.log("Child process listening...") diff --git a/docs/services/http/http.browser.md b/docs/services/http/http.browser.md index 31be4ff7..14a34698 100644 --- a/docs/services/http/http.browser.md +++ b/docs/services/http/http.browser.md @@ -16,8 +16,4 @@ http.listen() ``` -You can listen to specific paths independently and customize the fetch responses using cloned responses (so normal page flow is not disturbed). - -To call a node on the HTTPbackend, you can specify any url e.g. `https://localhost:8080/ping` and a method e.g. GET, POST, or any arbitrary method with inputs in the body. This will return results or if a string template is specified on a GET request then it will return a page response to you. You can easily specify site redirects this way, too, or specify as many different custom methods on a single URL as you want. - -Pretty cool! Lots of untapped potential here. +You can listen to specific paths independently and customize the fetch responses using cloned responses (so normal page flow is not disturbed). \ No newline at end of file diff --git a/docs/services/http/http.node.md b/docs/services/http/http.node.md index 32efa9c5..20f9c248 100644 --- a/docs/services/http/http.node.md +++ b/docs/services/http/http.node.md @@ -2,8 +2,6 @@ The HTTPbackend service puts the power of graphs and services into a full featured HTTP or HTTPS server. This lets you serve static assets or dynamic content straight from routes all through standard or customizable http fetch calls. This means you can implement your entire own http protocols and state machines willy nilly and feel like a backend master, it's a lot of fun! -To call a node on the HTTPbackend, you can specify any url e.g. https://localhost:8080/ping and a method e.g. GET, POST, or any arbitrary method with inputs in the body. This will return results or if a string template is specified on a GET request then it will return a page response to you. You can easily specify site redirects this way, too, or specify as many different custom methods on a single URL as you want. - See `examples/httpserver` to get started with a simple implementation. The extended `RouteProp` when declaring routes/nodes in Service.ts was made for this: @@ -108,10 +106,8 @@ http.setupServer( Easy! -The page specification lets you quickly set up static and dynamic page behaviors, if you pass an object then the routes are interpreted as node definitions which you can make as complicated as you want to run graph trees. Then a REST API can make any common or custom HTTP requests with any jsonifiable inputs in the request body. - -If a node's .get/.template string returns a findable file path or remote url, it will see if it can load the file on the server. This is a nice way for dynamic file routing. +The page specification lets you quickly set up static and dynamic page behaviors, if you pass an object then the routes are interpreted as node definitions which you can make as complicated as you want to run graph trees. -Later we need to implement security features but you can easily add custom features into the onrequest functions in each URL, e.g. to require passwords in the request body. +If a node's .get/.template returns a file path it will see if it can load the file on the server, just a nice way for dynamic file routing. -From here we can apply websocket, sse, and other services to build efficient web servers. See `examples/httpserver` for a quick implementation +From here we can apply websocket, sse, and other services to build efficient web servers. See `examples/httpserver` for a quick implementation \ No newline at end of file diff --git a/docs/services/router/Router.md b/docs/services/router/Router.md index 636d73ff..12241468 100644 --- a/docs/services/router/Router.md +++ b/docs/services/router/Router.md @@ -109,34 +109,23 @@ router.addUser({_id:'me'},{socketId:'socket12345678'}) //which returns via promise: export type User = { //users have macros to call grouped connections generically, based on what's available _id:string, - - //work with an available connection, you can set the preferred order (e.g. sse, websockets, http) send:(...args:any[])=>any, request:(...args:any[])=>Promise|Promise[]|undefined, post:(...args:any[])=>void, run:(...args:any[])=>Promise|Promise[]|undefined, subscribe:(...args:any[])=>Promise|Promise[]|undefined, unsubscribe:(...args:any[])=>Promise|Promise[]|undefined, - - //work with all of the connections associated with a user - sendAll:(...args:any[])=>any, - requestAll:(...args:any[])=>Promise|Promise[]|undefined, - postAll:(...args:any[])=>void, - runAll:(...args:any[])=>Promise|Promise[]|undefined, - subscribeAll:(...args:any[])=>Promise|Promise[]|undefined, - unsubscribeAll:(...args:any[])=>Promise|Promise[]|undefined, - terminate:(...args:any[]) => boolean, onclose?:(user:User)=>void, [key:string]:any -} +} & Partial ``` The user's send/post/etc. handles will search available connections sourced to that user and use the best connection that has the available functionality based on matching methods. The services we have all follow the same straightforward, fully functional (including all of the source API features for each type of protocol still on-hand), and reproducible format for pooling and matching connections for easier high level integration and a fairly limited learning curve for the amount of features you can pack together in a few dozen lines. It's very performant, while you still have full control over your servers and services as you need deeper specifications. -All together now with sessions and mixed SSE + Websocket connections and a configurable http/https server... See backend.ts in `examples/advanced/webrtcrouter` +All together now with sessions and mixed SSE + Websocket connections and a configurable http/https server... See backend.ts in `examples/webrtcrouter` ```ts diff --git a/docs/services/worker/worker.md b/docs/services/worker/worker.md index fdd1278e..89d0168d 100644 --- a/docs/services/worker/worker.md +++ b/docs/services/worker/worker.md @@ -5,7 +5,7 @@ To use workers within our graph hierarchy, we need to establish a worker service e.g. worker.ts ```ts //functionality -import { WorkerService, workerCanvasRoutes, workerCanvasRoutes, remoteGraphRoutes, ECSService } from 'graphscript'; +import { WorkerService, workerCanvasRoutes, workerCanvasRoutes, unsafeRoutes, ECSService } from 'graphscript'; //wonder if we can have a scheme to dynamic import within the services? e.g. to bring in node-only or browser-only services without additional workers @@ -17,9 +17,9 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope //GPUService, ECSService } - roots:{ + tree:{ ...workerCanvasRoutes, - ...remoteGraphRoutes //allows dynamic route loading + ...unsafeRoutes //allows dynamic route loading }, includeClassName:false }); @@ -35,4 +35,4 @@ This worker implements several useful services including a dedicated gpu.js inst Now you can post commands and subscribe to results easily, or chain threads via message ports easily (see worker.service.md). -Note the remoteGraphRoutes allow writing functions, properties, and classes to the thread from another thread. Use with caution! \ No newline at end of file +Note the unsafeRoutes allow writing functions, properties, and classes to the thread from another thread. Use with caution! \ No newline at end of file diff --git a/docs/services/worker/worker.service.md b/docs/services/worker/worker.service.md index 5e1a2675..b80c1e75 100644 --- a/docs/services/worker/worker.service.md +++ b/docs/services/worker/worker.service.md @@ -83,7 +83,7 @@ let worker2 = workers.addWorker({url:worker}); const portId = workers.establishMessageChannel(worker1.worker,worker2.worker) -//if the remoteGraphRoutes are enabled on the worker you can quickly write in functions from the main thread +//if unsafeService is enabled on the worker you can quickly write in functions from the main thread workers.transferFunction( worker1, function add1(input) { @@ -146,7 +146,7 @@ const router = new Router({ console.log(router) -let ret = router.load({ +let ret = router.setTree({ 'main':{ tagName:'div', __children:{ @@ -203,7 +203,7 @@ Worker: ```ts import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, //GPUService } from 'graphscript'/////"../../GraphServiceRouter/index";//from 'graphscript' @@ -213,10 +213,10 @@ declare var WorkerGlobalScope; if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { const worker = new WorkerService({ - roots:[ + tree:[ //GPUService as any, ...workerCanvasRoutes, - ...remoteGraphRoutes //allows dynamic route loading + ...unsafeRoutes //allows dynamic route loading ], includeClassName:false }); @@ -471,7 +471,7 @@ And to set up the worker, we add an intermediate function to the worker's `setup import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, ECSService, Systems @@ -494,7 +494,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope routes:[ //GPUService, ECSService, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading { ...workerCanvasRoutes, receiveThreeCanvas:function(options:WorkerCanvasReceiveProps){ //modified canvas receiver that installs desired threejs modules diff --git a/examples/example.png b/example.png similarity index 100% rename from examples/example.png rename to example.png diff --git a/examples/advanced/audiofeedback/index.html b/examples/3dmodel/index.html similarity index 100% rename from examples/advanced/audiofeedback/index.html rename to examples/3dmodel/index.html diff --git a/examples/loaders/3dmodel/index.ts b/examples/3dmodel/index.ts similarity index 79% rename from examples/loaders/3dmodel/index.ts rename to examples/3dmodel/index.ts index 2f0481c5..a7d0d4d8 100644 --- a/examples/loaders/3dmodel/index.ts +++ b/examples/3dmodel/index.ts @@ -1,5 +1,6 @@ import * as B from 'babylonjs' -import { Graph, htmlloader } from '../../../index'; +import propsLoader from '../../core/loaders/props/props.loader'; +import { Graph, htmlloader } from '../../index'; let canvas = document.createElement('canvas'); @@ -94,14 +95,17 @@ let modelLoader = (node, parent, graph) => { node.rotation = (node.rotation as B.Vector3).add(parent.rotation); } - - let __listeners = { - [parent.__node.tag+'.position']:function(newP) {node.position = (node.__localPosition as B.Vector3).add(newP);}, - [parent.__node.tag+'.rotation']:function(newR) {node.rotation = (node.__localRotation as B.Vector3).add(newR);}, - - }; - if(node.__listeners) Object.assign(node.__listeners,__listeners); - else node.__listeners = __listeners; + graph.subscribe( + parent.__node.tag+'.position', + node.__node.tag, + function(newP) {node.position = (node.__localPosition as B.Vector3).add(newP);} + ); + + graph.subscribe( + parent.__node.tag+'.rotation', + node.__node.tag, + function(newR) {node.rotation = (node.__localRotation as B.Vector3).add(newR);}, + ); } } } @@ -120,10 +124,13 @@ type __transition = { let cameraLoader = (node, parent, graph) => { let animating = true; - if(!node.__props && parent.__props instanceof B.FreeCamera) {node.__props = parent.__props; node.__proxyObject(node.__props); } + + if(!node.__props && parent.__props instanceof B.FreeCamera) node.__props = parent.__props + if(node.__props instanceof B.FreeCamera) { if(node.__transition) { - node.__setOperator(()=>{ + + node.__operator = () => { let lastTime = performance.now()*0.001; let startTime = lastTime; let startPos = (node.position as B.Vector3).clone(); @@ -146,16 +153,8 @@ let cameraLoader = (node, parent, graph) => { let currTime = performance.now()*0.001; let dT = (currTime - startTime) / node.__transition.duration; - - if (currTime - startTime >= node.__transition.duration) { - if(node.__transition.position) { - node.position = node.__transition.position; - } - if(node.__transition.rotation) { - node.rotation = node.__transition.rotation; - } - } - else { + if(node.__transition.position) { + if(node.__transition.rotation) { let newRot = startRot.add((node.__transition.rotation as B.Vector3).subtract(startRot).scale(dT)) if(node.__transition.rinterp) newRot = node.__transition.rinterp(newRot,node.rotation,currTime,startTime); @@ -163,22 +162,20 @@ let cameraLoader = (node, parent, graph) => { } else if (node.__transition.target) { (node.__props as B.FreeCamera).setTarget(node.__transition.target); } - if(node.__transition.position) { - let newP = startPos.add((node.__transition.position as B.Vector3).subtract(startPos).scale(dT)) - if(node.__transition.pinterp) newP = node.__transition.pinterp(newP,node.position,currTime,startTime); - node.position = newP; - - lastTime = currTime; - await new Promise(async (res)=>{requestAnimationFrame(async ()=>{res(await transition())})}); - } - return true; + + let newP = startPos.add((node.__transition.position as B.Vector3).subtract(startPos).scale(dT)) + if(node.__transition.pinterp) newP = node.__transition.pinterp(newP,node.position,currTime,startTime); + node.position = newP; + lastTime = currTime; + await new Promise(async (res)=>{requestAnimationFrame(async ()=>{res(await transition())})}); } + return true; } if(node.__transition.delay) { return new Promise ((res) => {setTimeout(async()=>{ res(await transition()); }, node.__transition.delay);}); } else return new Promise (async (res) => {res(await transition()); }); - }); + }; } } @@ -189,12 +186,13 @@ let cameraLoader = (node, parent, graph) => { } let graph = new Graph({ - roots:model, - loaders:{ + tree:model, + loaders:[ + propsLoader, htmlloader, modelLoader, cameraLoader - } + ] }); engine.runRenderLoop(function(){ @@ -210,4 +208,5 @@ window.addEventListener('resize', function(){ setTimeout(()=>{ engine.resize(); graph.run('camera'); + },0.1) diff --git a/examples/loaders/3dmodel/package-lock.json b/examples/3dmodel/package-lock.json similarity index 97% rename from examples/loaders/3dmodel/package-lock.json rename to examples/3dmodel/package-lock.json index e3132522..9e6994c0 100644 --- a/examples/loaders/3dmodel/package-lock.json +++ b/examples/3dmodel/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp5631", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "babylonjs": "^5.34.0", "web-worker": "^1.2.0" diff --git a/examples/loaders/3dmodel/package.json b/examples/3dmodel/package.json similarity index 96% rename from examples/loaders/3dmodel/package.json rename to examples/3dmodel/package.json index 880ac2df..469ac3a5 100644 --- a/examples/loaders/3dmodel/package.json +++ b/examples/3dmodel/package.json @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "babylonjs": "^5.34.0", "web-worker": "^1.2.0" diff --git a/examples/editing/tinybuild.config.js b/examples/3dmodel/tinybuild.config.js similarity index 95% rename from examples/editing/tinybuild.config.js rename to examples/3dmodel/tinybuild.config.js index 1f475b48..6a131f9b 100644 --- a/examples/editing/tinybuild.config.js +++ b/examples/3dmodel/tinybuild.config.js @@ -1,7 +1,7 @@ const config = { bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" + "index.ts" ], outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags //outdir:[] //exit point files, define for multiple bundle files @@ -20,10 +20,10 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8081, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 2020, //hotreload websocket server port + hotreload: 5001, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) diff --git a/examples/3dmodel/yarn.lock b/examples/3dmodel/yarn.lock new file mode 100644 index 00000000..dcacf327 --- /dev/null +++ b/examples/3dmodel/yarn.lock @@ -0,0 +1,13 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +babylonjs@^5.34.0: + version "5.38.0" + resolved "https://registry.yarnpkg.com/babylonjs/-/babylonjs-5.38.0.tgz#7031542323835b159fde7e4984f6c33a8c40a08f" + integrity sha512-9I8++4lwuLBGPJSyp3CJ4tX6AjUuLO3/wUpUe7prpRx38/gw/5SSl9MYz+u/4bghM8b/xxPUixf41nyDoyfgJA== + +web-worker@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/web-worker/-/web-worker-1.2.0.tgz#5d85a04a7fbc1e7db58f66595d7a3ac7c9c180da" + integrity sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA== diff --git a/examples/README.md b/examples/README.md index 0f821917..135a1643 100644 --- a/examples/README.md +++ b/examples/README.md @@ -6,4 +6,23 @@ There are buildable examples in this folder. We will be adding more starter proj - BLE and USB Debugger App, with multithreading: https://github.com/joshbrew/device_debugger - HTIL collab: https://github.com/brainsatplay/htil -- Low code editor: https://github.com/brainsatplay/editor \ No newline at end of file +- Low code editor: https://github.com/brainsatplay/editor + + +## Tested (12/18/22) +- [ ] 3D Model (~) + - NOTE: The model comes out weird and is missing objects... +- [ ] Audiofeedback +- [ ] EEG Neurofeedback +- [x] Graph +- [x] HTML + - NOTE: Must still switch over to new solution from ESCode +- [ ] HTTP Server +- [ ] WebRTC Router (~) + - NOTE: Just nothing is happening... +- [ ] Worker Canvas + - NOTE: Why are you setting tree with self? This makes the loaders interpreted as nodes...and nothing goes on when removed +- [ ] Worker ECS + - NOTE: Same as above +- [ ] Worker Three.js + - NOTE: Fails to load three.js as a dependency \ No newline at end of file diff --git a/examples/advanced/webrtc/.gitignore b/examples/advanced/webrtc/.gitignore deleted file mode 100644 index ac756779..00000000 --- a/examples/advanced/webrtc/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ - -dist -**/node_modules/** -**/*.pem -**/*.pfxs -**/*.key -**/*.lock -**/package-lock.json -**/*.key -**/*.log diff --git a/examples/advanced/webrtc/backend/package.json b/examples/advanced/webrtc/backend/package.json deleted file mode 100644 index 0e734865..00000000 --- a/examples/advanced/webrtc/backend/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tinybuildapp1477", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "type": "module", - "scripts": { - "start": "tinybuild && node dist/server.js", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "", - "dependencies": {}, - "devDependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} \ No newline at end of file diff --git a/examples/advanced/webrtc/backend/server.ts b/examples/advanced/webrtc/backend/server.ts deleted file mode 100644 index 0030ad35..00000000 --- a/examples/advanced/webrtc/backend/server.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { Router, HTTPbackend, WSSbackend, ServerProps, SSEbackend, SessionsService, SocketServerProps, SSEProps, User, OneWaySessionProps, SharedSessionProps } from '../../../../index.node' - - -const router = new Router({ - graph:{ - sessions:SessionsService, - wss:WSSbackend, - sse:SSEbackend, - http: { - service: HTTPbackend, - config:{ - protocol:'http', - host:'localhost', - port:8081, - pages:{ - '/':{ - template:'./index.html' - } - }, - onopen:(served) => { - router.openConnection( - 'wss', - { - server:served.server, - host:served.host, - port:8081, - path:'wss', - onconnection:(ws,req,serverinfo,id)=>{ - ws.send('Hello from WSS!'); - } - } as SocketServerProps - ) - - router.openConnection( - 'wss', - { - server:served.server, - host:served.host, - port:7000, - path:'hotreload', - onconnection:(ws)=>{ - ws.send('Hot reload port opened!'); - } - } as SocketServerProps - ) - - router.openConnection( - 'sse', - { - server:served.server, - path:'sse', - channels:['test'], - onconnection:(session,sseinfo,id,req,res)=>{ - console.log('pushing sse!') - session.push('Hello from SSE!'); - sseinfo.channels.forEach( - (c:string) => sseinfo.channel.broadcast( - 'SSE connection at '+req.headers.host+'/'+req.url, c - ) - ); - } - } as SSEProps - ) - } - } as ServerProps - } - } -}); - - - -router.addUser({ - _id:'admin' -}); - -let session = (router.services.sessions as SessionsService).openSharedSession( - { - _id:'webrtcrooms', - settings:{ - name:'webrtcrooms', - propnames:{ - rooms:true //if these props are updated on the user object we'll return them - }, - onopen:(session)=>{ - console.log("Session Started:",session); - }, - onhasupdate:(session, update)=>{ - console.log("Session Has Update:", update, session); - }, - onclose:(session)=>{ - console.log("Session closed!", session); - } - } - }, - 'admin' -); - -//fires when a session in the loop has an update -function sessionHasUpdate ( - session:OneWaySessionProps|SharedSessionProps, - update:{shared?:any,oneWay?:any} -){ - console.log("Session Update:",session,update); -} - -router.run('sessionLoop',sessionHasUpdate); - -//add users to a global session -router.subscribe('addUser', (user:User) => { - console.log('new user!', user._id); - if(typeof user === 'object') { - let joined = (router.services.sessions as SessionsService).joinSession('webrtcrooms', user._id, undefined, true); - } -}); \ No newline at end of file diff --git a/examples/advanced/webrtc/backend/tinybuild.config.js b/examples/advanced/webrtc/backend/tinybuild.config.js deleted file mode 100644 index 7811957e..00000000 --- a/examples/advanced/webrtc/backend/tinybuild.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "server.ts" - ], - outfile: "dist/server", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:'dist' //exit point folder, define for multiple entryPoints - bundleBrowser: false, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files // { platform:'node' } //etc you can also supply an object here to add more specific esbuild settings - bundleTypes: false, //create .d.ts files, //you need a .tsconfig for this to work - bundleNode: true, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - //bundleIIFE:false, //create an iife build, this is compiled temporarily to create the types files and only saved with bundleIIFE:true - //bundleCommonJS:false, //cjs format outputted as .cjs - minify: true, - sourcemap: false, - //plugins:{} //custom esbuild plugins? e.g. esbuild-sass-plugin for scss support - //includeDefaultPlugins:true //true by default, includes the presets for the streaming imports, worker bundling, and auto npm install - //blobWorkers:true, //package workers as blobs or files? blobs are faster but inflate the main package size - //workerBundler:{minifyWhitespace:true} //bundler settings specific to the worker. e.g. apply platform:'node' when bundling node workers, - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } - // outputs:{ //overwrites main config settings for specific use cases - // node:{ //e.g. for bundleNode - // // external:[] //externals for node environment builds - // }, - // //commonjs:{} //bundleCommonJS - // //browser:{} - // //esm:{} - // iife:{ - // // external:[] //we only use the iife for types so it doesn't really matter if it bundles node, just note otherwise if you need iife for some obscure reason - // } - // }, - - //refer to esbuild docs for more settings - }, - server: false// { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - // debug: false, - // protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - // host: "localhost", //'localhost' or '127.0.0.1' etc. - // port: 8080, //e.g. port 80, 443, 8000 - // //redirect: 'http://localhost:8082' //instead of serving the default content, redirect ot another url e.g. another server - // startpage: "index.html", //home page - // socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - // hotreload: 5000, //hotreload websocket server port - // reloadscripts: false, //hot swap scripts, can break things if script handles initializations, otherwise css, link, srcs all hot swap without page reloading fairly intelligently - // //delay: 50, //millisecond delay on the watch command for hot reloading - // //pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - // //watch: ['../'], //watch additional directories other than the current working directory - // python: false,//7000, //quart server port (configured via the python server script file still) - // python_node:7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - // errpage: 'node_modules/tinybuild/tinybuild/node_server/other/404.html', //default error page, etc. - // certpath:'node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem',//if using https, this is required. See cert.pfx.md for instructions - // keypath:'node_modules/tinybuild/tinybuild/node_server/ssl/key.pem'//if using https, this is required. See cert.pfx.md for instructions - // } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.css b/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.css deleted file mode 100644 index 79393f29..00000000 --- a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.css +++ /dev/null @@ -1,78 +0,0 @@ -body { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - height: 100vh; - margin: 0; - background-color: #f7f7f7; - font-family: Arial, sans-serif; -} - -.container { - width: 100%; - max-width: 800px; - padding: 20px; - box-sizing: border-box; - background-color: white; - border-radius: 10px; - box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); -} - -.canvas-container { - overflow: hidden; -} - -.canvas-container canvas { - border:1px solid black; - width:99%; -} - -.controls { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 10px; - margin-bottom: 20px; -} - -.input-group { - display: flex; - align-items: center; - gap: 5px; -} - -#toggle-mode-button, -#clear-button, -#recenter-button { - background-color: #4caf50; - border: none; - color: white; - padding: 10px 20px; - text-align: center; - text-decoration: none; - font-size: 16px; - cursor: pointer; - border-radius: 5px; - transition: background-color 0.3s ease; -} - -#toggle-mode-button:hover, -#clear-button:hover, -#recenter-button:hover { - background-color: #45a049; -} - -.controls input[type="number"] { - width: 50px; - padding: 8px; - border-radius: 5px; - border: 1px solid #ccc; -} - -.controls input[type="color"] { - width: 40px; - height: 40px; - border-radius: 50%; - border: none; -} diff --git a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.html b/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.html deleted file mode 100644 index 1cc31778..00000000 --- a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.html +++ /dev/null @@ -1,20 +0,0 @@ -
-
- - - -
- - -
- - -
- - -
-
-
- -
-
\ No newline at end of file diff --git a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.js b/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.js deleted file mode 100644 index fe6be80a..00000000 --- a/examples/advanced/webrtc/components/canvasdraw/CanvasWithControls.js +++ /dev/null @@ -1,333 +0,0 @@ -// import css from "./CanvasWithControls.css" //uncomment if using bundler and comment out the fetch operations -// import html from "./CanvasWithControls.html" - -let css, html; //comment out if importing above - -export class CanvasWithControls extends HTMLElement { - - ondraw; - - constructor() { - super(); - - this.canvasWidth = 800; - this.canvasHeight = 600; - this.lineWidth = 5; - - this.attachShadow({ mode: "open" }); - - } - - static get observedAttributes() { - return ['width', 'height','controls']; - } - - attributeChangedCallback(name, oldValue, newValue) { - if (name === 'width') { - this.canvasWidth = parseInt(newValue); - if(this.canvas) { - this.canvas.width = this.canvasWidth; - this.ctx.lineWidth = this.lineWidth; - } - } else if (name === 'height') { - this.canvasHeight = parseInt(newValue); - if(this.canvas) - { - this.canvas.height = this.canvasHeight; - this.ctx.lineWidth = this.lineWidth; - } - } else if(name === 'controls') { - if(newValue && newValue !== 'false') { - this.shadowRoot.getElementById('controls-container').style.display = ''; - } else { - this.shadowRoot.getElementById('controls-container').style.display = 'none'; - } - } - } - - // Additional methods or event handlers can be defined here - setup = async () => { - if(this.fetch) await this.fetch; - - this.canvas = this.shadowRoot.getElementById("canvas"); - this.ctx = this.canvas.getContext("2d"); - const canvas = this.canvas; - const ctx = this.ctx; - - const maxScale = 5; - // Set initial canvas width and height - canvas.width = this.canvasWidth; - canvas.height = this.canvasHeight; - - let cursorStyle = 'crosshair'; - - canvas.style.cursor = cursorStyle; - - let color = "#000000"; - // Initialize canvas properties - ctx.strokeStyle = "#000000"; - this.ctx.lineWidth = this.lineWidth; - - // Your existing event listeners can be added here - const colorPicker = this.shadowRoot.getElementById("color-picker"); - colorPicker.addEventListener("input", (event) => { - color = event.target.value; - this.ctx.strokeStyle = event.target.value; - }); - - - const clearButton = this.shadowRoot.getElementById("clear-button"); - clearButton.addEventListener("click", () => { - ctx.clearRect(0, 0, canvas.width, canvas.height); - }); - - const zoomRange = this.shadowRoot.getElementById("zoom-range"); - zoomRange.addEventListener("input", (event) => { - const scale = parseFloat(event.target.value); - canvas.style.transform = `scale(${scale})`; - }); - - let isDrawing = false; - let lastX = 0; - let lastY = 0; - - let isPanning = false; - let scale = 1; // Initialize the scale factor - let translateX = 0; // Initialize the horizontal translation - let translateY = 0; // Initialize the vertical translation - let initialX = 0; // Store initial X coordinate for panning - let initialY = 0; // Store initial Y coordinate for panning - - let recenter = false; - - let onzoomEvent = (event) => { - const rect = canvas.getBoundingClientRect(); - let newScale, offsetXBefore, offsetXAfter, offsetYBefore, offsetYAfter; - - // Calculate the new scale value based on the scroll direction - if(event) { - const delta = event.deltaY > 0 ? -0.1 : 0.1; - newScale = Math.min(Math.max(0.1, scale + delta), maxScale); - } - - if(!event || recenter || newScale < 1) { - newScale = 1; - translateX = 0; - translateY = 0; - offsetXBefore = 0; - offsetYBefore = 0; - offsetXAfter = 0; - offsetYAfter = 0; - recenter = false; - } else { - // Calculate the mouse position relative to the canvas before scaling - offsetXBefore = (event.clientX - rect.left) / scale - translateX; - offsetYBefore = (event.clientY - rect.top) / scale - translateY; - - // Calculate the mouse position relative to the canvas after scaling - offsetXAfter = (event.clientX - rect.left) / newScale - translateX; - offsetYAfter = (event.clientY - rect.top) / newScale - translateY; - } - // Adjust the translation to maintain the zooming point - translateX += offsetXBefore - offsetXAfter; - translateY += offsetYBefore - offsetYAfter; - - // Apply the new transform with both scale and translation - canvas.style.transform = `translate(${translateX}px, ${translateY}px) scale(${newScale})`; - - // Update the scale variable for future calculations - scale = newScale; - zoomRange.value = newScale; - } - - - const recenterButton = this.shadowRoot.getElementById("recenter-button"); - recenterButton.addEventListener("click", () => { - recenter = true; - onzoomEvent(); - }); - - - canvas.parentElement.addEventListener("wheel", (event) => { - event.preventDefault(); - onzoomEvent(event); - }); - - canvas.addEventListener("mousedown", (event) => { - // Check if the middle mouse button is pressed or the Alt key is held down - if (event.button === 1 || event.altKey) { - canvas.style.cursor = "move"; - } else { - [lastX, lastY] = [event.offsetX * (this.canvasWidth / canvas.clientWidth), event.offsetY * (this.canvasHeight / canvas.clientHeight)]; - } - }); - - let drawPixel = (event) => { - const x = event.offsetX * (this.canvasWidth / canvas.clientWidth); - const y = event.offsetY * (this.canvasHeight / canvas.clientHeight); - ctx.fillRect( - x - this.lineWidth / 2, - y - this.lineWidth / 2, - this.lineWidth, - this.lineWidth - ); - if(this.ondraw) { - this.ondraw({x,y,color,isLineDrawingMode,lineWidth}); - } - }; - - canvas.parentElement.addEventListener("mousedown", (event) => { - // Check if the middle mouse button is pressed or the Alt key is held down - if (event.button === 1 || event.altKey) { - isPanning = true; - initialX = event.clientX - translateX; - initialY = event.clientY - translateY; - canvas.parentElement.style.cursor = "move"; - } else { - isDrawing = true; - if (isLineDrawingMode) { //need to move to trigger lines - ctx.strokeStyle = color; - } else { - // Pixel drawing mode - ctx.fillStyle = color; // Set fill style to the selected color - //thrice because it grays out on first draw for some reason - drawPixel(event); - drawPixel(event); - drawPixel(event); - } - } - - - }); - - let draw = (event) => { - if (isLineDrawingMode) { - ctx.lineCap = "round"; - ctx.beginPath(); - ctx.moveTo( - typeof lastX === 'number' ? lastX : event.offsetX * (this.canvasWidth / canvas.clientWidth), - typeof lastY === 'number' ? lastY : event.offsetY * (this.canvasHeight / canvas.clientHeight) - ); - const x = event.offsetX * (this.canvasWidth / canvas.clientWidth); - const y = event.offsetY * (this.canvasHeight / canvas.clientHeight); - ctx.lineTo(x, y); - ctx.stroke(); - if(this.ondraw) { - this.ondraw({x,y,lastX,lastY,color,isLineDrawingMode,lineWidth}) - } - [lastX, lastY] = [x, y]; - } else { - // Pixel drawing mode - ctx.fillStyle = color; - drawPixel(event); - } - } - - canvas.addEventListener("mousemove", (event) => { - if (isDrawing) { - draw(event); - } - }); - - canvas.parentElement.addEventListener("mousemove", (event) => { - if (isPanning) { - if (event.clientX - initialX !== 0 || event.clientY - initialY !== 0) { - translateX = event.clientX - initialX; - translateY = event.clientY - initialY; - canvas.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`; - } - } - }); - - - canvas.addEventListener("mouseup", () => { - isDrawing = false; - lastX = undefined; lastY = undefined; - canvas.style.cursor = cursorStyle; - }); - - canvas.addEventListener("mouseout", () => { - isDrawing = false; - }); - - canvas.parentElement.addEventListener("mouseup", () => { - isPanning = false; - canvas.parentElement.style.cursor = "default"; - }); - - canvas.parentElement.addEventListener("mouseout", () => { - isPanning = false; - }); - - - let isLineDrawingMode = true; // Flag for line drawing mode - let lineWidthLabel = this.shadowRoot.getElementById('line-label'); - let lineWidthInput = this.shadowRoot.getElementById("line-width"); // Line width input element - - // Event listener for the line mode toggle button - const toggleModeButton = this.shadowRoot.getElementById("toggle-mode-button"); - toggleModeButton.addEventListener("click", () => { - isLineDrawingMode = !isLineDrawingMode; // Toggle line drawing mode - if (isLineDrawingMode) { - toggleModeButton.innerHTML = "Line Mode"; - lineWidthLabel.innerHTML = "Line Width:"; - cursorStyle = "crosshair"; // Set cursor to crosshair in line drawing mode - } else { - toggleModeButton.innerHTML = "Pixel Mode"; - lineWidthLabel.innerHTML = "Pixel Size:"; - cursorStyle = "default"; // Set cursor to default in pixel drawing mode - } - canvas.style.cursor = cursorStyle; - }); - - // Event listener for line width input - lineWidthInput.addEventListener("input", (event) => { - this.lineWidth = parseInt(event.target.value); // Update line width based on user input - ctx.lineWidth = this.lineWidth; // Apply the new line width to the context - }); - - } - - connectedCallback() { - // Code to run when the element is added to the DOM - - //Fetch HTML and CSS files asynchronously (comment out if bundling html and css instead) - if(!css || !html) { - this.fetch = Promise.all([ - fetch("CanvasWithControls.html").then(response => response.text()), - fetch("CanvasWithControls.css").then(response => response.text()) - ]).then(([h, c]) => { - html = h; css = c; //should only fetch once - this.shadowRoot.innerHTML = ` - - ${html} - `; - - // Your component's logic and event listeners here - // ... - }).catch(error => { - console.error("Error fetching resources:", error); - }); - - } else { - this.shadowRoot.innerHTML = ` - - ${html} - `; - } - - this.setup(); - } - - disconnectedCallback() { - // Code to run when the element is removed from the DOM - } - - // Define other lifecycle callbacks and methods as needed -} - -customElements.define("canvas-with-controls", CanvasWithControls); \ No newline at end of file diff --git a/examples/advanced/webrtc/components/chatdraw.html b/examples/advanced/webrtc/components/chatdraw.html deleted file mode 100644 index 725b653e..00000000 --- a/examples/advanced/webrtc/components/chatdraw.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - + + + + + + + + + + + + + `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` + + + + + + + + + + + + + + + `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var url=URL.createObjectURL(new Blob([String('(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browser=__commonJS({"../node_modules/web-worker/cjs/browser.js"(exports,module){module.exports=Worker}});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\\\"))args[0]=args[0].replace(/\\\\/g,"");if(args[0][0]===\'"\'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent2,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent2?.callback&&parent2?.worker))node.parentRoute=parent2?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setTree(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w2=s.worker;let wpId;wpId=service.establishMessageChannel(w2.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w2.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w2.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w2.run("setValue",["routeProxy",s.route]);w2.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w22=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w2.worker,w22.worker);s.pipeTo.worker=w22}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w2.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w2.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w2,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w2.run("setValue",["routeProxy",s.route]);service.transferFunction(w2,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w2.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w2.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w2.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w2.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w2.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w2.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;Object.assign(this.__node.graph.ALGORITHMS[_id],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;let res=this.__node.graph.ALGORITHMS[_id].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id]:res});return res}}}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b2)=>arr.filter(v2=>v2===a).length-arr.filter(v2=>v2===b2).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b2-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v2=>(v2-min)/(max-min))}static quadraticFormula(a,b2,c){let bbmac4=Math.sqrt(b2*b2-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b2*_a2];let nb=-b2;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x22=>{return Math.pow(x22,5)+x22*x22-x22-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v2,i,x22,y2)=>{return v2+x22+y2}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v2}, idx:${idx}, x:${i},y:${j}`);return v2+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x22,y2)=>{return[x22*10,y2*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_2,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b2){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b2.length,bNumCols=b2[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix22*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y2=0;y2{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x22=arr.filter((element,index)=>{return index%factor===0});return x22}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x22){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x22=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b2=0;if(0<=h&&h<60){r=c;g=x22;b2=0}else if(60<=h&&h<120){r=x22;g=c;b2=0}else if(120<=h&&h<180){r=0;g=c;b2=x22}else if(180<=h&&h<240){r=0;g=x22;b2=c}else if(240<=h&&h<300){r=x22;g=0;b2=c}else if(300<=h&&h<360){r=c;g=0;b2=x22}r=(r+m)*scalar;g=(g+m)*scalar;b2=(b2+m)*scalar;return[r,g,b2]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x22=>{let y2=x22;return y2},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x22+y2;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w2=x22+y2+z;return w2},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x22;return y2},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y2=0;y2{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{if(!("ax"in data)&&!("gx"in data))return void 0;if(!data.timestamp){if(data.ax&&Array.isArray(data.ax)||data.gx&&Array.isArray(data.gx)){let len=data.ax?data.ax.length:data.gx.length;let now=Date.now();let toInterp=[now-len*ctx.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,len)}else{data.timestamp=Date.now()}}let result;if(data.ax){let apass=(timestamp,ax,ay,az)=>{ax=ax*ctx.accelConstant;ay=ay*ctx.accelConstant;az=az*ctx.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+ctx.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+ctx.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v2,i)=>{return apass(v2,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-ctx.lastGyroTime;ctx.lastGyroTime=timestamp;gx=gx*ctx.gyroConstant+ctx.gyroXError;gy=gy*ctx.gyroConstant+ctx.gyroYError;gz=gz*ctx.gyroConstant+ctx.gyroZError;ctx.gyroXAngle+=gx*elapsed;ctx.gyroYAngle+=gy*elapsed;ctx.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:ctx.gyroXAngle,pitch:ctx.gyroYAngle,yaw:ctx.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v2,i)=>{if(result){let r=gpass(v2,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v2,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(ctx.gyroXAngle||ctx.gyroYAngle||ctx.gyroZAngle){result.roll=result.roll*.04+ctx.gyroXAngle*.96;result.pitch=result.pitch*.04+ctx.gyroYAngle*.96;result.yaw=ctx.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-ctx.lastAccelTime;ctx.lastAccelTime=timestamp;ctx.px+=result2.ax*elapsed*elapsed*Math.cos(ctx.pitch*Math.PI*.005555555555);ctx.py+=result2.ay*elapsed*elapsed*Math.cos(ctx.roll*Math.PI*.005555555555);ctx.pz+=result2.az*elapsed*elapsed*Math.sin(ctx.pitch*Math.PI*.005555555555);result2.px=ctx.px;result2.py=ctx.py;result2.pz=ctx.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){this.a0=0;this.a1=0;this.a2=0;this.b0=0;this.b1=0;this.b2=0;this.x1=0;this.x2=0;this.y1=0;this.y2=0;let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A2=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A2+A2);this[type](A2,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A2,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A2,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A2,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A2,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A2,sn,cs,alpha,beta){this.b0=1+alpha*A2;this.b1=-2*cs;this.b2=1-alpha*A2;this.a0=1+alpha/A2;this.a1=-2*cs;this.a2=1-alpha/A2}lowshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1-(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1-(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1+(A2+1)*cs+beta*sn;this.a1=2*(A2-1+(A2+1)*cs);this.a2=A2+1+(A2-1)*cs-beta*sn}highshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1+(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1+(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1-(A2+1)*cs-beta*sn;this.a1=2*(A2-1-(A2+1)*cs);this.a2=A2+1-(A2-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={structs:{refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10},oncreate:context=>{if(!context.lowpass){let freq=context.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;context.lowpass=new Biquad("lowpass",context.maxFreq,context.sps);context.peakFinderWindow=Math.floor(context.sps/context.maxFreq);if(context.peakFinderWindow%2===0)context.peakFinderWindow+=1;if(context.peakFinderWindow<5)context.peakFinderWindow=5;context.midpoint=Math.round(context.peakFinderWindow*.5)}},ondata:(context,data)=>{if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*context.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){context.refdata.push(amplitude)}context.timestamp.push(timestamp);let beat;if(context.refdata.length>context.peakFinderWindow){context.refdata.shift();context.timestamp.shift()}context.smoothed.push(context.lowpass.applyFilter(context.refdata[context.refdata.length-1]));if(context.smoothed.length>context.peakFinderWindow){context.smoothed.shift()}if(context.smoothed.length===context.peakFinderWindow){if(Math2.isExtrema(context.smoothed,"valley")){context.valleys.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}else if(Math2.isExtrema(context.smoothed,"peak")){context.peaks.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}if(context.valleys.length>2&&context.peaks.length>2){if(context.valleys[context.valleys.length-1].timestamp1&&context.valley_distances.length>1){if(context.lastPeakcontext.peak_distances[context.peak_distances.length-1].timestamp){let bpm,change=0;if(context.beats.length<1){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].distance+context.valley_distances[context.valley_distances.length-1].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-1].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].dt+context.valley_distances[context.valley_distances.length-1].dt));change=Math.abs(bpm-context.beats[context.beats.length-1].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-1].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-1].peak0-context.valley_distances[context.valley_distances.length-1].peak0,height1:context.peak_distances[context.peak_distances.length-1].peak1-context.valley_distances[context.valley_distances.length-1].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}else{let bpm,change=0;if(context.beats.length<2){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-2].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance));change=Math.abs(bpm-context.beats[context.beats.length-2].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-2].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-2].peak0-context.valley_distances[context.valley_distances.length-2].peak0,height1:context.peak_distances[context.peak_distances.length-2].peak1-context.valley_distances[context.valley_distances.length-2].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}}}if(context.peaks.length>context.limit){context.peaks.shift()}if(context.valleys.length>context.limit){context.valleys.shift()}if(context.peak_distances.length>context.limit){context.peak_distances.shift()}if(context.valley_distances.length>context.limit){context.valley_distances.shift()}if(context.beats.length>context.limit){context.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)data.red.map((v2,i)=>{return pass(v2+data.ir[i],data.timestamp[i])});else data.red.map((v2,i)=>{return pass(v2,data.timestamp[i])});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v2,i)=>{return pass(v2,data.timestamp[i])});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v2,i)=>{return pass(v2,data.timestamp[i])});return result}}};var blink_detect={structs:{sps:250,intervals:{},watch:["0"],tolerance:.2},oncreate:ctx=>{ctx.watch.forEach(ch=>ctx.intervals[ch]={lowpass:new Biquad("lowpass",20,ctx.sps),filtered:[],averaged:[]})},ondata:(ctx,data)=>{let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=ctx.intervals[key].lowpass.applyFilter(n);ctx.intervals[key].filtered.push(next);ctx.intervals[key].averaged.push(next);if(ctx.intervals[key].filtered.length>checkCt){if(ctx.intervals[key].averaged.length>averageCt){ctx.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(ctx.intervals[key].averaged);if(Math.abs(Math.min(...ctx.intervals[key].filtered))>Math.abs(mean)+ctx.tolerance){ctx.intervals[key].filtered.length=0;passed=true;found[key]=true}}else ctx.intervals[key].filtered.shift()}};for(const key in ctx.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var _ArrayManip=class{constructor(){this.recursivelyAssign=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target}}static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d2={};data.forEach((arr,i)=>{d2[i]=arr});data=d2;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_2,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var ArrayManip=_ArrayManip;ArrayManip.bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v2,o,c)=>String.fromCharCode(...new Uint8Array(v2.buffer,v2.byteOffset+o,c));var rts=(v2,o,c,s)=>new Uint8Array(v2.buffer,v2.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v2,o,c)=>str(v2,o+1,Math.min(v2.getUint8(o),c-1));var tsp=(v2,o,c,s)=>{v2.setUint8(o,s.length);rts(v2,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v2=>str(v2,o,1),p:(v2,c2)=>rts(v2,o,1,c2)})],"?":c=>[c,1,o=>({u:v2=>Boolean(v2.getUint8(o)),p:(v2,B)=>v2.setUint8(o,B)})],b:c=>[c,1,o=>({u:v2=>v2.getInt8(o),p:(v2,b2)=>v2.setInt8(o,b2)})],B:c=>[c,1,o=>({u:v2=>v2.getUint8(o),p:(v2,B)=>v2.setUint8(o,B)})],h:c=>[c,2,o=>({u:v2=>v2.getInt16(o,le),p:(v2,h)=>v2.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v2=>v2.getUint16(o,le),p:(v2,H)=>v2.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v2=>v2.getInt32(o,le),p:(v2,i)=>v2.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v2=>v2.getUint32(o,le),p:(v2,I)=>v2.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v2=>v2.getFloat32(o,le),p:(v2,f)=>v2.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v2=>v2.getFloat64(o,le),p:(v2,d2)=>v2.setFloat64(o,d2,le)})],s:c=>[1,c,o=>({u:v2=>str(v2,o,c),p:(v2,s)=>rts(v2,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v2=>pst(v2,o,c),p:(v2,s)=>tsp(v2,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var _ByteParser=class extends ArrayManip{static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x22){let int24=(255&x0)<<16|(255&x1)<<8|255&x22;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x22){return x0*65536+x1*256+x22}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x22,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x22)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x22,x3){return x0*16777216+x1*65536+x22*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M2=pattern.length;if(M2===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R2=256;var rightmost_positions=new Int32Array(R2);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v2=new DataView(arrb,offs|0);return fns.map(f=>f.u(v2))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v2,values[i]))};const pack=(...values)=>{let b2=new ArrayBuffer(size);pack_into(b2,0,...values);return b2};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var ByteParser=_ByteParser;ByteParser.codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};var rms={structs:{sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{}},ondata:(ctx,data)=>{ctx.watch.forEach(key=>{if(data[key]){if(!ctx.data[key]){if(Array.isArray(data[key])){ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key][0])}else ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key])}ByteParser.circularBuffer(ctx.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){ctx.rms.timestamp=data.timestamp[data.timestamp.length-1]}else ctx.rms.timestamp=data.timestamp}else ctx.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(ctx.watch.map(async key=>{if(ctx.data[key])ctx.rms[key]=Math.sqrt(Math.abs(ctx.data[key].reduce((p,v2,i)=>p+v2*v2)/ctx.data[key].length));else delete ctx.rms[key]}));res(ctx.rms)})}};var circularBuffer2d={structs:{bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false},oncreate:ctx=>{for(const key in ctx.watch){ctx.data[key]=new Array(ctx.bufferSize).fill(0)}},ondata:(ctx,data)=>{let buffer2d=[];ctx.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(ctx.data[key],data[key]);buffer2d.push(ctx.data[key])}});return buffer2d}};Object.assign(algorithms,{beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d});algorithms["breath"].structs=JSON.parse(JSON.stringify(algorithms["breath"].structs));algorithms["breath"].structs.maxFreq=.2;export{StructBackend,StructFrontend,Systems,algorithms,getStringId,Worker_default as gsworker,pseudoObjectId,randomId,setSignalControls,toObjectID,webglPlotRoutes}; diff --git a/extras/dist/index.services.js b/extras/dist/index.services.js new file mode 100644 index 00000000..d4b011d7 --- /dev/null +++ b/extras/dist/index.services.js @@ -0,0 +1,48 @@ +(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_objectid=__commonJS({"node_modules/bson-objectid/objectid.js"(exports,module){var MACHINE_ID=Math.floor(Math.random()*16777215);var index=ObjectID2.index=parseInt(Math.random()*16777215,10);var pid=(typeof process==="undefined"||typeof process.pid!=="number"?Math.floor(Math.random()*1e5):process.pid)%65535;var BufferCtr=(()=>{try{return _Buffer}catch(_2){try{return Buffer}catch(_3){return null}}})();var isBuffer=function(obj){return!!(obj!=null&&obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj))};var hexTable=[];for(i=0;i<256;i++){hexTable[i]=(i<=15?"0":"")+i.toString(16)}var i;var checkForHexRegExp=new RegExp("^[0-9a-fA-F]{24}$");var decodeLookup=[];i=0;while(i<10)decodeLookup[48+i]=i++;while(i<16)decodeLookup[65-10+i]=decodeLookup[97-10+i]=i++;function ObjectID2(id){if(!(this instanceof ObjectID2))return new ObjectID2(id);if(id&&(id instanceof ObjectID2||id._bsontype==="ObjectID"))return id;this._bsontype="ObjectID";if(id==null||typeof id==="number"){this.id=this.generate(id);return}var valid=ObjectID2.isValid(id);if(!valid&&id!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(valid&&typeof id==="string"&&id.length===24){return ObjectID2.createFromHexString(id)}else if(id!=null&&id.length===12){this.id=id}else if(id!=null&&typeof id.toHexString==="function"){return id}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}}module.exports=ObjectID2;ObjectID2.default=ObjectID2;ObjectID2.createFromTime=function(time){time=parseInt(time,10)%4294967295;return new ObjectID2(hex(8,time)+"0000000000000000")};ObjectID2.createFromHexString=function(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}var data="";var i2=0;while(i2<24){data+=String.fromCharCode(decodeLookup[hexString.charCodeAt(i2++)]<<4|decodeLookup[hexString.charCodeAt(i2++)])}return new ObjectID2(data)};ObjectID2.isValid=function(id){if(id==null)return false;if(typeof id==="number"){return true}if(typeof id==="string"){return id.length===12||id.length===24&&checkForHexRegExp.test(id)}if(id instanceof ObjectID2){return true}if(isBuffer(id)){return ObjectID2.isValid(id.toString("hex"))}if(typeof id.toHexString==="function"){if(BufferCtr&&(id.id instanceof BufferCtr||typeof id.id==="string")){return id.id.length===12||id.id.length===24&&checkForHexRegExp.test(id.id)}}return false};ObjectID2.prototype={constructor:ObjectID2,toHexString:function(){if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id.length===24){return this.id}if(isBuffer(this.id)){return this.id.toString("hex")}var hexString="";for(var i2=0;i2>24&255,time>>16&255,time>>8&255,time&255,MACHINE_ID>>16&255,MACHINE_ID>>8&255,MACHINE_ID&255,pid>>8&255,pid&255,inc>>16&255,inc>>8&255,inc&255)}};function next(){return index=(index+1)%16777215}function hex(length,n){n=n.toString(16);return n.length===length?n:"00000000".substring(n.length,length)+n}var inspect=Symbol&&Symbol.for&&Symbol.for("nodejs.util.inspect.custom")||"inspect";ObjectID2.prototype[inspect]=function(){return"ObjectID("+this+")"};ObjectID2.prototype.toJSON=ObjectID2.prototype.toHexString;ObjectID2.prototype.toString=ObjectID2.prototype.toHexString}});var DataStructures_exports={};__export(DataStructures_exports,{AuthorizationStruct:()=>AuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_2={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{};Object.assign(this.data,props);this.dataSorts=new Map;this.watches={};this.setSort("event",dataObj=>{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_2)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b2){if(a.timestamp&&b2.timestamp)return a.timestamp-b2.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_2,__,___=this.data){}onSorted(_2=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v2=>{localState[k]=v2;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v2)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d2=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d2.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{constructor(options,user){super(options);this.name="structs";this.tablet=new DataTablet;this.collections=this.tablet.collections;this.id=randomId();this.baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}if(data?.message==="notifications"){this.checkForNotifications()}if(data?.message==="deleted"){this.deleteLocalData(data.data)}this.onResult(data)};this.getUser=async(info="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info]}))?.[0];callback(res);return res}};this.getUsers=async(ids=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids]});callback(res);return res}};this.getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};this.getAllUserData=async(ownerId,excluded=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[ownerId,excluded]});callback(res);return res}};this.query=async(collection,queryObj={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!queryObj)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,queryObj,findOne,skip]});if(typeof callback==="function")callback(res);return res}};this.getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip]});if(typeof callback==="function")callback(res);return res}};this.getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection]});if(typeof callback==="function")callback(res);return res}};this.getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};this.setUser=async(userStruct={},callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct)]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify]});if(typeof callback==="function")callback(res);return res}};this.updateServerData=this.setData;this.deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=(await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.deleteUser=async(userId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=(await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.setGroup=async(groupStruct={},callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct)]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId]});if(typeof callback==="function")callback(res);return res}};this.deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=(await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.setAuthorization=async(authorizationStruct={},callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct)]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId]});if(typeof callback==="function")callback(res);return res}};this.deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=(await this.currentUser.request({route:"deleteAuthorization",args:[authorizationId]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};this.resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};this.setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};this.deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};this.deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent2=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent2){toUpdate=[parent2];allReplies.forEach(r=>{let idx=parent2.replies?.indexOf(r._id);if(idx>-1)parent2.replies.splice(idx,1);let idx2=parent2.comments?.indexOf(r._id);if(idx2>-1)parent2.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent2?._id){let idx=replyTo.replies?.indexOf(parent2._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};this.getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u=authorizationStruct.authorizerId;if(u){return new Promise(async resolve=>{this.getUser(u,async data=>{if(!collection)await this.getAllUserData(u,["notification"],callback);else await this.getData(collection,u,searchDict,limit,skip,callback);resolve(data);callback(data)})})}else return void 0};this.getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u=o.authorizerId;if(u){let data;let user=await this.getUser(u,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u,["notification"],callback);else data=await this.getData(collection,u,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};this.getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return[];let result=[];let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result.push(a.authorizedId)});return result};this.authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization.ownerId=parentUser._id;newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};this.addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);newGroup.ownerId=parentUser._id;if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};this.addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;newDataInstance.ownerId=parentUser._id;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};this.addEvent=async(parentUser,author="",event="",notes="",startTime=0,endTime=0,grade=0,attachments=[],users={},updateServer=true)=>{if(!parentUser)return void 0;if(Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.users=users;newEvent.ownerId=parentUser._id;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};this.addChatroom=async(parentUser,authorId="",message="",attachments=[],users={},updateServer=true)=>{if(!parentUser)return void 0;if(Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];newChatroom.ownerId=parentUser._id;let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};this.addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=[],updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];newComment.ownerId=parentUser._id;if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res};this.setTree(this);if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}async setupUser(userinfo,callback=currentUser=>{}){if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u;let newu=false;console.log("getUser result",user);if(!user||!user._id){console.log("creating new profile");u=this.userStruct(userinfo,true);newu=true;let wasSet=await this.setUser(u);let structs=this.getLocalData(void 0,{"ownerId":u._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u)}else{u=user;if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u)}else{let data=await this.getAllUserData(u._id,void 0);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u);console.log("collections",this.tablet.collections)}if(u){this.currentUser=u;callback(this.currentUser);return this.currentUser}else{callback(u);return u}}onResult(data){}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}async addStruct(structType="struct",props={},parentUser,parentStruct,updateServer=true){let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct}overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b2)=>a*(typeof b2==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(struct);if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct={}){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop].constructor.name==="Map"||typeof copy[prop]==="function")delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e10);user._id=user.id;user.ownerId=user.id;for(const prop in props){if(Object.keys(DataStructures_exports.ProfileStruct()).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}};var import_bson_objectid=__toESM(require_objectid());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectID=str2=>{return typeof str2==="string"&&str2.length===24?(0,import_bson_objectid.default)(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{constructor(options,dboptions){super(options);this.name="structs";this.debug=false;this.users={};this.collections={};this.useAuths=true;this.query=async(requestingUserId,collection,queryObj,findOne,skip)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res)}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}));return data}};this.getUser=async(requestingUserId,lookupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:{}};else{let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};this.setUser=async(requestingUserId,struct)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct)}else{let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};this.getUsersByIds=async(requestingUserId,userIds)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct)data.push(struct)}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};this.getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};this.deleteUser=async(requestingUserId,userId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};this.setData=async(requestingUserId,structs,notify)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]=this.db?{instance:this.db.collection(struct.structType)}:{};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};this.getData=async(requestingUserId,collection,ownerId,dict,limit,skip)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};this.getDataByIds=async(requestingUserId,structIds,ownerId,collection)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};this.getAllData=async(requestingUserId,ownerId,excludedCollections)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};this.deleteData=async(requestingUserId,structIds)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};this.getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};this.deleteGroup=async(requestingUserId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE")}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};this.getAuthorizations=async(requestingUserId,ownerId,authId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};this.deleteAuthorization=async(requestingUserId,authId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};this.wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};this.setTree(this);if(dboptions?.users)this.users=dboptions.users;if(dboptions?.db)this.mode=this.db?dboptions.mode?dboptions.mode:"local":"local";if(dboptions?.collections)this.collections=dboptions.collections;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})}notificationStruct(parentStruct={}){let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct}async checkToNotify(user,structs=[],mode=this.mode){if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id);newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id);newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});if(await s.count()>0){await s.forEach(d2=>auths.push(d2))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id);newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications)}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid].send({route:"structNotification",args:true})}return true}else return false}async queryMongo(user,collection,queryObj={},findOne=false,skip=0){if(!collection&&!queryObj)return void 0;else if(findOne){let res=this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res)}if(passed)return res;else return void 0}else{let res=await this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];if(await res.count()>0){let passed=!this.useAuths;let checkedAuth="";await res.forEach(async s=>{if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed)structs.push(s)})}return structs}}async setMongoData(user,structs=[],notify=true){let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]=this.db?{instance:this.db.collection(struct.structType)}:{};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType).insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType).updateOne({parent:struct.parent,_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType).updateOne({_id:toObjectID(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType).insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectID(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectID(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false}async setMongoUser(user,struct){if(struct._id){const _id=toObjectID(struct._id);let usersearch=_id!==struct._id?{_id}:{id:struct.id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false}async setGroup(user,struct,mode=this.mode){if(struct?._id){let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(getStringId(user._id))<0))return false;if(getStringId(user._id)!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u=>{allusers.push({email:u},{id:u},{username:u})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});if(await cursor.count()>0){await cursor.forEach(user2=>{users[getStringId(user2._id)]=user2;ids[getStringId(user2._id)]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u=users[id];if(struct.admins[getStringId(u._id)]||struct.admins[u.email]||struct.admins[u.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u._id)])admins[getStringId(u._id)]=true}if(struct.peers[getStringId(u._id)]||struct.peers[u.email]||struct.peers[u.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u._id)])peers[getStringId(u._id)]=true}if(struct.clients[getStringId(u._id)]||struct.clients[u.email]||struct.clients[u.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u._id)])clients[getStringId(u._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType).insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType).findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectID(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false}async getMongoUser(user,info="",bypassAuth=false){return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectID(info)})}catch(e){}let u=await this.collections.profile.instance.findOne({$or:query});if(!u||u==null)resolve({});else{u._id=getStringId(u._id);if(!u.ownerId)u.ownerId=u._id;if(u&&bypassAuth===false){if(getStringId(user._id)!==u._id||getStringId(user._id)===u._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u._id});if(await auths.count()>0){await auths.forEach(d2=>authorizations.push(d2))}let gs=this.collections.group.instance.find({users:{$all:[u._id]}});let groups=[];if(await gs.count()>0){await gs.forEach(d2=>groups.push(d2))}resolve({user:u,authorizations,groups})}else resolve({user:u})}})}async getMongoUsersByIds(user,userIds=[]){let usrs=[];userIds.forEach(u=>{try{usrs.push({_id:toObjectID(u)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});if(await users.count()>0){await users.forEach(u=>{found.push(u)})}}return found}async getMongoUsersByRole(user,role){let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];if(await users.count()>0){await users.forEach(u=>{found.push(u)})}return found}async getMongoDataByIds(user,structIds,ownerId,collection){if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectID(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});if(await cursor.count()>0){let passed=true;let checkedAuth="";await cursor.forEach(async s=>{if(!s?.ownerId)passed=true;else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed)found.push(s)})}}))}else{let cursor=await this.db.collection(collection).find({$or:query});if(await cursor.count()>0){let passed=true;let checkedAuth="";await cursor.forEach(async s=>{if(!s?.ownerId)passed=true;else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}}async getMongoData(user,collection,ownerId,dict={},limit=0,skip=0){if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectID(dict._id);let structs=[];let passed=true;let checkedAuth="";if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){let cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip);if(limit>0)cursor.limit(limit);if(await cursor.count()>0){await cursor.forEach(async s=>{if(!s?.ownerId)passed=true;else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed===true)structs.push(s)})}}else if(Object.keys(dict).length>0&&ownerId){let found=await this.db.collection(collection).findOne({ownerId,...dict});if(found)structs.push(found)}else if(Object.keys(dict).length>0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{let found=await this.db.collection(name).findOne(dict);if(found){if(!found?.ownerId)passed=true;else if((getStringId(user._id)!==found.ownerId||getStringId(user._id)===found.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==found.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,found);checkedAuth=found.ownerId}structs.push(found);return}}))}if(!passed)return[];return structs}async getAllUserMongoData(user,ownerId,excluded=[]){let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let cursor=this.db.collection(name).find({ownerId});let count=await cursor.count();for(let k=0;k0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectID(ref._id)});if(struct){let passed=true;if(!struct?.ownerId)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs}async getMongoAuthorizations(user,ownerId=getStringId(user._id),authId=""){let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});if(await cursor.count>0){await cursor.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectID(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0]);if(!passed)return void 0}return auths}async getMongoGroups(user,userId=getStringId(user._id),groupId=""){let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});if(await cursor.count>0){await cursor.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectID(groupId),users:{$all:[userId]}}))}catch{}}return groups}async deleteMongoData(user,structRefs=[]){let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectID(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=await notifications.count();for(let i=0;i{let passed=true;if(!struct?.ownerId)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE")}if(passed){await this.db.collection(struct.structType).deleteOne({_id:toObjectID(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid].send({route:"structDeleted",args:getStringId(struct._id)})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId].send({route:"structDeleted",args:getStringId(struct._id)})}}}));return true}async deleteMongoUser(user,userId){if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u,"WRITE");if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId].send({route:"structDeleted",args:userId});return true}async deleteMongoGroup(user,groupId){let s=await this.collections.group.instance.findOne({_id:toObjectID(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE");if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u=>{this.users[s.authorizerId].send({route:"structDeleted",args:getStringId(s._id)})})}await this.collections.group.instance.deleteOne({_id:toObjectID(groupId)});return true}else return false}async deleteMongoAuthorization(user,authId){let s=await this.collections.authorization.instance.findOne({_id:toObjectID(authId)});if(s){if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE");if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectID(s.associatedAuthId)});if(s.authorizerId&&s.authorizerId!==getStringId(user._id))this.users[s.authorizerId].send({route:"structDeleted",args:getStringId(s._id)});else if(s.authorizedId&&s.authorizedId!==getStringId(user._id))this.users[s.authorizerId].send({route:"structDeleted",args:getStringId(s._id)})}await this.collections.authorization.instance.deleteOne({_id:toObjectID(authId)});return true}else return false}async setAuthorization(user,authStruct,mode=this.mode){let u1,u2;if(mode.includes("mongo")){u1=(await this.getMongoUser(user,authStruct.authorizedId,true)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,true)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE");if(!passed)return false}let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});if(await s.count()>0){await s.forEach(d2=>auths.push(d2))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d2=>{if(d2.authorizerId===authStruct.authorizerId)auths.push(d2)})}}let otherAuthset;if(Array.isArray(auths)){auths.forEach(async auth=>{if(auth.ownerId===getStringId(user._id)){}else{if(authStruct.authorizerId===getStringId(user._id)){auth.authorizations=authStruct.authorizations;auth.structs=authStruct.structs;auth.excluded=authStruct.excluded;auth.expires=authStruct.expires;auth.status="OKAY";authStruct.status="OKAY"}else{authStruct.authorizations=auth.authorizations;authStruct.structs=auth.structs;authStruct.excluded=auth.excluded;authStruct.expires=auth.expires;auth.status="OKAY";authStruct.status="OKAY"}authStruct.associatedAuthId=getStringId(auth._id);auth.associatedAuthId=getStringId(authStruct._id);otherAuthset=auth;let copy2=JSON.parse(JSON.stringify(auth));if(mode.includes("mongo")){delete copy2._id;await this.collections.authorization.instance.updateOne({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId},{ownerId:auth.ownerId}]},{$set:copy2},{upsert:true})}else{this.setLocalData(copy2)}}})}let copy=JSON.parse(JSON.stringify(authStruct));if(mode.includes("mongo")){delete copy._id;await this.collections.authorization.instance.updateOne({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId},{ownerId:authStruct.ownerId}]},{$set:copy},{upsert:true})}else{this.setLocalData(copy)}if(getStringId(authStruct._id).includes("defaultId")&&mode.includes("mongo")){let replacedAuth=await this.collections.authorization.instance.findOne(copy);if(replacedAuth){authStruct._id=getStringId(replacedAuth._id);if(otherAuthset){let otherAuth=await this.collections.authorization.instance.findOne({$and:[{authorizedId:otherAuthset.authorizedId},{authorizerId:otherAuthset.authorizerId},{ownerId:otherAuthset.ownerId}]});if(otherAuth){otherAuth.associatedAuthId=getStringId(authStruct._id);let copy2=JSON.parse(JSON.stringify(otherAuth));delete copy2._id;await this.collections.authorization.instance.updateOne({$and:[{authorizedId:otherAuth.authorizedId},{authorizerId:otherAuth.authorizerId},{ownerId:otherAuth.ownerId}]},{$set:copy2},{upsert:true});this.checkToNotify(user,[otherAuth])}}}}return authStruct}async checkAuthorization(user,struct,request="READ",mode=this.mode){if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}else return true}}else if(typeof user==="string"){if(struct.ownerId===user){return true}else user={_id:user}}let auth1,auth2;if(mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:struct.ownerId},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:struct.ownerId}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true;else passed=false}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed}overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}deleteLocalData(struct){if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b2={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b2,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u=(dot11*dot02-dot01*dot12)*_denom;let v2=(dot00*dot12-dot01*dot02)*_denom;if(u>=0&&v2>=0&&u+v2<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v2=>{let magnitude=0;for(const key in v2){magnitude+=v2[key]*v2[key]}return Math.sqrt(magnitude)},normalize:v2=>{let magnitude=Systems.collision.magnitude(v2);let _mag=magnitude?1/magnitude:0;let vn=Object.assign({},v2);for(const key in v2){vn[key]=v2[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w2=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w2||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var b=class{constructor(e,t,s,h){this.r=e,this.g=t,this.b=s,this.a=h}};var x2=class{constructor(){this.scaleX=1,this.scaleY=1,this.offsetX=0,this.offsetY=0,this.loop=false,this._vbuffer=0,this._coord=0,this.visible=true,this.intensity=1,this.xy=new Float32Array([]),this.numPoints=0,this.color=new b(0,0,0,1),this.webglNumPoints=0}};var v=class extends x2{constructor(e,t){super(),this.currentIndex=0,this.webglNumPoints=t,this.numPoints=t,this.color=e,this.xy=new Float32Array(2*this.webglNumPoints)}setX(e,t){this.xy[e*2]=t}setY(e,t){this.xy[e*2+1]=t}getX(e){return this.xy[e*2]}getY(e){return this.xy[e*2+1]}lineSpaceX(e,t){for(let s=0;s{let s={x:0,y:0};return s.x=c.x+e.x*t,s.y=c.y+e.y*t,s};var _=c=>P(-c.y,c.x);var w=(c,e)=>{let t=T(c,e);return t=M(t),t};var S=(c,e)=>{let t={x:0,y:0};return t.x=c.x+e.x,t.y=c.y+e.y,t};var R=(c,e)=>c.x*e.x+c.y*e.y;var M=c=>{let e={x:0,y:0},t=c.x*c.x+c.y*c.y;return t>0&&(t=1/Math.sqrt(t),e.x=c.x*t,e.y=c.y*t),e};var P=(c,e)=>{let t={x:0,y:0};return t.x=c,t.y=e,t};var T=(c,e)=>{let t={x:0,y:0};return t.x=c.x-e.x,t.y=c.y-e.y,t};var C=c=>{let e,t={x:0,y:0},s={x:0,y:0},h=[],r=(n,l)=>{h.push({vec2:n,miterLength:l})},a=n=>({x:c[n*2],y:c[n*2+1]});t=w(a(1),a(0)),e=_(t),r(e,1);let o=c.length/2;for(let n=1;n{let t=S(c,e);return t=M(t),P(-t.y,t.x)};var N=(c,e,t)=>{let s=P(-c.y,c.x);return t/R(e,s)};var d=class extends x2{constructor(e,t,s){super(),this.currentIndex=0,this._thicknessRequested=0,this._actualThickness=0,this.webglNumPoints=t*2,this.numPoints=t,this.color=e,this._thicknessRequested=s,this._linePoints=new Float32Array(t*2),this.xy=new Float32Array(2*this.webglNumPoints)}convertToTriPoints(){let e=this._actualThickness/2,t=C(this._linePoints);for(let s=0;s{if(s.visible){t.useProgram(this._progLine);let h=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(h,false,new Float32Array([s.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,s.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let r=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(r,new Float32Array([s.offsetX+this.gOffsetX,s.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let o=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(o,[s.color.r,s.color.g,s.color.b,s.color.a]),t.bufferData(t.ARRAY_BUFFER,s.xy,t.STREAM_DRAW),t.drawArrays(s.loop?t.LINE_LOOP:t.LINE_STRIP,0,s.webglNumPoints)}})}_drawSurfaces(e){let t=this.webgl;e.forEach(s=>{if(s.visible){t.useProgram(this._progLine);let h=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(h,false,new Float32Array([s.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,s.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let r=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(r,new Float32Array([s.offsetX+this.gOffsetX,s.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let o=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(o,[s.color.r,s.color.g,s.color.b,s.color.a]),t.bufferData(t.ARRAY_BUFFER,s.xy,t.STREAM_DRAW),t.drawArrays(t.TRIANGLE_STRIP,0,s.webglNumPoints)}})}_drawTriangles(e){let t=this.webgl;t.bufferData(t.ARRAY_BUFFER,e.xy,t.STREAM_DRAW),t.useProgram(this._progLine);let s=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(s,false,new Float32Array([e.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,e.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let h=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(h,new Float32Array([e.offsetX+this.gOffsetX,e.offsetY+this.gOffsetY]));let r=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(r,new Int32Array([0,0]));let a=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(a,[e.color.r,e.color.g,e.color.b,e.color.a]),t.drawArrays(t.TRIANGLE_STRIP,0,e.xy.length/2)}_drawThickLines(){this._thickLines.forEach(e=>{if(e.visible){let t=Math.min(this.gScaleX,this.gScaleY);e.setActualThickness(e.getThickness()/t),e.convertToTriPoints(),this._drawTriangles(e)}})}update(){this.clear(),this.draw()}draw(){this._drawLines(this.linesData),this._drawLines(this.linesAux),this._drawThickLines(),this._drawSurfaces(this.surfaces)}clear(){this.webgl.clear(this.webgl.COLOR_BUFFER_BIT)}_addLine(e){e._vbuffer=this.webgl.createBuffer(),this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER,e._vbuffer),this.webgl.bufferData(this.webgl.ARRAY_BUFFER,e.xy,this.webgl.STREAM_DRAW),e._coord=this.webgl.getAttribLocation(this._progLine,"coordinates"),this.webgl.vertexAttribPointer(e._coord,2,this.webgl.FLOAT,false,0,0),this.webgl.enableVertexAttribArray(e._coord)}addDataLine(e){this._addLine(e),this.linesData.push(e)}addAuxLine(e){this._addLine(e),this.linesAux.push(e)}addThickLine(e){this._addLine(e),this._thickLines.push(e)}addSurface(e){this._addLine(e),this.surfaces.push(e)}initThinLineProgram(){let e=` + attribute vec2 coordinates; + uniform mat2 uscale; + uniform vec2 uoffset; + uniform ivec2 is_log; + + void main(void) { + float x = (is_log[0]==1) ? log(coordinates.x) : coordinates.x; + float y = (is_log[1]==1) ? log(coordinates.y) : coordinates.y; + vec2 line = vec2(x, y); + gl_Position = vec4(uscale*line + uoffset, 0.0, 1.0); + }`,t=this.webgl.createShader(this.webgl.VERTEX_SHADER);this.webgl.shaderSource(t,e),this.webgl.compileShader(t);let s=` + precision mediump float; + uniform highp vec4 uColor; + void main(void) { + gl_FragColor = uColor; + }`,h=this.webgl.createShader(this.webgl.FRAGMENT_SHADER);this.webgl.shaderSource(h,s),this.webgl.compileShader(h),this._progLine=this.webgl.createProgram(),this.webgl.attachShader(this._progLine,t),this.webgl.attachShader(this._progLine,h),this.webgl.linkProgram(this._progLine)}popDataLine(){this.linesData.pop()}removeAllLines(){this._linesData=[],this._linesAux=[],this._thickLines=[],this._surfaces=[]}removeDataLines(){this._linesData=[]}removeAuxLines(){this._linesAux=[]}viewport(e,t,s,h){this.webgl.viewport(e,t,s,h)}log(e){this.debug&&console.log("[webgl-plot]:"+e)}};var y=class{constructor(){this.plots={}}initPlot(e,t){if(t||(t=new A(e.canvas,e.webglOptions)),!e._id)e._id=`plot${Math.floor(Math.random()*1e15)}`;else if(this.plots[e._id]){let l=this.plots[e._id].initial;if(e.lines){for(let i in e.lines)if(l.lines[i]&&Array.isArray(e.lines[i])){let f=e.lines[i];e.lines[i]=l.lines[i]}}e=Object.assign(l,e)}e.overlay&&(typeof e.overlay!="object"&&(e.overlay=document.createElement("canvas"),e.overlay.style.position="absolute",e.overlay.width=e.canvas.width,e.overlay.height=e.canvas.height,e.canvas.appendChild(e.overlay)),e.overlayCtx||(e.overlayCtx=e.overlay.getContext("2d"))),e.width&&(e.canvas.width=e.width,e.canvas.style&&(e.canvas.style.width=e.width+"px"),typeof e.overlay=="object"&&(e.overlay.width=e.width,e.overlay.style&&(e.overlay.style.width=e.width+"px"))),e.height&&(e.canvas.height=e.height,e.canvas.style&&(e.canvas.style.height=e.height+"px"),typeof e.overlay=="object"&&(e.overlay.height=e.height,e.overlay.style&&(e.overlay.style.height=e.height+"px"))),e.lines?.timestamp&&delete e.lines.timestamp;let s={};for(let l in e.lines)s[l]=Object.assign({},s[l]),"viewing"in e.lines[l]||(e.lines[l].viewing=true),s[l].viewing=e.lines[l].viewing,s[l].sps=e.lines[l].sps,s[l].nSec=e.lines[l].nSec,s[l].nPoints=e.lines[l].nPoints,s[l].ymin=e.lines[l].ymin,s[l].ymax=e.lines[l].ymax,s[l].units=e.lines[l].units;let h={plot:t,settings:e,initial:Object.assign(Object.assign({},e),{lines:s}),anim:()=>{t.update()}};this.plots[e._id]=h;let r=0,a=0;Object.keys(e.lines).forEach(l=>{e.lines[l]?.viewing!==false&&a++}),e.nLines=a;let o,n;typeof e.overlay=="object"&&(o=e.overlay,n=e.overlayCtx,n.clearRect(0,0,e.overlay.width,e.overlay.height),n.font=e.overlayFont?e.overlayFont:"1em Courier",n.fillStyle=e.overlayColor?e.overlayColor:"white");for(let l in e.lines){let i=e.lines[l];if(Array.isArray(i)&&(i={values:i},e.lines[l]=i),"viewing"in i||(i.viewing=true),i.color)Array.isArray(i.color)&&(i.color=new b(...i.color));else{let m=y.HSLToRGB(360*(r/a)%360,100,50,1);h.initial.lines[l].color=[...m,1],i.color=new b(...m,1)}let f;if(i.nSec&&i.sps?f=Math.ceil(i.nSec*i.sps):i.nPoints?f=i.nPoints:i.points?f=i.points:e.linePoints?f=e.linePoints:i.values?f=i.values.length:f=1e3,i.points=f,e.lines[l].viewing===false)continue;if((i.width||e.lineWidth)&&i.width!==0){let m=e.lineWidth;m||(m=i.width),i.width?i.line=new d(i.color,f,i.width):e.lineWidth&&(i.line=new d(i.color,f,e.lineWidth)),i.line.lineSpaceX(-1,2/i.line.numPoints)}else i.line=new v(i.color,f),i.line.arrangeX();i.values?.length===i.points?i.values.length!==f&&(i.interpolate?i.values.length>f?i.values=y.downsample(i.values,f):i.values.lengthi.points?i.values=i.values.slice(i.values.length-i.points):i.values=[...new Array(i.points-i.values.length).fill(0),...i.values]):Array.isArray(i.values)?i.values=[...new Array(f-i.values.length).fill(0),...i.values]:i.values=new Array(i.points).fill(0);let u=i.ymin,g=i.ymax;if(u===g?(g=i.values.length<=1e5?Math.max(...i.values):1,u=i.values.length<=1e5?Math.min(...i.values):0):isNaN(g)&&(g=i.values.length<=1e5?Math.max(...i.values):1),isNaN(u)&&(u=i.values.length<=1e5?Math.min(...i.values):0),u>g){let m=u;g=u,u=m}let p=Math.abs(u);if(i.absmax=p>g?p:g,"autoscale"in i||(i.autoscale=true),i.position||(i.position=e.nLines-r-1),i.autoscale?i.autoscale===2?("clamp"in i||(i.clamp=true),i.scaled=y.autoscale(i.values,i.position,a,i.centerZero,u,g,i.clamp)):(i.scaled=i.values,i.line.scaleY=y.getYScalar(i.values,a,i.centerZero,u,g),i.line.offsetY=y.getYOffset(i.position,a,u,i.line.scaleY)):i.scaled=i.values,i.scaled.forEach((m,L)=>i.line.setY(L,m)),i.line instanceof d?t.addThickLine(i.line):i.line instanceof v&&t.addDataLine(i.line),"xAxis"in i||(i.xAxis=true),i.xAxis){i.xColor?Array.isArray(i.xColor)&&(i.xColor=new b(...i.xColor)):i.xColor=new b(1,1,1,.3);let m=new v(i.xColor,2),L=i.autoscale?(r+1)*2/a-1-1/a:0;m.constY(L),m.arrangeX(),m.xy[2]=1,i.x=m,t.addAuxLine(m)}if(a>1&&i.autoscale&&r!==a-1){e.dividerColor?Array.isArray(e.dividerColor)&&(e.dividerColor=new b(...e.dividerColor)):e.dividerColor=new b(1,1,1,1);let m=new v(e.dividerColor,2);m.constY(i.autoscale?(r+1)*2/a-1:1),m.arrangeX(),m.xy[2]=1,i.divider=m,t.addAuxLine(m)}if(typeof e.overlay=="object"&&(i.useOverlay||!("useOverlay"in i))){let m=e.nLines-i.position-1;n.fillText(l,20,o.height*(m+.2)/e.nLines),n.fillText(`${Math.floor(g)===g?g:g?.toFixed(5)} ${i.units?i.units:""}`,o.width-100,o.height*(m+.2)/e.nLines),n.fillText(`${Math.floor(u)===u?u:u?.toFixed(5)} ${i.units?i.units:""}`,o.width-100,o.height*(m+.9)/e.nLines)}r++}return requestAnimationFrame(h.anim),this.plots[e._id]}deinitPlot(e){return typeof e=="string"&&(e=this.plots[e]),e.plot.clear(),e.plot.removeAllLines(),true}reinitPlot(e,t){if(typeof e=="string"){let s=e;e=this.plots[e],t._id||(t._id=s)}if(!!e.plot)return e.plot.clear(),e.plot.removeAllLines(),e.settings.overlayCtx&&e.settings.overlayCtx.clearRect(0,0,e.settings.overlay?.width,e.settings.overlay?.height),this.initPlot(t,e.plot)}getChartSettings(e,t){let s=this.plots[e];if(s){let h=Object.assign({},s.initial);for(let r in s.initial.lines)typeof s.initial.lines[r]?.ymax!="number"&&(h.lines[r].ymax=s.settings.lines[r]?.ymax),typeof s.initial.lines[r]?.ymin!="number"&&(h.lines[r].ymin=s.settings.lines[r]?.ymin),t&&(h.lines[r].values=s.settings.lines[r].values);return delete h.canvas,delete h.overlay,delete h.overlayCtx,h}}update(e,t,s=true){if(typeof e=="string"&&(e=this.plots[e]),!e)return false;if(t){let h=false,r,a;typeof e.settings.overlay=="object"&&(r=e.settings.overlay,a=e.settings.overlayCtx,a.font=e.settings.overlayFont?e.settings.overlayFont:"1em Courier",a.fillStyle=e.settings.overlayColor?e.settings.overlayColor:"white");for(let o in t)if(e.settings.lines[o]&&e.settings.lines[o].line){if(e.settings.lines[o]?.viewing===false)continue;let n=e.settings.lines[o];if(Array.isArray(t[o])&&n.values.length<1e5?t[o].length===n.values.length?n.values=t[o]:y.circularBuffer(n.values,t[o]):typeof t[o]=="number"?(n.values.push(t[o]),n.values.shift()):t[o]?.values&&(t[o].values.length===n.values.length?n.values=t[o].values:y.circularBuffer(n.values,t[o].values)),n.values){n.values.length!==n.points&&(n.interpolate?n.values.length>n.points?n.values=y.downsample(n.values,n.points):n.scaled.lengthn.points?n.values.splice(0,n.values.length-n.points):n.values=new Array(n.points).fill(0).splice(n.points-n.values.length,0,n.values));let l=n.ymin,i=n.ymax;if(l===i?(i=n.values.length<=1e5?Math.max(...n.values):1,l=n.values.length<=1e5?Math.min(...n.values):0):isNaN(i)&&(i=n.values.length<=1e5?Math.max(...n.values):1),isNaN(l)&&(l=n.values.length<=1e5?Math.min(...n.values):0),l>i){let u=l;i=l,l=u}let f=Math.abs(l);if(n.absmax=f>i?f:i,n.autoscale?n.autoscale===2?n.scaled=y.autoscale(n.values,n.position,e.settings.nLines,n.centerZero,l,i,n.clamp):(n.scaled=n.values,n.line.scaleY=y.getYScalar(n.values,e.settings.nLines,n.centerZero,l,i),n.line.offsetY=y.getYOffset(n.position,e.settings.nLines,l,n.line.scaleY)):n.scaled=n.values,n.scaled.forEach((u,g)=>{!n.autoscale&&n.absmax>1?n.line.setY(g,u/n.absmax):n.line.setY(g,u)}),typeof e.settings.overlay=="object"&&(n.useOverlay||!("useOverlay"in n))){let u=e.settings.nLines-n.position-1;a.clearRect(0,r.height*u/e.settings.nLines,r.width,r.height/e.settings.nLines),a.fillText(o,20,r.height*(u+.2)/e.settings.nLines),a.fillText(`${Math.floor(i)===i?i:i?.toFixed(5)} ${n.units?n.units:""}`,r.width-100,r.height*(u+.2)/e.settings.nLines),a.fillText(`${Math.floor(l)===l?l:l?.toFixed(5)} ${n.units?n.units:""}`,r.width-100,r.height*(u+.9)/e.settings.nLines)}}}else e.settings.generateNewLines&&!o.includes("timestamp")&&(Array.isArray(t[o])&&(t[o]={values:t[o]}),!t[o].nSec&&!t[o].nPoints&&!e.settings.linePoints&&(t[o].nPoints=1e3),h=true);if(h)return e.settings.cleanGeneration||Object.keys(e.initial.lines).forEach(o=>{t[o]?t[o]=Object.assign(e.initial.lines[o],t[o]):t[o]=e.initial.lines[o]}),this.reinitPlot(e,{_id:e.settings._id,lines:t}),true}return s&&requestAnimationFrame(e.anim),true}updateLine(e,t,s,h,r,a,o){return e.numPoints!==t.length&&(s?e.numPoints>t.length?t=y.downsample(t,e.numPoints):e.numPointse.numPoints?t=t.slice(t.length-e.numPoints):t=[...new Array(t.length).fill(0),...t]),h&&(t=y.autoscale(t,r,a,o)),t.forEach((n,l)=>e.setY(l,n)),true}static autoscale(e,t=0,s=1,h=false,r,a,o){if(e?.length===0)return e;let n=typeof a=="number"?a:e.length<=1e5?Math.max(...e):1,l=typeof r=="number"?r:e.length<=1e5?Math.min(...e):0,i=1/s,f=1;if(h){let u=Math.max(Math.abs(l),Math.abs(n));return u!==0&&(f=i/u),e.map(g=>(o&&(gn&&(g=n)),g*f+(i*(t+1)*2-1-i)))}else return n===l?n!==0?f=i/n:l!==0&&(f=i/Math.abs(l)):f=i/(n-l),e.map(u=>(o&&(un&&(u=n)),2*((u-l)*f-1/(2*s))+(i*(t+1)*2-1-i)))}static getYScalar(e,t=1,s=false,h,r){if(e?.length===0)return e;let a=typeof r=="number"?r:e.length<=1e5?Math.max(...e):1,o=typeof h=="number"?h:e.length<=1e5?Math.min(...e):0,n=1/t,l=1;if(s){let i=Math.max(Math.abs(o),Math.abs(a));return i!==0&&(l=n/i),2*l}else return a===o?a!==0?l=n/a:o!==0&&(l=n/Math.abs(o)):l=n/(a-o),2*l}static getYOffset(e=0,t=1,s=0,h=1){let r=1/t,a=r*(e+1)*2-1-r;return s>0&&(a-=s*h+1/t),a}static absmax(e){return Math.max(Math.abs(Math.min(...e)),Math.max(...e))}static downsample(e,t,s=1){if(e.length>t){let h=new Array(t),r=e.length/t,a=e.length-1,o=0,n=0;for(let l=r;la&&(i=a);for(let f=o;ft?y.downsample(e,t,s):e.lengthe.length){let s=e.length;e.splice(0,s,t.slice(s-t.length))}else e.splice(0,e.length,...t);return e}static formatDataForCharts(e,t){if(Array.isArray(e)){if(Array.isArray(e[0])){let s={};if(e.forEach((h,r)=>{s[r]=h}),e=s,isNaN(e[0][0]))return}else if(t){if(e={[t]:e},isNaN(e[t][0]))return}else if(e={0:e},isNaN(e[0][0]))return}else if(typeof e=="object"){for(let s in e)if(typeof e[s]=="number"?e[s]=[e[s]]:e[s]?.values&&typeof e[s].values=="number"&&(e[s].values=[e[s].values]),isNaN(e[s][0]))return}else if(typeof e=="string"){let s;if(e.includes(`\r +`)){let h=e.split(`\r +`);e={},h.forEach((r,a)=>{r.includes(" ")?s=r.split(" "):r.includes(",")?s=r.split(","):r.includes("|")&&(s=r.split("|")),s&&s.forEach((o,n)=>{if(o.includes(":")){let[l,i]=o.split(":"),f=parseFloat(i);isNaN(f)||(e[l]=[f])}else{let l=parseFloat(o);isNaN(l)||(e[n]=[l])}})})}else e.includes(" ")?s=e.split(" "):e.includes(",")?s=e.split(","):e.includes("|")&&(s=e.split("|"));e={},s&&s.forEach((h,r)=>{if(h.includes(":")){let[a,o]=h.split(":"),n=parseFloat(o);isNaN(n)||(e[a]=[n])}else{let a=parseFloat(h);isNaN(a)||(e[r]=[a])}})}else typeof e=="number"&&(t?e={[t]:[e]}:e={0:[e]});return e}static padTime(e,t,s,h){let r=(e[0]-t)/s/h;return[...new Array(h-e.length).map((o,n)=>t+r*(n+1)),...e]}static interpolateForTime(e,t,s){return y.interpolate(e,Math.ceil(s*t))}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new y;return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new y;return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` + + + + + + + + + + + + + + `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` + + + + + + + + + + + + + + + `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var url=URL.createObjectURL(new Blob([String('(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browser=__commonJS({"../node_modules/web-worker/cjs/browser.js"(exports,module){module.exports=Worker}});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\\\"))args[0]=args[0].replace(/\\\\/g,"");if(args[0][0]===\'"\'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent2,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent2?.callback&&parent2?.worker))node.parentRoute=parent2?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setTree(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w2=s.worker;let wpId;wpId=service.establishMessageChannel(w2.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w2.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w2.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w2.run("setValue",["routeProxy",s.route]);w2.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w22=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w2.worker,w22.worker);s.pipeTo.worker=w22}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w2.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w2.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w2,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w2.run("setValue",["routeProxy",s.route]);service.transferFunction(w2,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w2.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w2.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w2.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w2.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w2.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w2.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;Object.assign(this.__node.graph.ALGORITHMS[_id],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;let res=this.__node.graph.ALGORITHMS[_id].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id]:res});return res}}}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b2)=>arr.filter(v2=>v2===a).length-arr.filter(v2=>v2===b2).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b2-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v2=>(v2-min)/(max-min))}static quadraticFormula(a,b2,c){let bbmac4=Math.sqrt(b2*b2-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b2*_a2];let nb=-b2;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x22=>{return Math.pow(x22,5)+x22*x22-x22-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v2,i,x22,y2)=>{return v2+x22+y2}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v2}, idx:${idx}, x:${i},y:${j}`);return v2+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x22,y2)=>{return[x22*10,y2*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_2,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b2){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b2.length,bNumCols=b2[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix22*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y2=0;y2{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x22=arr.filter((element,index)=>{return index%factor===0});return x22}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x22){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x22=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b2=0;if(0<=h&&h<60){r=c;g=x22;b2=0}else if(60<=h&&h<120){r=x22;g=c;b2=0}else if(120<=h&&h<180){r=0;g=c;b2=x22}else if(180<=h&&h<240){r=0;g=x22;b2=c}else if(240<=h&&h<300){r=x22;g=0;b2=c}else if(300<=h&&h<360){r=c;g=0;b2=x22}r=(r+m)*scalar;g=(g+m)*scalar;b2=(b2+m)*scalar;return[r,g,b2]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x22=>{let y2=x22;return y2},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x22+y2;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w2=x22+y2+z;return w2},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x22;return y2},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y2=0;y2{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{if(!("ax"in data)&&!("gx"in data))return void 0;if(!data.timestamp){if(data.ax&&Array.isArray(data.ax)||data.gx&&Array.isArray(data.gx)){let len=data.ax?data.ax.length:data.gx.length;let now=Date.now();let toInterp=[now-len*ctx.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,len)}else{data.timestamp=Date.now()}}let result;if(data.ax){let apass=(timestamp,ax,ay,az)=>{ax=ax*ctx.accelConstant;ay=ay*ctx.accelConstant;az=az*ctx.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+ctx.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+ctx.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v2,i)=>{return apass(v2,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-ctx.lastGyroTime;ctx.lastGyroTime=timestamp;gx=gx*ctx.gyroConstant+ctx.gyroXError;gy=gy*ctx.gyroConstant+ctx.gyroYError;gz=gz*ctx.gyroConstant+ctx.gyroZError;ctx.gyroXAngle+=gx*elapsed;ctx.gyroYAngle+=gy*elapsed;ctx.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:ctx.gyroXAngle,pitch:ctx.gyroYAngle,yaw:ctx.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v2,i)=>{if(result){let r=gpass(v2,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v2,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(ctx.gyroXAngle||ctx.gyroYAngle||ctx.gyroZAngle){result.roll=result.roll*.04+ctx.gyroXAngle*.96;result.pitch=result.pitch*.04+ctx.gyroYAngle*.96;result.yaw=ctx.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-ctx.lastAccelTime;ctx.lastAccelTime=timestamp;ctx.px+=result2.ax*elapsed*elapsed*Math.cos(ctx.pitch*Math.PI*.005555555555);ctx.py+=result2.ay*elapsed*elapsed*Math.cos(ctx.roll*Math.PI*.005555555555);ctx.pz+=result2.az*elapsed*elapsed*Math.sin(ctx.pitch*Math.PI*.005555555555);result2.px=ctx.px;result2.py=ctx.py;result2.pz=ctx.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){this.a0=0;this.a1=0;this.a2=0;this.b0=0;this.b1=0;this.b2=0;this.x1=0;this.x2=0;this.y1=0;this.y2=0;let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A2=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A2+A2);this[type](A2,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A2,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A2,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A2,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A2,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A2,sn,cs,alpha,beta){this.b0=1+alpha*A2;this.b1=-2*cs;this.b2=1-alpha*A2;this.a0=1+alpha/A2;this.a1=-2*cs;this.a2=1-alpha/A2}lowshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1-(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1-(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1+(A2+1)*cs+beta*sn;this.a1=2*(A2-1+(A2+1)*cs);this.a2=A2+1+(A2-1)*cs-beta*sn}highshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1+(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1+(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1-(A2+1)*cs-beta*sn;this.a1=2*(A2-1-(A2+1)*cs);this.a2=A2+1-(A2-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={structs:{refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10},oncreate:context=>{if(!context.lowpass){let freq=context.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;context.lowpass=new Biquad("lowpass",context.maxFreq,context.sps);context.peakFinderWindow=Math.floor(context.sps/context.maxFreq);if(context.peakFinderWindow%2===0)context.peakFinderWindow+=1;if(context.peakFinderWindow<5)context.peakFinderWindow=5;context.midpoint=Math.round(context.peakFinderWindow*.5)}},ondata:(context,data)=>{if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*context.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){context.refdata.push(amplitude)}context.timestamp.push(timestamp);let beat;if(context.refdata.length>context.peakFinderWindow){context.refdata.shift();context.timestamp.shift()}context.smoothed.push(context.lowpass.applyFilter(context.refdata[context.refdata.length-1]));if(context.smoothed.length>context.peakFinderWindow){context.smoothed.shift()}if(context.smoothed.length===context.peakFinderWindow){if(Math2.isExtrema(context.smoothed,"valley")){context.valleys.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}else if(Math2.isExtrema(context.smoothed,"peak")){context.peaks.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}if(context.valleys.length>2&&context.peaks.length>2){if(context.valleys[context.valleys.length-1].timestamp1&&context.valley_distances.length>1){if(context.lastPeakcontext.peak_distances[context.peak_distances.length-1].timestamp){let bpm,change=0;if(context.beats.length<1){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].distance+context.valley_distances[context.valley_distances.length-1].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-1].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].dt+context.valley_distances[context.valley_distances.length-1].dt));change=Math.abs(bpm-context.beats[context.beats.length-1].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-1].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-1].peak0-context.valley_distances[context.valley_distances.length-1].peak0,height1:context.peak_distances[context.peak_distances.length-1].peak1-context.valley_distances[context.valley_distances.length-1].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}else{let bpm,change=0;if(context.beats.length<2){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-2].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance));change=Math.abs(bpm-context.beats[context.beats.length-2].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-2].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-2].peak0-context.valley_distances[context.valley_distances.length-2].peak0,height1:context.peak_distances[context.peak_distances.length-2].peak1-context.valley_distances[context.valley_distances.length-2].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}}}if(context.peaks.length>context.limit){context.peaks.shift()}if(context.valleys.length>context.limit){context.valleys.shift()}if(context.peak_distances.length>context.limit){context.peak_distances.shift()}if(context.valley_distances.length>context.limit){context.valley_distances.shift()}if(context.beats.length>context.limit){context.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)data.red.map((v2,i)=>{return pass(v2+data.ir[i],data.timestamp[i])});else data.red.map((v2,i)=>{return pass(v2,data.timestamp[i])});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v2,i)=>{return pass(v2,data.timestamp[i])});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v2,i)=>{return pass(v2,data.timestamp[i])});return result}}};var blink_detect={structs:{sps:250,intervals:{},watch:["0"],tolerance:.2},oncreate:ctx=>{ctx.watch.forEach(ch=>ctx.intervals[ch]={lowpass:new Biquad("lowpass",20,ctx.sps),filtered:[],averaged:[]})},ondata:(ctx,data)=>{let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=ctx.intervals[key].lowpass.applyFilter(n);ctx.intervals[key].filtered.push(next);ctx.intervals[key].averaged.push(next);if(ctx.intervals[key].filtered.length>checkCt){if(ctx.intervals[key].averaged.length>averageCt){ctx.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(ctx.intervals[key].averaged);if(Math.abs(Math.min(...ctx.intervals[key].filtered))>Math.abs(mean)+ctx.tolerance){ctx.intervals[key].filtered.length=0;passed=true;found[key]=true}}else ctx.intervals[key].filtered.shift()}};for(const key in ctx.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var _ArrayManip=class{constructor(){this.recursivelyAssign=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target}}static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d2={};data.forEach((arr,i)=>{d2[i]=arr});data=d2;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_2,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var ArrayManip=_ArrayManip;ArrayManip.bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v2,o,c)=>String.fromCharCode(...new Uint8Array(v2.buffer,v2.byteOffset+o,c));var rts=(v2,o,c,s)=>new Uint8Array(v2.buffer,v2.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v2,o,c)=>str(v2,o+1,Math.min(v2.getUint8(o),c-1));var tsp=(v2,o,c,s)=>{v2.setUint8(o,s.length);rts(v2,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v2=>str(v2,o,1),p:(v2,c2)=>rts(v2,o,1,c2)})],"?":c=>[c,1,o=>({u:v2=>Boolean(v2.getUint8(o)),p:(v2,B)=>v2.setUint8(o,B)})],b:c=>[c,1,o=>({u:v2=>v2.getInt8(o),p:(v2,b2)=>v2.setInt8(o,b2)})],B:c=>[c,1,o=>({u:v2=>v2.getUint8(o),p:(v2,B)=>v2.setUint8(o,B)})],h:c=>[c,2,o=>({u:v2=>v2.getInt16(o,le),p:(v2,h)=>v2.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v2=>v2.getUint16(o,le),p:(v2,H)=>v2.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v2=>v2.getInt32(o,le),p:(v2,i)=>v2.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v2=>v2.getUint32(o,le),p:(v2,I)=>v2.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v2=>v2.getFloat32(o,le),p:(v2,f)=>v2.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v2=>v2.getFloat64(o,le),p:(v2,d2)=>v2.setFloat64(o,d2,le)})],s:c=>[1,c,o=>({u:v2=>str(v2,o,c),p:(v2,s)=>rts(v2,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v2=>pst(v2,o,c),p:(v2,s)=>tsp(v2,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var _ByteParser=class extends ArrayManip{static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x22){let int24=(255&x0)<<16|(255&x1)<<8|255&x22;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x22){return x0*65536+x1*256+x22}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x22,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x22)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x22,x3){return x0*16777216+x1*65536+x22*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M2=pattern.length;if(M2===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R2=256;var rightmost_positions=new Int32Array(R2);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v2=new DataView(arrb,offs|0);return fns.map(f=>f.u(v2))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v2,values[i]))};const pack=(...values)=>{let b2=new ArrayBuffer(size);pack_into(b2,0,...values);return b2};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var ByteParser=_ByteParser;ByteParser.codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};var rms={structs:{sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{}},ondata:(ctx,data)=>{ctx.watch.forEach(key=>{if(data[key]){if(!ctx.data[key]){if(Array.isArray(data[key])){ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key][0])}else ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key])}ByteParser.circularBuffer(ctx.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){ctx.rms.timestamp=data.timestamp[data.timestamp.length-1]}else ctx.rms.timestamp=data.timestamp}else ctx.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(ctx.watch.map(async key=>{if(ctx.data[key])ctx.rms[key]=Math.sqrt(Math.abs(ctx.data[key].reduce((p,v2,i)=>p+v2*v2)/ctx.data[key].length));else delete ctx.rms[key]}));res(ctx.rms)})}};var circularBuffer2d={structs:{bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false},oncreate:ctx=>{for(const key in ctx.watch){ctx.data[key]=new Array(ctx.bufferSize).fill(0)}},ondata:(ctx,data)=>{let buffer2d=[];ctx.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(ctx.data[key],data[key]);buffer2d.push(ctx.data[key])}});return buffer2d}};Object.assign(algorithms,{beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d});algorithms["breath"].structs=JSON.parse(JSON.stringify(algorithms["breath"].structs));algorithms["breath"].structs.maxFreq=.2;})(); diff --git a/src/extras/dist/index.storage.services.d.ts b/extras/dist/index.storage.services.d.ts similarity index 100% rename from src/extras/dist/index.storage.services.d.ts rename to extras/dist/index.storage.services.d.ts diff --git a/extras/dist/index.storage.services.esm.js b/extras/dist/index.storage.services.esm.js new file mode 100644 index 00000000..b573330f --- /dev/null +++ b/extras/dist/index.storage.services.esm.js @@ -0,0 +1,12 @@ +var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browserfs=__commonJS({"node_modules/browserfs/dist/browserfs.js"(exports,module){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["BrowserFS"]=factory();else root["BrowserFS"]=factory()})(exports,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module2=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__);module2.loaded=true;return module2.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module2,exports2,__webpack_require__){(function(Buffer2,global,module3,process){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var buffer=__webpack_require__(2);var path=__webpack_require__(9);var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2["EPERM"]=1]="EPERM";ErrorCode2[ErrorCode2["ENOENT"]=2]="ENOENT";ErrorCode2[ErrorCode2["EIO"]=5]="EIO";ErrorCode2[ErrorCode2["EBADF"]=9]="EBADF";ErrorCode2[ErrorCode2["EACCES"]=13]="EACCES";ErrorCode2[ErrorCode2["EBUSY"]=16]="EBUSY";ErrorCode2[ErrorCode2["EEXIST"]=17]="EEXIST";ErrorCode2[ErrorCode2["ENOTDIR"]=20]="ENOTDIR";ErrorCode2[ErrorCode2["EISDIR"]=21]="EISDIR";ErrorCode2[ErrorCode2["EINVAL"]=22]="EINVAL";ErrorCode2[ErrorCode2["EFBIG"]=27]="EFBIG";ErrorCode2[ErrorCode2["ENOSPC"]=28]="ENOSPC";ErrorCode2[ErrorCode2["EROFS"]=30]="EROFS";ErrorCode2[ErrorCode2["ENOTEMPTY"]=39]="ENOTEMPTY";ErrorCode2[ErrorCode2["ENOTSUP"]=95]="ENOTSUP"})(ErrorCode||(ErrorCode={}));var ErrorStrings={};ErrorStrings[ErrorCode.EPERM]="Operation not permitted.";ErrorStrings[ErrorCode.ENOENT]="No such file or directory.";ErrorStrings[ErrorCode.EIO]="Input/output error.";ErrorStrings[ErrorCode.EBADF]="Bad file descriptor.";ErrorStrings[ErrorCode.EACCES]="Permission denied.";ErrorStrings[ErrorCode.EBUSY]="Resource busy or locked.";ErrorStrings[ErrorCode.EEXIST]="File exists.";ErrorStrings[ErrorCode.ENOTDIR]="File is not a directory.";ErrorStrings[ErrorCode.EISDIR]="File is a directory.";ErrorStrings[ErrorCode.EINVAL]="Invalid argument.";ErrorStrings[ErrorCode.EFBIG]="File is too big.";ErrorStrings[ErrorCode.ENOSPC]="No space left on disk.";ErrorStrings[ErrorCode.EROFS]="Cannot modify a read-only file system.";ErrorStrings[ErrorCode.ENOTEMPTY]="Directory is not empty.";ErrorStrings[ErrorCode.ENOTSUP]="Operation is not supported.";var ApiError=function(Error2){function ApiError2(type,message,path$$1){if(message===void 0)message=ErrorStrings[type];Error2.call(this,message);this.syscall="";this.errno=type;this.code=ErrorCode[type];this.path=path$$1;this.stack=new Error2().stack;this.message="Error: "+this.code+": "+message+(this.path?", '"+this.path+"'":"")}if(Error2)ApiError2.__proto__=Error2;ApiError2.prototype=Object.create(Error2&&Error2.prototype);ApiError2.prototype.constructor=ApiError2;ApiError2.fromJSON=function fromJSON(json){var err=new ApiError2(0);err.errno=json.errno;err.code=json.code;err.path=json.path;err.stack=json.stack;err.message=json.message;return err};ApiError2.fromBuffer=function fromBuffer(buffer$$1,i2){if(i2===void 0)i2=0;return ApiError2.fromJSON(JSON.parse(buffer$$1.toString("utf8",i2+4,i2+4+buffer$$1.readUInt32LE(i2))))};ApiError2.FileError=function FileError(code,p){return new ApiError2(code,ErrorStrings[code],p)};ApiError2.ENOENT=function ENOENT(path$$1){return this.FileError(ErrorCode.ENOENT,path$$1)};ApiError2.EEXIST=function EEXIST(path$$1){return this.FileError(ErrorCode.EEXIST,path$$1)};ApiError2.EISDIR=function EISDIR(path$$1){return this.FileError(ErrorCode.EISDIR,path$$1)};ApiError2.ENOTDIR=function ENOTDIR(path$$1){return this.FileError(ErrorCode.ENOTDIR,path$$1)};ApiError2.EPERM=function EPERM(path$$1){return this.FileError(ErrorCode.EPERM,path$$1)};ApiError2.ENOTEMPTY=function ENOTEMPTY(path$$1){return this.FileError(ErrorCode.ENOTEMPTY,path$$1)};ApiError2.prototype.toString=function toString(){return this.message};ApiError2.prototype.toJSON=function toJSON(){return{errno:this.errno,code:this.code,path:this.path,stack:this.stack,message:this.message}};ApiError2.prototype.writeToBuffer=function writeToBuffer(buffer$$1,i2){if(buffer$$1===void 0)buffer$$1=Buffer2.alloc(this.bufferSize());if(i2===void 0)i2=0;var bytesWritten=buffer$$1.write(JSON.stringify(this.toJSON()),i2+4);buffer$$1.writeUInt32LE(bytesWritten,i2);return buffer$$1};ApiError2.prototype.bufferSize=function bufferSize(){return 4+Buffer2.byteLength(JSON.stringify(this.toJSON()))};return ApiError2}(Error);var api_error=Object.freeze({get ErrorCode(){return ErrorCode},ErrorStrings,ApiError});var ActionType;(function(ActionType2){ActionType2[ActionType2["NOP"]=0]="NOP";ActionType2[ActionType2["THROW_EXCEPTION"]=1]="THROW_EXCEPTION";ActionType2[ActionType2["TRUNCATE_FILE"]=2]="TRUNCATE_FILE";ActionType2[ActionType2["CREATE_FILE"]=3]="CREATE_FILE"})(ActionType||(ActionType={}));var FileFlag=function FileFlag2(flagStr){this.flagStr=flagStr;if(FileFlag2.validFlagStrs.indexOf(flagStr)<0){throw new ApiError(ErrorCode.EINVAL,"Invalid flag: "+flagStr)}};FileFlag.getFileFlag=function getFileFlag(flagStr){if(FileFlag.flagCache.hasOwnProperty(flagStr)){return FileFlag.flagCache[flagStr]}return FileFlag.flagCache[flagStr]=new FileFlag(flagStr)};FileFlag.prototype.getFlagString=function getFlagString(){return this.flagStr};FileFlag.prototype.isReadable=function isReadable(){return this.flagStr.indexOf("r")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isWriteable=function isWriteable(){return this.flagStr.indexOf("w")!==-1||this.flagStr.indexOf("a")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isTruncating=function isTruncating(){return this.flagStr.indexOf("w")!==-1};FileFlag.prototype.isAppendable=function isAppendable(){return this.flagStr.indexOf("a")!==-1};FileFlag.prototype.isSynchronous=function isSynchronous(){return this.flagStr.indexOf("s")!==-1};FileFlag.prototype.isExclusive=function isExclusive(){return this.flagStr.indexOf("x")!==-1};FileFlag.prototype.pathExistsAction=function pathExistsAction(){if(this.isExclusive()){return ActionType.THROW_EXCEPTION}else if(this.isTruncating()){return ActionType.TRUNCATE_FILE}else{return ActionType.NOP}};FileFlag.prototype.pathNotExistsAction=function pathNotExistsAction(){if((this.isWriteable()||this.isAppendable())&&this.flagStr!=="r+"){return ActionType.CREATE_FILE}else{return ActionType.THROW_EXCEPTION}};FileFlag.flagCache={};FileFlag.validFlagStrs=["r","r+","rs","rs+","w","wx","w+","wx+","a","ax","a+","ax+"];var FileType;(function(FileType2){FileType2[FileType2["FILE"]=32768]="FILE";FileType2[FileType2["DIRECTORY"]=16384]="DIRECTORY";FileType2[FileType2["SYMLINK"]=40960]="SYMLINK"})(FileType||(FileType={}));var Stats=function Stats2(itemType,size,mode,atime,mtime,ctime){if(atime===void 0)atime=new Date;if(mtime===void 0)mtime=new Date;if(ctime===void 0)ctime=new Date;this.size=size;this.atime=atime;this.mtime=mtime;this.ctime=ctime;this.dev=0;this.ino=0;this.rdev=0;this.nlink=1;this.blksize=4096;this.uid=0;this.gid=0;this.birthtime=new Date(0);this.fileData=null;if(!mode){switch(itemType){case FileType.FILE:this.mode=420;break;case FileType.DIRECTORY:default:this.mode=511}}else{this.mode=mode}this.blocks=Math.ceil(size/512);if(this.mode<4096){this.mode|=itemType}};Stats.fromBuffer=function fromBuffer(buffer$$1){var size=buffer$$1.readUInt32LE(0),mode=buffer$$1.readUInt32LE(4),atime=buffer$$1.readDoubleLE(8),mtime=buffer$$1.readDoubleLE(16),ctime=buffer$$1.readDoubleLE(24);return new Stats(mode&61440,size,mode&4095,new Date(atime),new Date(mtime),new Date(ctime))};Stats.prototype.toBuffer=function toBuffer(){var buffer$$1=Buffer2.alloc(32);buffer$$1.writeUInt32LE(this.size,0);buffer$$1.writeUInt32LE(this.mode,4);buffer$$1.writeDoubleLE(this.atime.getTime(),8);buffer$$1.writeDoubleLE(this.mtime.getTime(),16);buffer$$1.writeDoubleLE(this.ctime.getTime(),24);return buffer$$1};Stats.prototype.clone=function clone(){return new Stats(this.mode&61440,this.size,this.mode&4095,this.atime,this.mtime,this.ctime)};Stats.prototype.isFile=function isFile(){return(this.mode&61440)===FileType.FILE};Stats.prototype.isDirectory=function isDirectory(){return(this.mode&61440)===FileType.DIRECTORY};Stats.prototype.isSymbolicLink=function isSymbolicLink(){return(this.mode&61440)===FileType.SYMLINK};Stats.prototype.chmod=function chmod(mode){this.mode=this.mode&61440|mode};Stats.prototype.isSocket=function isSocket(){return false};Stats.prototype.isBlockDevice=function isBlockDevice(){return false};Stats.prototype.isCharacterDevice=function isCharacterDevice(){return false};Stats.prototype.isFIFO=function isFIFO(){return false};var wrapCb=function(cb,numArgs){return cb};function assertRoot(fs4){if(fs4){return fs4}throw new ApiError(ErrorCode.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function normalizeMode(mode,def){switch(typeof mode){case"number":return mode;case"string":var trueMode=parseInt(mode,8);if(!isNaN(trueMode)){return trueMode}return def;default:return def}}function normalizeTime(time){if(time instanceof Date){return time}else if(typeof time==="number"){return new Date(time*1e3)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid time.")}}function normalizePath(p){if(p.indexOf("\0")>=0){throw new ApiError(ErrorCode.EINVAL,"Path must be a string without null bytes.")}else if(p===""){throw new ApiError(ErrorCode.EINVAL,"Path must not be empty.")}return path.resolve(p)}function normalizeOptions(options,defEnc,defFlag,defMode){switch(typeof options){case"object":return{encoding:typeof options["encoding"]!=="undefined"?options["encoding"]:defEnc,flag:typeof options["flag"]!=="undefined"?options["flag"]:defFlag,mode:normalizeMode(options["mode"],defMode)};case"string":return{encoding:options,flag:defFlag,mode:defMode};default:return{encoding:defEnc,flag:defFlag,mode:defMode}}}function nopCb(){}var FS=function FS2(){this.F_OK=0;this.R_OK=4;this.W_OK=2;this.X_OK=1;this.root=null;this.fdMap={};this.nextFd=100};FS.prototype.initialize=function initialize3(rootFS){if(!rootFS.constructor.isAvailable()){throw new ApiError(ErrorCode.EINVAL,"Tried to instantiate BrowserFS with an unavailable file system.")}return this.root=rootFS};FS.prototype._toUnixTimestamp=function _toUnixTimestamp(time){if(typeof time==="number"){return time}else if(time instanceof Date){return time.getTime()/1e3}throw new Error("Cannot parse time: "+time)};FS.prototype.getRootFS=function getRootFS(){if(this.root){return this.root}else{return null}};FS.prototype.rename=function rename(oldPath,newPath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).rename(normalizePath(oldPath),normalizePath(newPath),newCb)}catch(e){newCb(e)}};FS.prototype.renameSync=function renameSync(oldPath,newPath){assertRoot(this.root).renameSync(normalizePath(oldPath),normalizePath(newPath))};FS.prototype.exists=function exists2(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).exists(normalizePath(path$$1),newCb)}catch(e){return newCb(false)}};FS.prototype.existsSync=function existsSync(path$$1){try{return assertRoot(this.root).existsSync(normalizePath(path$$1))}catch(e){return false}};FS.prototype.stat=function stat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),false,newCb)}catch(e){return newCb(e)}};FS.prototype.statSync=function statSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),false)};FS.prototype.lstat=function lstat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),true,newCb)}catch(e){return newCb(e)}};FS.prototype.lstatSync=function lstatSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),true)};FS.prototype.truncate=function truncate(path$$1,arg2,cb){if(arg2===void 0)arg2=0;if(cb===void 0)cb=nopCb;var len=0;if(typeof arg2==="function"){cb=arg2}else if(typeof arg2==="number"){len=arg2}var newCb=wrapCb(cb,1);try{if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncate(normalizePath(path$$1),len,newCb)}catch(e){return newCb(e)}};FS.prototype.truncateSync=function truncateSync(path$$1,len){if(len===void 0)len=0;if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncateSync(normalizePath(path$$1),len)};FS.prototype.unlink=function unlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).unlink(normalizePath(path$$1),newCb)}catch(e){return newCb(e)}};FS.prototype.unlinkSync=function unlinkSync(path$$1){return assertRoot(this.root).unlinkSync(normalizePath(path$$1))};FS.prototype.open=function open(path$$1,flag,arg2,cb){var this$1=this;if(cb===void 0)cb=nopCb;var mode=normalizeMode(arg2,420);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{assertRoot(this.root).open(normalizePath(path$$1),FileFlag.getFileFlag(flag),mode,function(e,file){if(file){newCb(e,this$1.getFdForFile(file))}else{newCb(e)}})}catch(e){newCb(e)}};FS.prototype.openSync=function openSync(path$$1,flag,mode){if(mode===void 0)mode=420;return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1),FileFlag.getFileFlag(flag),normalizeMode(mode,420)))};FS.prototype.readFile=function readFile2(filename,arg2,cb){if(arg2===void 0)arg2={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg2,null,"r",null);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{var flag=FileFlag.getFileFlag(options["flag"]);if(!flag.isReadable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading."))}return assertRoot(this.root).readFile(normalizePath(filename),options.encoding,flag,newCb)}catch(e){return newCb(e)}};FS.prototype.readFileSync=function readFileSync(filename,arg2){if(arg2===void 0)arg2={};var options=normalizeOptions(arg2,null,"r",null);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isReadable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading.")}return assertRoot(this.root).readFileSync(normalizePath(filename),options.encoding,flag)};FS.prototype.writeFile=function writeFile2(filename,data,arg3,cb){if(arg3===void 0)arg3={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","w",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing."))}return assertRoot(this.root).writeFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){return newCb(e)}};FS.prototype.writeFileSync=function writeFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","w",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing.")}return assertRoot(this.root).writeFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.appendFile=function appendFile3(filename,data,arg3,cb){if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","a",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending."))}assertRoot(this.root).appendFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){newCb(e)}};FS.prototype.appendFileSync=function appendFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","a",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending.")}return assertRoot(this.root).appendFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.fstat=function fstat(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{var file=this.fd2file(fd);file.stat(newCb)}catch(e){newCb(e)}};FS.prototype.fstatSync=function fstatSync(fd){return this.fd2file(fd).statSync()};FS.prototype.close=function close(fd,cb){var this$1=this;if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).close(function(e){if(!e){this$1.closeFd(fd)}newCb(e)})}catch(e){newCb(e)}};FS.prototype.closeSync=function closeSync(fd){this.fd2file(fd).closeSync();this.closeFd(fd)};FS.prototype.ftruncate=function ftruncate(fd,arg2,cb){if(cb===void 0)cb=nopCb;var length=typeof arg2==="number"?arg2:0;cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(length<0){throw new ApiError(ErrorCode.EINVAL)}file.truncate(length,newCb)}catch(e){newCb(e)}};FS.prototype.ftruncateSync=function ftruncateSync(fd,len){if(len===void 0)len=0;var file=this.fd2file(fd);if(len<0){throw new ApiError(ErrorCode.EINVAL)}file.truncateSync(len)};FS.prototype.fsync=function fsync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).sync(newCb)}catch(e){newCb(e)}};FS.prototype.fsyncSync=function fsyncSync(fd){this.fd2file(fd).syncSync()};FS.prototype.fdatasync=function fdatasync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).datasync(newCb)}catch(e){newCb(e)}};FS.prototype.fdatasyncSync=function fdatasyncSync(fd){this.fd2file(fd).datasyncSync()};FS.prototype.write=function write(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var buffer$$1,offset,length,position=null;if(typeof arg2==="string"){var encoding="utf8";switch(typeof arg3){case"function":cb=arg3;break;case"number":position=arg3;encoding=typeof arg4==="string"?arg4:"utf8";cb=typeof arg5==="function"?arg5:cb;break;default:cb=typeof arg4==="function"?arg4:typeof arg5==="function"?arg5:cb;return cb(new ApiError(ErrorCode.EINVAL,"Invalid arguments."))}buffer$$1=Buffer2.from(arg2,encoding);offset=0;length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null;cb=typeof arg5==="function"?arg5:cb}var newCb=wrapCb(cb,3);try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.write(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.writeSync=function writeSync(fd,arg2,arg3,arg4,arg5){var buffer$$1,offset=0,length,position;if(typeof arg2==="string"){position=typeof arg3==="number"?arg3:null;var encoding=typeof arg4==="string"?arg4:"utf8";offset=0;buffer$$1=Buffer2.from(arg2,encoding);length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}return file.writeSync(buffer$$1,offset,length,position)};FS.prototype.read=function read(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var position,offset,length,buffer$$1,newCb;if(typeof arg2==="number"){length=arg2;position=arg3;var encoding=arg4;cb=typeof arg5==="function"?arg5:cb;offset=0;buffer$$1=Buffer2.alloc(length);newCb=wrapCb(function(err,bytesRead,buf){if(err){return cb(err)}cb(err,buf.toString(encoding),bytesRead)},3)}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5;newCb=wrapCb(cb,3)}try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.read(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.readSync=function readSync(fd,arg2,arg3,arg4,arg5){var shenanigans=false;var buffer$$1,offset,length,position,encoding="utf8";if(typeof arg2==="number"){length=arg2;position=arg3;encoding=arg4;offset=0;buffer$$1=Buffer2.alloc(length);shenanigans=true}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}var rv=file.readSync(buffer$$1,offset,length,position);if(!shenanigans){return rv}else{return[buffer$$1.toString(encoding),rv]}};FS.prototype.fchown=function fchown(fd,uid,gid,callback){if(callback===void 0)callback=nopCb;var newCb=wrapCb(callback,1);try{this.fd2file(fd).chown(uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.fchownSync=function fchownSync(fd,uid,gid){this.fd2file(fd).chownSync(uid,gid)};FS.prototype.fchmod=function fchmod(fd,mode,cb){var newCb=wrapCb(cb,1);try{var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmod(numMode,newCb)}catch(e){newCb(e)}};FS.prototype.fchmodSync=function fchmodSync(fd,mode){var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmodSync(numMode)};FS.prototype.futimes=function futimes(fd,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(typeof atime==="number"){atime=new Date(atime*1e3)}if(typeof mtime==="number"){mtime=new Date(mtime*1e3)}file.utimes(atime,mtime,newCb)}catch(e){newCb(e)}};FS.prototype.futimesSync=function futimesSync(fd,atime,mtime){this.fd2file(fd).utimesSync(normalizeTime(atime),normalizeTime(mtime))};FS.prototype.rmdir=function rmdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).rmdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.rmdirSync=function rmdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).rmdirSync(path$$1)};FS.prototype.mkdir=function mkdir(path$$1,mode,cb){if(cb===void 0)cb=nopCb;if(typeof mode==="function"){cb=mode;mode=511}var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).mkdir(path$$1,mode,newCb)}catch(e){newCb(e)}};FS.prototype.mkdirSync=function mkdirSync(path$$1,mode){assertRoot(this.root).mkdirSync(normalizePath(path$$1),normalizeMode(mode,511))};FS.prototype.readdir=function readdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readdirSync=function readdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readdirSync(path$$1)};FS.prototype.link=function link(srcpath,dstpath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).link(srcpath,dstpath,newCb)}catch(e){newCb(e)}};FS.prototype.linkSync=function linkSync(srcpath,dstpath){srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).linkSync(srcpath,dstpath)};FS.prototype.symlink=function symlink(srcpath,dstpath,arg3,cb){if(cb===void 0)cb=nopCb;var type=typeof arg3==="string"?arg3:"file";cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{if(type!=="file"&&type!=="dir"){return newCb(new ApiError(ErrorCode.EINVAL,"Invalid type: "+type))}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).symlink(srcpath,dstpath,type,newCb)}catch(e){newCb(e)}};FS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(!type){type="file"}else if(type!=="file"&&type!=="dir"){throw new ApiError(ErrorCode.EINVAL,"Invalid type: "+type)}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).symlinkSync(srcpath,dstpath,type)};FS.prototype.readlink=function readlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readlink(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readlinkSync=function readlinkSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readlinkSync(path$$1)};FS.prototype.chown=function chown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,false,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.chownSync=function chownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,false,uid,gid)};FS.prototype.lchown=function lchown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,true,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.lchownSync=function lchownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,true,uid,gid)};FS.prototype.chmod=function chmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),false,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.chmodSync=function chmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}path$$1=normalizePath(path$$1);assertRoot(this.root).chmodSync(path$$1,false,numMode)};FS.prototype.lchmod=function lchmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),true,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.lchmodSync=function lchmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<1){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmodSync(normalizePath(path$$1),true,numMode)};FS.prototype.utimes=function utimes(path$$1,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).utimes(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime),newCb)}catch(e){newCb(e)}};FS.prototype.utimesSync=function utimesSync(path$$1,atime,mtime){assertRoot(this.root).utimesSync(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime))};FS.prototype.realpath=function realpath(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;var cache=typeof arg2==="object"?arg2:{};cb=typeof arg2==="function"?arg2:nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).realpath(path$$1,cache,newCb)}catch(e){newCb(e)}};FS.prototype.realpathSync=function realpathSync(path$$1,cache){if(cache===void 0)cache={};path$$1=normalizePath(path$$1);return assertRoot(this.root).realpathSync(path$$1,cache)};FS.prototype.watchFile=function watchFile(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.unwatchFile=function unwatchFile(filename,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.watch=function watch(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.access=function access(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.accessSync=function accessSync(path$$1,mode){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createReadStream=function createReadStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createWriteStream=function createWriteStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.wrapCallbacks=function wrapCallbacks(cbWrapper){wrapCb=cbWrapper};FS.prototype.getFdForFile=function getFdForFile(file){var fd=this.nextFd++;this.fdMap[fd]=file;return fd};FS.prototype.fd2file=function fd2file(fd){var rv=this.fdMap[fd];if(rv){return rv}else{throw new ApiError(ErrorCode.EBADF,"Invalid file descriptor.")}};FS.prototype.closeFd=function closeFd(fd){delete this.fdMap[fd]};FS.Stats=Stats;var fs3=new FS;var _fsMock={};var fsProto=FS.prototype;Object.keys(fsProto).forEach(function(key){if(typeof fs3[key]==="function"){_fsMock[key]=function(){return fs3[key].apply(fs3,arguments)}}else{_fsMock[key]=fs3[key]}});_fsMock["changeFSModule"]=function(newFs){fs3=newFs};_fsMock["getFSModule"]=function(){return fs3};_fsMock["FS"]=FS;function _min(d0,d1,d2,bx,ay){return d0d2?d2+1:d0+1:bx===ay?d1:d1+1}function levenshtein(a,b){if(a===b){return 0}if(a.length>b.length){var tmp=a;a=b;b=tmp}var la=a.length;var lb=b.length;while(la>0&&a.charCodeAt(la-1)===b.charCodeAt(lb-1)){la--;lb--}var offset=0;while(offsetdd?dd+1:dy$1+1:bx0$1===vector[la+y$2]?d0:d0+1;d0=dy$1}}return dd}function deprecationMessage(print,fsName,opts){if(print){console.warn("["+fsName+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+fsName+".Create("+JSON.stringify(opts)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}}var isIE=typeof navigator!=="undefined"&&!!(/(msie) ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||navigator.userAgent.indexOf("Trident")!==-1);var isWebWorker=typeof window==="undefined";function fail(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function mkdirpSync(p,mode,fs4){if(!fs4.existsSync(p)){mkdirpSync(path.dirname(p),mode,fs4);fs4.mkdirSync(p,mode)}}function buffer2ArrayBuffer(buff){var u8=buffer2Uint8array(buff),u8offset=u8.byteOffset,u8Len=u8.byteLength;if(u8offset===0&&u8Len===u8.buffer.byteLength){return u8.buffer}else{return u8.buffer.slice(u8offset,u8offset+u8Len)}}function buffer2Uint8array(buff){if(buff instanceof Uint8Array){return buff}else{return new Uint8Array(buff)}}function arrayish2Buffer(arr){if(arr instanceof Buffer2){return arr}else if(arr instanceof Uint8Array){return uint8Array2Buffer(arr)}else{return Buffer2.from(arr)}}function uint8Array2Buffer(u8){if(u8 instanceof Buffer2){return u8}else if(u8.byteOffset===0&&u8.byteLength===u8.buffer.byteLength){return arrayBuffer2Buffer(u8.buffer)}else{return Buffer2.from(u8.buffer,u8.byteOffset,u8.byteLength)}}function arrayBuffer2Buffer(ab){return Buffer2.from(ab)}function copyingSlice(buff,start,end){if(start===void 0)start=0;if(end===void 0)end=buff.length;if(start<0||end<0||end>buff.length||start>end){throw new TypeError("Invalid slice bounds on buffer of length "+buff.length+": ["+start+", "+end+"]")}if(buff.length===0){return emptyBuffer()}else{var u8=buffer2Uint8array(buff),s0=buff[0],newS0=(s0+1)%255;buff[0]=newS0;if(u8[0]===newS0){u8[0]=s0;return uint8Array2Buffer(u8.slice(start,end))}else{buff[0]=s0;return uint8Array2Buffer(u8.subarray(start,end))}}}var emptyBuff=null;function emptyBuffer(){if(emptyBuff){return emptyBuff}return emptyBuff=Buffer2.alloc(0)}function bufferValidator(v,cb){if(Buffer2.isBuffer(v)){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"option must be a Buffer."))}}function checkOptions(fsType,opts,cb){var optsInfo=fsType.Options;var fsName=fsType.Name;var pendingValidators=0;var callbackCalled=false;var loopEnded=false;function validatorCallback(e){if(!callbackCalled){if(e){callbackCalled=true;cb(e)}pendingValidators--;if(pendingValidators===0&&loopEnded){cb()}}}var loop=function(optName2){if(optsInfo.hasOwnProperty(optName2)){var opt=optsInfo[optName2];var providedValue=opts[optName2];if(providedValue===void 0||providedValue===null){if(!opt.optional){var incorrectOptions=Object.keys(opts).filter(function(o){return!(o in optsInfo)}).map(function(a){return{str:a,distance:levenshtein(optName2,a)}}).filter(function(o){return o.distance<5}).sort(function(a,b){return a.distance-b.distance});if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Required option '"+optName2+"' not provided."+(incorrectOptions.length>0?" You provided unrecognized option '"+incorrectOptions[0].str+"'; perhaps you meant to type '"+optName2+"'.":"")+"\nOption description: "+opt.description))}}}else{var typeMatches=false;if(Array.isArray(opt.type)){typeMatches=opt.type.indexOf(typeof providedValue)!==-1}else{typeMatches=typeof providedValue===opt.type}if(!typeMatches){if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Value provided for option "+optName2+" is not the proper type. Expected "+(Array.isArray(opt.type)?"one of {"+opt.type.join(", ")+"}":opt.type)+", but received "+typeof providedValue+"\nOption description: "+opt.description))}}else if(opt.validator){pendingValidators++;opt.validator(providedValue,validatorCallback)}}}};for(var optName in optsInfo){var returned=loop(optName);if(returned)return returned.v}loopEnded=true;if(pendingValidators===0&&!callbackCalled){cb()}}var BFSUtils=Object.freeze({deprecationMessage,isIE,isWebWorker,fail,mkdirpSync,buffer2ArrayBuffer,buffer2Uint8array,arrayish2Buffer,uint8Array2Buffer,arrayBuffer2Buffer,copyingSlice,emptyBuffer,bufferValidator,checkOptions});var BFSEmscriptenStreamOps=function BFSEmscriptenStreamOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenStreamOps.prototype.open=function open(stream){var path$$1=this.fs.realPath(stream.node);var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)){stream.nfd=this.nodefs.openSync(path$$1,this.fs.flagsToPermissionString(stream.flags))}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.close=function close(stream){var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)&&stream.nfd){this.nodefs.closeSync(stream.nfd)}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.read=function read(stream,buffer$$1,offset,length,position){try{return this.nodefs.readSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.write=function write(stream,buffer$$1,offset,length,position){try{return this.nodefs.writeSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.llseek=function llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(this.FS.isFile(stream.node.mode)){try{var stat=this.nodefs.fstatSync(stream.nfd);position+=stat.size}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}}if(position<0){throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL)}stream.position=position;return position};var BFSEmscriptenNodeOps=function BFSEmscriptenNodeOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenNodeOps.prototype.getattr=function getattr(node){var path$$1=this.fs.realPath(node);var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}};BFSEmscriptenNodeOps.prototype.setattr=function setattr(node,attr){var path$$1=this.fs.realPath(node);try{if(attr.mode!==void 0){this.nodefs.chmodSync(path$$1,attr.mode);node.mode=attr.mode}if(attr.timestamp!==void 0){var date=new Date(attr.timestamp);this.nodefs.utimesSync(path$$1,date,date)}}catch(e){if(!e.code){throw e}if(e.code!=="ENOTSUP"){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}if(attr.size!==void 0){try{this.nodefs.truncateSync(path$$1,attr.size)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}};BFSEmscriptenNodeOps.prototype.lookup=function lookup(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);var mode=this.fs.getMode(path$$1);return this.fs.createNode(parent,name,mode)};BFSEmscriptenNodeOps.prototype.mknod=function mknod(parent,name,mode,dev){var node=this.fs.createNode(parent,name,mode,dev);var path$$1=this.fs.realPath(node);try{if(this.FS.isDir(node.mode)){this.nodefs.mkdirSync(path$$1,node.mode)}else{this.nodefs.writeFileSync(path$$1,"",{mode:node.mode})}}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return node};BFSEmscriptenNodeOps.prototype.rename=function rename(oldNode,newDir,newName){var oldPath=this.fs.realPath(oldNode);var newPath=this.PATH.join2(this.fs.realPath(newDir),newName);try{this.nodefs.renameSync(oldPath,newPath);oldNode.name=newName;oldNode.parent=newDir}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.unlink=function unlink(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.unlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.rmdir=function rmdir(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.rmdirSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readdir=function readdir(node){var path$$1=this.fs.realPath(node);try{var contents=this.nodefs.readdirSync(path$$1);contents.push(".","..");return contents}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.symlink=function symlink(parent,newName,oldPath){var newPath=this.PATH.join2(this.fs.realPath(parent),newName);try{this.nodefs.symlinkSync(oldPath,newPath)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readlink=function readlink(node){var path$$1=this.fs.realPath(node);try{return this.nodefs.readlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};var BFSEmscriptenFS=function BFSEmscriptenFS2(_FS,_PATH,_ERRNO_CODES,nodefs){if(_FS===void 0)_FS=self["FS"];if(_PATH===void 0)_PATH=self["PATH"];if(_ERRNO_CODES===void 0)_ERRNO_CODES=self["ERRNO_CODES"];if(nodefs===void 0)nodefs=_fsMock;this.flagsToPermissionStringMap={0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"};this.nodefs=nodefs;this.FS=_FS;this.PATH=_PATH;this.ERRNO_CODES=_ERRNO_CODES;this.node_ops=new BFSEmscriptenNodeOps(this);this.stream_ops=new BFSEmscriptenStreamOps(this)};BFSEmscriptenFS.prototype.mount=function mount(m){return this.createNode(null,"/",this.getMode(m.opts.root),0)};BFSEmscriptenFS.prototype.createNode=function createNode(parent,name,mode,dev){var FS2=this.FS;if(!FS2.isDir(mode)&&!FS2.isFile(mode)&&!FS2.isLink(mode)){throw new FS2.ErrnoError(this.ERRNO_CODES.EINVAL)}var node=FS2.createNode(parent,name,mode);node.node_ops=this.node_ops;node.stream_ops=this.stream_ops;return node};BFSEmscriptenFS.prototype.getMode=function getMode(path$$1){var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return stat.mode};BFSEmscriptenFS.prototype.realPath=function realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return this.PATH.join.apply(null,parts)};BFSEmscriptenFS.prototype.flagsToPermissionString=function flagsToPermissionString(flags){var parsedFlags=typeof flags==="string"?parseInt(flags,10):flags;parsedFlags&=8191;if(parsedFlags in this.flagsToPermissionStringMap){return this.flagsToPermissionStringMap[parsedFlags]}else{return flags}};BFSEmscriptenFS.prototype.getNodeFS=function getNodeFS(){return this.nodefs};BFSEmscriptenFS.prototype.getFS=function getFS(){return this.FS};BFSEmscriptenFS.prototype.getPATH=function getPATH(){return this.PATH};BFSEmscriptenFS.prototype.getERRNO_CODES=function getERRNO_CODES(){return this.ERRNO_CODES};var BaseFileSystem=function BaseFileSystem2(){};BaseFileSystem.prototype.supportsLinks=function supportsLinks(){return false};BaseFileSystem.prototype.diskSpace=function diskSpace(p,cb){cb(0,0)};BaseFileSystem.prototype.openFile=function openFile(p,flag,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFile=function createFile(p,flag,mode,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.open=function open(p,flag,mode,cb){var this$1=this;var mustBeFile=function(e,stats){if(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.stat(path.dirname(p),false,function(e2,parentStats){if(e2){cb(e2)}else if(parentStats&&!parentStats.isDirectory()){cb(ApiError.ENOTDIR(path.dirname(p)))}else{this$1.createFile(p,flag,mode,cb)}});case ActionType.THROW_EXCEPTION:return cb(ApiError.ENOENT(p));default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}else{if(stats&&stats.isDirectory()){return cb(ApiError.EISDIR(p))}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:return cb(ApiError.EEXIST(p));case ActionType.TRUNCATE_FILE:return this$1.openFile(p,flag,function(e2,fd){if(e2){cb(e2)}else if(fd){fd.truncate(0,function(){fd.sync(function(){cb(null,fd)})})}else{fail()}});case ActionType.NOP:return this$1.openFile(p,flag,cb);default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}};this.stat(p,false,mustBeFile)};BaseFileSystem.prototype.rename=function rename(oldPath,newPath,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.renameSync=function renameSync(oldPath,newPath){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.stat=function stat(p,isLstat,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.statSync=function statSync(p,isLstat){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openFileSync=function openFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFileSync=function createFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openSync=function openSync(p,flag,mode){var stats;try{stats=this.statSync(p,false)}catch(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:var parentStats=this.statSync(path.dirname(p),false);if(!parentStats.isDirectory()){throw ApiError.ENOTDIR(path.dirname(p))}return this.createFileSync(p,flag,mode);case ActionType.THROW_EXCEPTION:throw ApiError.ENOENT(p);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}}if(stats.isDirectory()){throw ApiError.EISDIR(p)}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:throw ApiError.EEXIST(p);case ActionType.TRUNCATE_FILE:this.unlinkSync(p);return this.createFileSync(p,flag,stats.mode);case ActionType.NOP:return this.openFileSync(p,flag,mode);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}};BaseFileSystem.prototype.unlink=function unlink(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.unlinkSync=function unlinkSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.rmdir=function rmdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.rmdirSync=function rmdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.mkdir=function mkdir(p,mode,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.mkdirSync=function mkdirSync(p,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.readdir=function readdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.readdirSync=function readdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.exists=function exists2(p,cb){this.stat(p,null,function(err){cb(!err)})};BaseFileSystem.prototype.existsSync=function existsSync(p){try{this.statSync(p,true);return true}catch(e){return false}};BaseFileSystem.prototype.realpath=function realpath(p,cache,cb){if(this.supportsLinks()){var splitPath=p.split(path.sep);for(var i2=0;i2this._buffer.length){var buf=Buffer2.alloc(len-this._buffer.length,0);this.writeSync(buf,0,buf.length,this._buffer.length);if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}return}this._stat.size=len;var newBuff=Buffer2.alloc(len);this._buffer.copy(newBuff,0,0,len);this._buffer=newBuff;if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}};PreloadFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){this._dirty=true;if(position===void 0||position===null){position=this.getPos()}if(!this._flag.isWriteable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a writeable mode.")}var endFp=position+length;if(endFp>this._stat.size){this._stat.size=endFp;if(endFp>this._buffer.length){var newBuff=Buffer2.alloc(endFp);this._buffer.copy(newBuff);this._buffer=newBuff}}var len=buffer$$1.copy(this._buffer,position,offset,offset+length);this._stat.mtime=new Date;if(this._flag.isSynchronous()){this.syncSync();return len}this.setPos(position+len);return len};PreloadFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){if(!this._flag.isReadable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a readable mode.")}if(position===void 0||position===null){position=this.getPos()}var endRead=position+length;if(endRead>this._stat.size){length=this._stat.size-position}var rv=this._buffer.copy(buffer$$1,offset,position,position+length);this._stat.atime=new Date;this._pos=position+length;return rv};PreloadFile2.prototype.chmod=function chmod(mode,cb){try{this.chmodSync(mode);cb()}catch(e){cb(e)}};PreloadFile2.prototype.chmodSync=function chmodSync(mode){if(!this._fs.supportsProps()){throw new ApiError(ErrorCode.ENOTSUP)}this._dirty=true;this._stat.chmod(mode);this.syncSync()};PreloadFile2.prototype.isDirty=function isDirty(){return this._dirty};PreloadFile2.prototype.resetDirty=function resetDirty(){this._dirty=false};return PreloadFile2}(BaseFile);var NoSyncFile=function(PreloadFile2){function NoSyncFile2(_fs,_path,_flag,_stat,contents){PreloadFile2.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile2)NoSyncFile2.__proto__=PreloadFile2;NoSyncFile2.prototype=Object.create(PreloadFile2&&PreloadFile2.prototype);NoSyncFile2.prototype.constructor=NoSyncFile2;NoSyncFile2.prototype.sync=function sync(cb){cb()};NoSyncFile2.prototype.syncSync=function syncSync(){};NoSyncFile2.prototype.close=function close(cb){cb()};NoSyncFile2.prototype.closeSync=function closeSync(){};return NoSyncFile2}(PreloadFile);var MirrorFile=function(PreloadFile$$1){function MirrorFile2(fs4,path$$1,flag,stat,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,data)}if(PreloadFile$$1)MirrorFile2.__proto__=PreloadFile$$1;MirrorFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);MirrorFile2.prototype.constructor=MirrorFile2;MirrorFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};MirrorFile2.prototype.closeSync=function closeSync(){this.syncSync()};return MirrorFile2}(PreloadFile);var AsyncMirror=function(SynchronousFileSystem$$1){function AsyncMirror2(sync,async,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this._queue=[];this._queueRunning=false;this._isInitialized=false;this._initializeCallbacks=[];this._sync=sync;this._async=async;if(!sync.supportsSynch()){throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.")}deprecationMessage(deprecateMsg,AsyncMirror2.Name,{sync:"sync file system instance",async:"async file system instance"})}if(SynchronousFileSystem$$1)AsyncMirror2.__proto__=SynchronousFileSystem$$1;AsyncMirror2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);AsyncMirror2.prototype.constructor=AsyncMirror2;AsyncMirror2.Create=function Create(opts,cb){try{var fs4=new AsyncMirror2(opts.sync,opts.async,false);fs4.initialize(function(e){if(e){cb(e)}else{cb(null,fs4)}},false)}catch(e){cb(e)}};AsyncMirror2.isAvailable=function isAvailable(){return true};AsyncMirror2.prototype.getName=function getName(){return AsyncMirror2.Name};AsyncMirror2.prototype._syncSync=function _syncSync(fd){this._sync.writeFileSync(fd.getPath(),fd.getBuffer(),null,FileFlag.getFileFlag("w"),fd.getStats().mode);this.enqueueOp({apiMethod:"writeFile",arguments:[fd.getPath(),fd.getBuffer(),null,fd.getFlag(),fd.getStats().mode]})};AsyncMirror2.prototype.initialize=function initialize3(userCb,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.")}var callbacks=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbacks.forEach(function(cb){return cb(e)})};if(!this._isInitialized){if(callbacks.push(userCb)===1){var copyDirectory=function(p,mode,cb){if(p!=="/"){this$1._sync.mkdirSync(p,mode)}this$1._async.readdir(p,function(err,files){var i2=0;function copyNextFile(err2){if(err2){cb(err2)}else if(i20){var op2=this$1._queue.shift(),args=op2.arguments;args.push(doNextOp);this$1._async[op2.apiMethod].apply(this$1._async,args)}else{this$1._queueRunning=false}};doNextOp()}};return AsyncMirror2}(SynchronousFileSystem);AsyncMirror.Name="AsyncMirror";AsyncMirror.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var nativeMax=Math.max;function overRest$1(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}var breakLoop={};function noop(){}function once(fn){return function(){if(fn===null){return}var callFn=fn;fn=null;callFn.apply(this,arguments)}}var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index-1&&value%1==0&&value++numRun){switch(error.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){performOp(interceptCb)},timeoutDuration*1e3);break;default:cb.apply(null,arguments);break}}else{cb.apply(null,arguments)}};performOp(interceptCb)};CachedDropboxClient.prototype.getCachedInfo=function getCachedInfo(p){return this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.putCachedInfo=function putCachedInfo(p,cache){this._cache[p.toLowerCase()]=cache};CachedDropboxClient.prototype.deleteCachedInfo=function deleteCachedInfo(p){delete this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.getCachedDirInfo=function getCachedDirInfo(p){var info=this.getCachedInfo(p);if(isDirInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.getCachedFileInfo=function getCachedFileInfo(p){var info=this.getCachedInfo(p);if(isFileInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.updateCachedDirInfo=function updateCachedDirInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.contentHash!==null&&(cachedInfo===void 0||cachedInfo.stat.contentHash!==stat.contentHash)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedFileInfo=function updateCachedFileInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.versionTag!==null&&(cachedInfo===void 0||cachedInfo.stat.versionTag!==stat.versionTag)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedInfo=function updateCachedInfo(p,stat,contents){if(contents===void 0)contents=null;if(stat.isFile&&isArrayBuffer(contents)){this.updateCachedFileInfo(p,stat,contents)}else if(stat.isFolder&&Array.isArray(contents)){this.updateCachedDirInfo(p,stat,contents)}};var DropboxFile=function(PreloadFile$$1){function DropboxFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)DropboxFile2.__proto__=PreloadFile$$1;DropboxFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);DropboxFile2.prototype.constructor=DropboxFile2;DropboxFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){var buffer$$1=this.getBuffer(),arrayBuffer=buffer2ArrayBuffer(buffer$$1);this._fs._writeFileStrict(this.getPath(),arrayBuffer,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};DropboxFile2.prototype.close=function close(cb){this.sync(cb)};return DropboxFile2}(PreloadFile);var DropboxFileSystem=function(BaseFileSystem$$1){function DropboxFileSystem2(client,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._client=new CachedDropboxClient(client);deprecationMessage(deprecateMsg,DropboxFileSystem2.Name,{client:"authenticated dropbox client instance"});constructErrorCodeLookup()}if(BaseFileSystem$$1)DropboxFileSystem2.__proto__=BaseFileSystem$$1;DropboxFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);DropboxFileSystem2.prototype.constructor=DropboxFileSystem2;DropboxFileSystem2.Create=function Create(opts,cb){cb(null,new DropboxFileSystem2(opts.client,false))};DropboxFileSystem2.isAvailable=function isAvailable(){return typeof Dropbox!=="undefined"};DropboxFileSystem2.prototype.getName=function getName(){return DropboxFileSystem2.Name};DropboxFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};DropboxFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};DropboxFileSystem2.prototype.supportsProps=function supportsProps(){return false};DropboxFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};DropboxFileSystem2.prototype.empty=function empty(mainCb){var this$1=this;this._client.readdir("/",function(error,files){if(error){mainCb(this$1.convert(error,"/"))}else{var deleteFile2=function(file,cb){var p=path.join("/",file);this$1._client.remove(p,function(err){cb(err?this$1.convert(err,p):null)})};var finished=function(err){if(err){mainCb(err)}else{mainCb()}};eachLimit(files,deleteFile2,finished)}})};DropboxFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._client.move(oldPath,newPath,function(error){if(error){this$1._client.stat(newPath,function(error2,stat){if(error2||stat.isFolder){var missingPath=error.response.error.indexOf(oldPath)>-1?oldPath:newPath;cb(this$1.convert(error,missingPath))}else{this$1._client.remove(newPath,function(error22){if(error22){cb(this$1.convert(error22,newPath))}else{this$1.rename(oldPath,newPath,cb)}})}})}else{cb()}})};DropboxFileSystem2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;this._client.stat(path$$1,function(error,stat2){if(error){cb(this$1.convert(error,path$$1))}else if(stat2&&stat2.isRemoved){cb(ApiError.FileError(ErrorCode.ENOENT,path$$1))}else{var stats=new Stats(this$1._statType(stat2),stat2.size);return cb(null,stats)}})};DropboxFileSystem2.prototype.open=function open(path$$1,flags,mode,cb){var this$1=this;this._client.readFile(path$$1,function(error,content,dbStat){if(error){if(flags.isReadable()){cb(this$1.convert(error,path$$1))}else{switch(error.status){case Dropbox.ApiError.NOT_FOUND:var ab=new ArrayBuffer(0);return this$1._writeFileStrict(path$$1,ab,function(error2,stat){if(error2){cb(error2)}else{var file2=this$1._makeFile(path$$1,flags,stat,arrayBuffer2Buffer(ab));cb(null,file2)}});default:return cb(this$1.convert(error,path$$1))}}}else{var buffer$$1;if(content===null){buffer$$1=emptyBuffer()}else{buffer$$1=arrayBuffer2Buffer(content)}var file=this$1._makeFile(path$$1,flags,dbStat,buffer$$1);return cb(null,file)}})};DropboxFileSystem2.prototype._writeFileStrict=function _writeFileStrict(p,data,cb){var this$1=this;var parent=path.dirname(p);this.stat(parent,false,function(error,stat){if(error){cb(ApiError.FileError(ErrorCode.ENOENT,parent))}else{this$1._client.writeFile(p,data,function(error2,stat2){if(error2){cb(this$1.convert(error2,p))}else{cb(null,stat2)}})}})};DropboxFileSystem2.prototype._statType=function _statType(stat){return stat.isFile?FileType.FILE:FileType.DIRECTORY};DropboxFileSystem2.prototype._makeFile=function _makeFile(path$$1,flag,stat,buffer$$1){var type=this._statType(stat);var stats=new Stats(type,stat.size);return new DropboxFile(this,path$$1,flag,stats,buffer$$1)};DropboxFileSystem2.prototype._remove=function _remove(path$$1,cb,isFile){var this$1=this;this._client.stat(path$$1,function(error,stat){if(error){cb(this$1.convert(error,path$$1))}else{if(stat.isFile&&!isFile){cb(ApiError.FileError(ErrorCode.ENOTDIR,path$$1))}else if(!stat.isFile&&isFile){cb(ApiError.FileError(ErrorCode.EISDIR,path$$1))}else{this$1._client.remove(path$$1,function(error2){if(error2){cb(this$1.convert(error2,path$$1))}else{cb(null)}})}}})};DropboxFileSystem2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};DropboxFileSystem2.prototype.rmdir=function rmdir(path$$1,cb){this._remove(path$$1,cb,false)};DropboxFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;var parent=path.dirname(p);this._client.stat(parent,function(error,stat){if(error){cb(this$1.convert(error,parent))}else{this$1._client.mkdir(p,function(error2){if(error2){cb(ApiError.FileError(ErrorCode.EEXIST,p))}else{cb(null)}})}})};DropboxFileSystem2.prototype.readdir=function readdir(path$$1,cb){var this$1=this;this._client.readdir(path$$1,function(error,files){if(error){return cb(this$1.convert(error))}else{return cb(null,files)}})};DropboxFileSystem2.prototype.convert=function convert(err,path$$1){if(path$$1===void 0)path$$1=null;var errorCode=errorCodeLookup[err.status];if(errorCode===void 0){errorCode=ErrorCode.EIO}if(!path$$1){return new ApiError(errorCode)}else{return ApiError.FileError(errorCode,path$$1)}};return DropboxFileSystem2}(BaseFileSystem);DropboxFileSystem.Name="Dropbox";DropboxFileSystem.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(opt,cb){if(opt.isAuthenticated&&opt.isAuthenticated()){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}}};function convertError(e,path$$1){if(path$$1===void 0)path$$1="";var errno=e.errno;var parent=e.node;var paths=[];while(parent){paths.unshift(parent.name);if(parent===parent.parent){break}parent=parent.parent}return new ApiError(errno,ErrorStrings[errno],paths.length>0?"/"+paths.join("/"):path$$1)}var EmscriptenFile=function(BaseFile$$1){function EmscriptenFile2(_fs,_FS,_path,_stream){BaseFile$$1.call(this);this._fs=_fs;this._FS=_FS;this._path=_path;this._stream=_stream}if(BaseFile$$1)EmscriptenFile2.__proto__=BaseFile$$1;EmscriptenFile2.prototype=Object.create(BaseFile$$1&&BaseFile$$1.prototype);EmscriptenFile2.prototype.constructor=EmscriptenFile2;EmscriptenFile2.prototype.getPos=function getPos(){return void 0};EmscriptenFile2.prototype.close=function close(cb){var err=null;try{this.closeSync()}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.closeSync=function closeSync(){try{this._FS.close(this._stream)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.stat=function stat(cb){try{cb(null,this.statSync())}catch(e){cb(e)}};EmscriptenFile2.prototype.statSync=function statSync(){try{return this._fs.statSync(this._path,false)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.truncate=function truncate(len,cb){var err=null;try{this.truncateSync(len)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.truncateSync=function truncateSync(len){try{this._FS.ftruncate(this._stream.fd,len)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.write(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.read(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.sync=function sync(cb){cb()};EmscriptenFile2.prototype.syncSync=function syncSync(){};EmscriptenFile2.prototype.chown=function chown(uid,gid,cb){var err=null;try{this.chownSync(uid,gid)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chownSync=function chownSync(uid,gid){try{this._FS.fchown(this._stream.fd,uid,gid)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.chmod=function chmod(mode,cb){var err=null;try{this.chmodSync(mode)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chmodSync=function chmodSync(mode){try{this._FS.fchmod(this._stream.fd,mode)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.utimes=function utimes(atime,mtime,cb){var err=null;try{this.utimesSync(atime,mtime)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.utimesSync=function utimesSync(atime,mtime){this._fs.utimesSync(this._path,atime,mtime)};return EmscriptenFile2}(BaseFile);var EmscriptenFileSystem=function(SynchronousFileSystem$$1){function EmscriptenFileSystem2(_FS){SynchronousFileSystem$$1.call(this);this._FS=_FS}if(SynchronousFileSystem$$1)EmscriptenFileSystem2.__proto__=SynchronousFileSystem$$1;EmscriptenFileSystem2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);EmscriptenFileSystem2.prototype.constructor=EmscriptenFileSystem2;EmscriptenFileSystem2.Create=function Create(opts,cb){cb(null,new EmscriptenFileSystem2(opts.FS))};EmscriptenFileSystem2.isAvailable=function isAvailable(){return true};EmscriptenFileSystem2.prototype.getName=function getName(){return this._FS.DB_NAME()};EmscriptenFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};EmscriptenFileSystem2.prototype.supportsLinks=function supportsLinks(){return true};EmscriptenFileSystem2.prototype.supportsProps=function supportsProps(){return true};EmscriptenFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};EmscriptenFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){try{this._FS.rename(oldPath,newPath)}catch(e){if(e.errno===ErrorCode.ENOENT){throw convertError(e,this.existsSync(oldPath)?newPath:oldPath)}else{throw convertError(e)}}};EmscriptenFileSystem2.prototype.statSync=function statSync(p,isLstat){try{var stats=isLstat?this._FS.lstat(p):this._FS.stat(p);var itemType=this.modeToFileType(stats.mode);return new Stats(itemType,stats.size,stats.mode,stats.atime,stats.mtime,stats.ctime)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.openSync=function openSync(p,flag,mode){try{var stream=this._FS.open(p,flag.getFlagString(),mode);if(this._FS.isDir(stream.node.mode)){this._FS.close(stream);throw ApiError.EISDIR(p)}return new EmscriptenFile(this,this._FS,p,stream)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.unlinkSync=function unlinkSync(p){try{this._FS.unlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.rmdirSync=function rmdirSync(p){try{this._FS.rmdir(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){try{this._FS.mkdir(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readdirSync=function readdirSync(p){try{return this._FS.readdir(p).filter(function(p2){return p2!=="."&&p2!==".."})}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.truncateSync=function truncateSync(p,len){try{this._FS.truncate(p,len)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readFileSync=function readFileSync(p,encoding,flag){try{var data=this._FS.readFile(p,{flags:flag.getFlagString()});var buff=uint8Array2Buffer(data);if(encoding){return buff.toString(encoding)}else{return buff}}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.writeFileSync=function writeFileSync(p,data,encoding,flag,mode){try{if(encoding){data=Buffer2.from(data,encoding)}var u8=buffer2Uint8array(data);this._FS.writeFile(p,u8,{flags:flag.getFlagString(),encoding:"binary"});this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){try{isLchmod?this._FS.lchmod(p,mode):this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){try{isLchown?this._FS.lchown(p,uid,gid):this._FS.chown(p,uid,gid)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){try{this._FS.symlink(srcpath,dstpath)}catch(e){throw convertError(e)}};EmscriptenFileSystem2.prototype.readlinkSync=function readlinkSync(p){try{return this._FS.readlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.utimesSync=function utimesSync(p,atime,mtime){try{this._FS.utime(p,atime.getTime(),mtime.getTime())}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.modeToFileType=function modeToFileType(mode){if(this._FS.isDir(mode)){return FileType.DIRECTORY}else if(this._FS.isFile(mode)){return FileType.FILE}else if(this._FS.isLink(mode)){return FileType.SYMLINK}else{throw ApiError.EPERM("Invalid mode: "+mode)}};return EmscriptenFileSystem2}(SynchronousFileSystem);EmscriptenFileSystem.Name="EmscriptenFileSystem";EmscriptenFileSystem.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var FolderAdapter=function(BaseFileSystem$$1){function FolderAdapter2(folder,wrapped){BaseFileSystem$$1.call(this);this._folder=folder;this._wrapped=wrapped}if(BaseFileSystem$$1)FolderAdapter2.__proto__=BaseFileSystem$$1;FolderAdapter2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);FolderAdapter2.prototype.constructor=FolderAdapter2;FolderAdapter2.Create=function Create(opts,cb){cb(null,new FolderAdapter2(opts.folder,opts.wrapped))};FolderAdapter2.isAvailable=function isAvailable(){return true};FolderAdapter2.prototype.initialize=function initialize3(cb){var this$1=this;this._wrapped.exists(this._folder,function(exists2){if(exists2){cb()}else if(this$1._wrapped.isReadOnly()){cb(ApiError.ENOENT(this$1._folder))}else{this$1._wrapped.mkdir(this$1._folder,511,cb)}})};FolderAdapter2.prototype.getName=function getName(){return this._wrapped.getName()};FolderAdapter2.prototype.isReadOnly=function isReadOnly(){return this._wrapped.isReadOnly()};FolderAdapter2.prototype.supportsProps=function supportsProps(){return this._wrapped.supportsProps()};FolderAdapter2.prototype.supportsSynch=function supportsSynch(){return this._wrapped.supportsSynch()};FolderAdapter2.prototype.supportsLinks=function supportsLinks(){return false};return FolderAdapter2}(BaseFileSystem);FolderAdapter.Name="FolderAdapter";FolderAdapter.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}};function translateError(folder,e){if(e!==null&&typeof e==="object"){var err=e;var p=err.path;if(p){p="/"+path.relative(folder,p);err.message=err.message.replace(err.path,p);err.path=p}}return e}function wrapCallback(folder,cb){if(typeof cb==="function"){return function(err){if(arguments.length>0){arguments[0]=translateError(folder,err)}cb.apply(null,arguments)}}else{return cb}}function wrapFunction(name,wrapFirst,wrapSecond){if(name.slice(name.length-4)!=="Sync"){return function(){if(arguments.length>0){if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}arguments[arguments.length-1]=wrapCallback(this._folder,arguments[arguments.length-1])}return this._wrapped[name].apply(this._wrapped,arguments)}}else{return function(){try{if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}return this._wrapped[name].apply(this._wrapped,arguments)}catch(e){throw translateError(this._folder,e)}}}}["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,false)});["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,true)});var toExport;if(typeof window!=="undefined"){toExport=window}else if(typeof self!=="undefined"){toExport=self}else{toExport=global}var global$1=toExport;function isDirectoryEntry(entry){return entry.isDirectory}var _getFS=global$1.webkitRequestFileSystem||global$1.requestFileSystem||null;function _requestQuota(type,size,success,errorCallback){if(typeof navigator["webkitPersistentStorage"]!=="undefined"){switch(type){case global$1.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(size,success,errorCallback);break;case global$1.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(size,success,errorCallback);break;default:errorCallback(new TypeError("Invalid storage type: "+type));break}}else{global$1.webkitStorageInfo.requestQuota(type,size,success,errorCallback)}}function _toArray(list2){return Array.prototype.slice.call(list2||[],0)}function convertError$1(err,p,expectedDir){switch(err.name){case"PathExistsError":return ApiError.EEXIST(p);case"QuotaExceededError":return ApiError.FileError(ErrorCode.ENOSPC,p);case"NotFoundError":return ApiError.ENOENT(p);case"SecurityError":return ApiError.FileError(ErrorCode.EACCES,p);case"InvalidModificationError":return ApiError.FileError(ErrorCode.EPERM,p);case"TypeMismatchError":return ApiError.FileError(expectedDir?ErrorCode.ENOTDIR:ErrorCode.EISDIR,p);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return ApiError.FileError(ErrorCode.EINVAL,p)}}var HTML5FSFile=function(PreloadFile$$1){function HTML5FSFile2(fs4,entry,path$$1,flag,stat,contents){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,contents);this._entry=entry}if(PreloadFile$$1)HTML5FSFile2.__proto__=PreloadFile$$1;HTML5FSFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);HTML5FSFile2.prototype.constructor=HTML5FSFile2;HTML5FSFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){return cb()}this._entry.createWriter(function(writer){var buffer$$1=this$1.getBuffer();var blob=new Blob([buffer2ArrayBuffer(buffer$$1)]);var length=blob.size;writer.onwriteend=function(err){writer.onwriteend=null;writer.onerror=null;writer.truncate(length);this$1.resetDirty();cb()};writer.onerror=function(err){cb(convertError$1(err,this$1.getPath(),false))};writer.write(blob)})};HTML5FSFile2.prototype.close=function close(cb){this.sync(cb)};return HTML5FSFile2}(PreloadFile);var HTML5FS=function(BaseFileSystem$$1){function HTML5FS2(size,type,deprecateMsg){if(size===void 0)size=5;if(type===void 0)type=global$1.PERSISTENT;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this.size=1024*1024*size;this.type=type;deprecationMessage(deprecateMsg,HTML5FS2.Name,{size,type})}if(BaseFileSystem$$1)HTML5FS2.__proto__=BaseFileSystem$$1;HTML5FS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);HTML5FS2.prototype.constructor=HTML5FS2;HTML5FS2.Create=function Create(opts,cb){var fs4=new HTML5FS2(opts.size,opts.type,false);fs4.allocate(function(e){return e?cb(e):cb(null,fs4)},false)};HTML5FS2.isAvailable=function isAvailable(){return!!_getFS};HTML5FS2.prototype.getName=function getName(){return HTML5FS2.Name};HTML5FS2.prototype.isReadOnly=function isReadOnly(){return false};HTML5FS2.prototype.supportsSymlinks=function supportsSymlinks(){return false};HTML5FS2.prototype.supportsProps=function supportsProps(){return false};HTML5FS2.prototype.supportsSynch=function supportsSynch(){return false};HTML5FS2.prototype.allocate=function allocate(cb,deprecateMsg){var this$1=this;if(cb===void 0)cb=function(){};if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.")}var success=function(fs4){this$1.fs=fs4;cb()};var error=function(err){cb(convertError$1(err,"/",true))};if(this.type===global$1.PERSISTENT){_requestQuota(this.type,this.size,function(granted){_getFS(this$1.type,granted,success,error)},error)}else{_getFS(this.type,this.size,success,error)}};HTML5FS2.prototype.empty=function empty(mainCb){this._readdir("/",function(err,entries){if(err){console.error("Failed to empty FS");mainCb(err)}else{var finished=function(er){if(err){console.error("Failed to empty FS");mainCb(err)}else{mainCb()}};var deleteEntry=function(entry,cb){var succ=function(){cb()};var error=function(err2){cb(convertError$1(err2,entry.fullPath,!entry.isDirectory))};if(isDirectoryEntry(entry)){entry.removeRecursively(succ,error)}else{entry.remove(succ,error)}};eachLimit(entries,deleteEntry,finished)}})};HTML5FS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var semaphore=2;var successCount=0;var root2=this.fs.root;var currentPath=oldPath;var error=function(err){if(--semaphore<=0){cb(convertError$1(err,currentPath,false))}};var success=function(file){if(++successCount===2){return cb(new ApiError(ErrorCode.EINVAL,"Something was identified as both a file and a directory. This should never happen."))}if(oldPath===newPath){return cb()}currentPath=path.dirname(newPath);root2.getDirectory(currentPath,{},function(parentDir){currentPath=path.basename(newPath);file.moveTo(parentDir,currentPath,function(entry){cb()},function(err){if(file.isDirectory){currentPath=newPath;this$1.unlink(newPath,function(e){if(e){error(err)}else{this$1.rename(oldPath,newPath,cb)}})}else{error(err)}})},error)};root2.getFile(oldPath,{},success,error);root2.getDirectory(oldPath,{},success,error)};HTML5FS2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;var opts={create:false};var loadAsFile=function(entry){var fileFromEntry=function(file){var stat2=new Stats(FileType.FILE,file.size);cb(null,stat2)};entry.file(fileFromEntry,failedToLoad)};var loadAsDir=function(dir$$1){var size=4096;var stat2=new Stats(FileType.DIRECTORY,size);cb(null,stat2)};var failedToLoad=function(err){cb(convertError$1(err,path$$1,false))};var failedToLoadAsFile=function(){this$1.fs.root.getDirectory(path$$1,opts,loadAsDir,failedToLoad)};this.fs.root.getFile(path$$1,opts,loadAsFile,failedToLoadAsFile)};HTML5FS2.prototype.open=function open(p,flags,mode,cb){var this$1=this;var error=function(err){if(err.name==="InvalidModificationError"&&flags.isExclusive()){cb(ApiError.EEXIST(p))}else{cb(convertError$1(err,p,false))}};this.fs.root.getFile(p,{create:flags.pathNotExistsAction()===ActionType.CREATE_FILE,exclusive:flags.isExclusive()},function(entry){entry.file(function(file){var reader=new FileReader;reader.onloadend=function(event){var bfsFile=this$1._makeFile(p,entry,flags,file,reader.result);cb(null,bfsFile)};reader.onerror=function(ev){error(reader.error)};reader.readAsArrayBuffer(file)},error)},error)};HTML5FS2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};HTML5FS2.prototype.rmdir=function rmdir(path$$1,cb){var this$1=this;this.readdir(path$$1,function(e,files){if(e){cb(e)}else if(files.length>0){cb(ApiError.ENOTEMPTY(path$$1))}else{this$1._remove(path$$1,cb,false)}})};HTML5FS2.prototype.mkdir=function mkdir(path$$1,mode,cb){var opts={create:true,exclusive:true};var success=function(dir$$1){cb()};var error=function(err){cb(convertError$1(err,path$$1,true))};this.fs.root.getDirectory(path$$1,opts,success,error)};HTML5FS2.prototype.readdir=function readdir(path$$1,cb){this._readdir(path$$1,function(e,entries){if(entries){var rv=[];for(var i2=0,list2=entries;i20){throw ApiError.ENOTEMPTY(p)}else{this.removeEntry(p,true)}};SyncKeyValueFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data)};SyncKeyValueFileSystem2.prototype.readdirSync=function readdirSync(p){var tx=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(tx,p,this.findINode(tx,p)))};SyncKeyValueFileSystem2.prototype._syncSync=function _syncSync(p,data,stats){var tx=this.store.beginTransaction("readwrite"),fileInodeId=this._findINode(tx,path.dirname(p),path.basename(p)),fileInode=this.getINode(tx,p,fileInodeId),inodeChanged=fileInode.update(stats);try{tx.put(fileInode.id,data,true);if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true)}}catch(e){tx.abort();throw e}tx.commit()};SyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(){var tx=this.store.beginTransaction("readwrite");if(tx.get(ROOT_NODE_ID)===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false);tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false);tx.commit()}};SyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename){var this$1=this;var readDirectory=function(inode){var dirList=this$1.getDirListing(tx,parent,inode);if(dirList[filename]){return dirList[filename]}else{throw ApiError.ENOENT(path.resolve(parent,filename))}};if(parent==="/"){if(filename===""){return ROOT_NODE_ID}else{return readDirectory(this.getINode(tx,parent,ROOT_NODE_ID))}}else{return readDirectory(this.getINode(tx,parent+path.sep+filename,this._findINode(tx,path.dirname(parent),path.basename(parent))))}};SyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p){return this.getINode(tx,p,this._findINode(tx,path.dirname(p),path.basename(p)))};SyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id){var inode=tx.get(id);if(inode===void 0){throw ApiError.ENOENT(p)}return Inode.fromBuffer(inode)};SyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode){if(!inode.isDirectory()){throw ApiError.ENOTDIR(p)}var data=tx.get(inode.id);if(data===void 0){throw ApiError.ENOENT(p)}return JSON.parse(data.toString())};SyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data){var retries=0;var currId;while(retries<5){try{currId=GenerateRandomID();tx.put(currId,data,false);return currId}catch(e){}}throw new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store.")};SyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data){var parentDir=path.dirname(p),fname=path.basename(p),parentNode=this.findINode(tx,parentDir),dirListing=this.getDirListing(tx,parentDir,parentNode),currTime=new Date().getTime();if(p==="/"){throw ApiError.EEXIST(p)}if(dirListing[fname]){throw ApiError.EEXIST(p)}var fileNode;try{var dataId=this.addNewNode(tx,data);fileNode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);var fileNodeId=this.addNewNode(tx,fileNode.toBuffer());dirListing[fname]=fileNodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true)}catch(e){tx.abort();throw e}tx.commit();return fileNode};SyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir){var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),parentNode=this.findINode(tx,parent),parentListing=this.getDirListing(tx,parent,parentNode),fileName=path.basename(p);if(!parentListing[fileName]){throw ApiError.ENOENT(p)}var fileNodeId=parentListing[fileName];delete parentListing[fileName];var fileNode=this.getINode(tx,p,fileNodeId);if(!isDir&&fileNode.isDirectory()){throw ApiError.EISDIR(p)}else if(isDir&&!fileNode.isDirectory()){throw ApiError.ENOTDIR(p)}try{tx.del(fileNode.id);tx.del(fileNodeId);tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true)}catch(e){tx.abort();throw e}tx.commit()};return SyncKeyValueFileSystem2}(SynchronousFileSystem);var AsyncKeyValueFile=function(PreloadFile$$1){function AsyncKeyValueFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)AsyncKeyValueFile2.__proto__=PreloadFile$$1;AsyncKeyValueFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);AsyncKeyValueFile2.prototype.constructor=AsyncKeyValueFile2;AsyncKeyValueFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};AsyncKeyValueFile2.prototype.close=function close(cb){this.sync(cb)};return AsyncKeyValueFile2}(PreloadFile);var AsyncKeyValueFileSystem=function(BaseFileSystem$$1){function AsyncKeyValueFileSystem2(){BaseFileSystem$$1.apply(this,arguments)}if(BaseFileSystem$$1)AsyncKeyValueFileSystem2.__proto__=BaseFileSystem$$1;AsyncKeyValueFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);AsyncKeyValueFileSystem2.prototype.constructor=AsyncKeyValueFileSystem2;AsyncKeyValueFileSystem2.isAvailable=function isAvailable(){return true};AsyncKeyValueFileSystem2.prototype.init=function init(store,cb){this.store=store;this.makeRootDirectory(cb)};AsyncKeyValueFileSystem2.prototype.getName=function getName(){return this.store.name()};AsyncKeyValueFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};AsyncKeyValueFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};AsyncKeyValueFileSystem2.prototype.supportsProps=function supportsProps(){return false};AsyncKeyValueFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};AsyncKeyValueFileSystem2.prototype.empty=function empty(cb){var this$1=this;this.store.clear(function(e){if(noError(e,cb)){this$1.makeRootDirectory(cb)}})};AsyncKeyValueFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");var oldParent=path.dirname(oldPath),oldName=path.basename(oldPath);var newParent=path.dirname(newPath),newName=path.basename(newPath);var inodes={};var lists={};var errorOccurred=false;if((newParent+"/").indexOf(oldPath+"/")===0){return cb(new ApiError(ErrorCode.EBUSY,oldParent))}var theOleSwitcharoo=function(){if(errorOccurred||!lists.hasOwnProperty(oldParent)||!lists.hasOwnProperty(newParent)){return}var oldParentList=lists[oldParent],oldParentINode=inodes[oldParent],newParentList=lists[newParent],newParentINode=inodes[newParent];if(!oldParentList[oldName]){cb(ApiError.ENOENT(oldPath))}else{var fileId=oldParentList[oldName];delete oldParentList[oldName];var completeRename=function(){newParentList[newName]=fileId;tx.put(oldParentINode.id,Buffer2.from(JSON.stringify(oldParentList)),true,function(e){if(noErrorTx(e,tx,cb)){if(oldParent===newParent){tx.commit(cb)}else{tx.put(newParentINode.id,Buffer2.from(JSON.stringify(newParentList)),true,function(e2){if(noErrorTx(e2,tx,cb)){tx.commit(cb)}})}}})};if(newParentList[newName]){this$1.getINode(tx,newPath,newParentList[newName],function(e,inode){if(noErrorTx(e,tx,cb)){if(inode.isFile()){tx.del(inode.id,function(e2){if(noErrorTx(e2,tx,cb)){tx.del(newParentList[newName],function(e3){if(noErrorTx(e3,tx,cb)){completeRename()}})}})}else{tx.abort(function(e2){cb(ApiError.EPERM(newPath))})}}})}else{completeRename()}}};var processInodeAndListings=function(p){this$1.findINodeAndDirListing(tx,p,function(e,node,dirList){if(e){if(!errorOccurred){errorOccurred=true;tx.abort(function(){cb(e)})}}else{inodes[p]=node;lists[p]=dirList;theOleSwitcharoo()}})};processInodeAndListings(oldParent);if(oldParent!==newParent){processInodeAndListings(newParent)}};AsyncKeyValueFileSystem2.prototype.stat=function stat(p,isLstat,cb){var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){cb(null,inode.toStats())}})};AsyncKeyValueFileSystem2.prototype.createFile=function createFile(p,flag,mode,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),data=emptyBuffer();this.commitNewFile(tx,p,FileType.FILE,mode,data,function(e,newFile){if(noError(e,cb)){cb(null,new AsyncKeyValueFile(this$1,p,flag,newFile.toStats(),data))}})};AsyncKeyValueFileSystem2.prototype.openFile=function openFile(p,flag,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){tx.get(inode.id,function(e2,data){if(noError(e2,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,new AsyncKeyValueFile(this$1,p,flag,inode.toStats(),data))}}})}})};AsyncKeyValueFileSystem2.prototype.unlink=function unlink(p,cb){this.removeEntry(p,false,cb)};AsyncKeyValueFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;this.readdir(p,function(err,files){if(err){cb(err)}else if(files.length>0){cb(ApiError.ENOTEMPTY(p))}else{this$1.removeEntry(p,true,cb)}})};AsyncKeyValueFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data,cb)};AsyncKeyValueFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,dirListing){if(noError(e2,cb)){cb(null,Object.keys(dirListing))}})}})};AsyncKeyValueFileSystem2.prototype._sync=function _sync(p,data,stats,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");this._findINode(tx,path.dirname(p),path.basename(p),function(e,fileInodeId){if(noErrorTx(e,tx,cb)){this$1.getINode(tx,p,fileInodeId,function(e2,fileInode){if(noErrorTx(e2,tx,cb)){var inodeChanged=fileInode.update(stats);tx.put(fileInode.id,data,true,function(e3){if(noErrorTx(e3,tx,cb)){if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(cb)}})}else{tx.commit(cb)}}})}})}})};AsyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(cb){var tx=this.store.beginTransaction("readwrite");tx.get(ROOT_NODE_ID,function(e,data){if(e||data===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false,function(e2){if(noErrorTx(e2,tx,cb)){tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false,function(e3){if(e3){tx.abort(function(){cb(e3)})}else{tx.commit(cb)}})}})}else{tx.commit(cb)}})};AsyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename,cb){var this$1=this;var handleDirectoryListings=function(e,inode,dirList){if(e){cb(e)}else if(dirList[filename]){cb(null,dirList[filename])}else{cb(ApiError.ENOENT(path.resolve(parent,filename)))}};if(parent==="/"){if(filename===""){cb(null,ROOT_NODE_ID)}else{this.getINode(tx,parent,ROOT_NODE_ID,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,parent,inode,function(e2,dirList){handleDirectoryListings(e2,inode,dirList)})}})}}else{this.findINodeAndDirListing(tx,parent,handleDirectoryListings)}};AsyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p,cb){var this$1=this;this._findINode(tx,path.dirname(p),path.basename(p),function(e,id){if(noError(e,cb)){this$1.getINode(tx,p,id,cb)}})};AsyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id,cb){tx.get(id,function(e,data){if(noError(e,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,Inode.fromBuffer(data))}}})};AsyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode,cb){if(!inode.isDirectory()){cb(ApiError.ENOTDIR(p))}else{tx.get(inode.id,function(e,data){if(noError(e,cb)){try{cb(null,JSON.parse(data.toString()))}catch(e2){cb(ApiError.ENOENT(p))}}})}};AsyncKeyValueFileSystem2.prototype.findINodeAndDirListing=function findINodeAndDirListing(tx,p,cb){var this$1=this;this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,listing){if(noError(e2,cb)){cb(null,inode,listing)}})}})};AsyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data,cb){var retries=0,currId;var reroll=function(){if(++retries===5){cb(new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store."))}else{currId=GenerateRandomID();tx.put(currId,data,false,function(e,committed){if(e||!committed){reroll()}else{cb(null,currId)}})}};reroll()};AsyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data,cb){var this$1=this;var parentDir=path.dirname(p),fname=path.basename(p),currTime=new Date().getTime();if(p==="/"){return cb(ApiError.EEXIST(p))}this.findINodeAndDirListing(tx,parentDir,function(e,parentNode,dirListing){if(noErrorTx(e,tx,cb)){if(dirListing[fname]){tx.abort(function(){cb(ApiError.EEXIST(p))})}else{this$1.addNewNode(tx,data,function(e2,dataId){if(noErrorTx(e2,tx,cb)){var fileInode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);this$1.addNewNode(tx,fileInode.toBuffer(),function(e3,fileInodeId){if(noErrorTx(e3,tx,cb)){dirListing[fname]=fileInodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(function(e5){if(noErrorTx(e5,tx,cb)){cb(null,fileInode)}})}})}})}})}}})};AsyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),fileName=path.basename(p);this.findINodeAndDirListing(tx,parent,function(e,parentNode,parentListing){if(noErrorTx(e,tx,cb)){if(!parentListing[fileName]){tx.abort(function(){cb(ApiError.ENOENT(p))})}else{var fileNodeId=parentListing[fileName];delete parentListing[fileName];this$1.getINode(tx,p,fileNodeId,function(e2,fileNode){if(noErrorTx(e2,tx,cb)){if(!isDir&&fileNode.isDirectory()){tx.abort(function(){cb(ApiError.EISDIR(p))})}else if(isDir&&!fileNode.isDirectory()){tx.abort(function(){cb(ApiError.ENOTDIR(p))})}else{tx.del(fileNode.id,function(e3){if(noErrorTx(e3,tx,cb)){tx.del(fileNodeId,function(e4){if(noErrorTx(e4,tx,cb)){tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true,function(e5){if(noErrorTx(e5,tx,cb)){tx.commit(cb)}})}})}})}}})}}})};return AsyncKeyValueFileSystem2}(BaseFileSystem);var InMemoryStore=function InMemoryStore2(){this.store={}};InMemoryStore.prototype.name=function name(){return InMemoryFileSystem.Name};InMemoryStore.prototype.clear=function clear(){this.store={}};InMemoryStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};InMemoryStore.prototype.get=function get(key){return this.store[key]};InMemoryStore.prototype.put=function put(key,data,overwrite){if(!overwrite&&this.store.hasOwnProperty(key)){return false}this.store[key]=data;return true};InMemoryStore.prototype.del=function del(key){delete this.store[key]};var InMemoryFileSystem=function(SyncKeyValueFileSystem$$1){function InMemoryFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new InMemoryStore})}if(SyncKeyValueFileSystem$$1)InMemoryFileSystem2.__proto__=SyncKeyValueFileSystem$$1;InMemoryFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);InMemoryFileSystem2.prototype.constructor=InMemoryFileSystem2;InMemoryFileSystem2.Create=function Create(options,cb){cb(null,new InMemoryFileSystem2)};return InMemoryFileSystem2}(SyncKeyValueFileSystem);InMemoryFileSystem.Name="InMemory";InMemoryFileSystem.Options={};var indexedDB=global$1.indexedDB||global$1.mozIndexedDB||global$1.webkitIndexedDB||global$1.msIndexedDB;function convertError$2(e,message){if(message===void 0)message=e.toString();switch(e.name){case"NotFoundError":return new ApiError(ErrorCode.ENOENT,message);case"QuotaExceededError":return new ApiError(ErrorCode.ENOSPC,message);default:return new ApiError(ErrorCode.EIO,message)}}function onErrorHandler(cb,code,message){if(code===void 0)code=ErrorCode.EIO;if(message===void 0)message=null;return function(e){e.preventDefault();cb(new ApiError(code,message!==null?message:void 0))}}var IndexedDBROTransaction=function IndexedDBROTransaction2(tx,store){this.tx=tx;this.store=store};IndexedDBROTransaction.prototype.get=function get(key,cb){try{var r=this.store.get(key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){var result=event.target.result;if(result===void 0){cb(null,result)}else{cb(null,arrayBuffer2Buffer(result))}}}catch(e){cb(convertError$2(e))}};var IndexedDBRWTransaction=function(IndexedDBROTransaction2){function IndexedDBRWTransaction2(tx,store){IndexedDBROTransaction2.call(this,tx,store)}if(IndexedDBROTransaction2)IndexedDBRWTransaction2.__proto__=IndexedDBROTransaction2;IndexedDBRWTransaction2.prototype=Object.create(IndexedDBROTransaction2&&IndexedDBROTransaction2.prototype);IndexedDBRWTransaction2.prototype.constructor=IndexedDBRWTransaction2;IndexedDBRWTransaction2.prototype.put=function put(key,data,overwrite,cb){try{var arraybuffer=buffer2ArrayBuffer(data);var r;if(overwrite){r=this.store.put(arraybuffer,key)}else{r=this.store.add(arraybuffer,key)}r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb(null,true)}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.del=function del(key,cb){try{var r=this.store["delete"](key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb()}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.commit=function commit(cb){setTimeout(cb,0)};IndexedDBRWTransaction2.prototype.abort=function abort(cb){var _e=null;try{this.tx.abort()}catch(e){_e=convertError$2(e)}finally{cb(_e)}};return IndexedDBRWTransaction2}(IndexedDBROTransaction);var IndexedDBStore=function IndexedDBStore2(cb,storeName){var this$1=this;if(storeName===void 0)storeName="browserfs";this.storeName=storeName;var openReq=indexedDB.open(this.storeName,1);openReq.onupgradeneeded=function(event){var db=event.target.result;if(db.objectStoreNames.contains(this$1.storeName)){db.deleteObjectStore(this$1.storeName)}db.createObjectStore(this$1.storeName)};openReq.onsuccess=function(event){this$1.db=event.target.result;cb(null,this$1)};openReq.onerror=onErrorHandler(cb,ErrorCode.EACCES)};IndexedDBStore.prototype.name=function name(){return IndexedDBFileSystem.Name+" - "+this.storeName};IndexedDBStore.prototype.clear=function clear(cb){try{var tx=this.db.transaction(this.storeName,"readwrite"),objectStore=tx.objectStore(this.storeName),r=objectStore.clear();r.onsuccess=function(event){setTimeout(cb,0)};r.onerror=onErrorHandler(cb)}catch(e){cb(convertError$2(e))}};IndexedDBStore.prototype.beginTransaction=function beginTransaction(type){if(type===void 0)type="readonly";var tx=this.db.transaction(this.storeName,type),objectStore=tx.objectStore(this.storeName);if(type==="readwrite"){return new IndexedDBRWTransaction(tx,objectStore)}else if(type==="readonly"){return new IndexedDBROTransaction(tx,objectStore)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid transaction type.")}};var IndexedDBFileSystem=function(AsyncKeyValueFileSystem$$1){function IndexedDBFileSystem2(cb,storeName,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;AsyncKeyValueFileSystem$$1.call(this);this.store=new IndexedDBStore(function(e){if(e){cb(e)}else{this$1.init(this$1.store,function(e2){cb(e2,this$1)})}},storeName);deprecationMessage(deprecateMsg,IndexedDBFileSystem2.Name,{storeName})}if(AsyncKeyValueFileSystem$$1)IndexedDBFileSystem2.__proto__=AsyncKeyValueFileSystem$$1;IndexedDBFileSystem2.prototype=Object.create(AsyncKeyValueFileSystem$$1&&AsyncKeyValueFileSystem$$1.prototype);IndexedDBFileSystem2.prototype.constructor=IndexedDBFileSystem2;IndexedDBFileSystem2.Create=function Create(opts,cb){new IndexedDBFileSystem2(cb,opts.storeName,false)};IndexedDBFileSystem2.isAvailable=function isAvailable(){try{return typeof indexedDB!=="undefined"&&null!==indexedDB.open("__browserfs_test__")}catch(e){return false}};return IndexedDBFileSystem2}(AsyncKeyValueFileSystem);IndexedDBFileSystem.Name="IndexedDB";IndexedDBFileSystem.Options={storeName:{type:"string",optional:true,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var supportsBinaryString=false;var binaryEncoding;try{global$1.localStorage.setItem("__test__",String.fromCharCode(55296));supportsBinaryString=global$1.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(e){supportsBinaryString=false}binaryEncoding=supportsBinaryString?"binary_string":"binary_string_ie";if(!Buffer2.isEncoding(binaryEncoding)){binaryEncoding="base64"}var LocalStorageStore=function LocalStorageStore2(){};LocalStorageStore.prototype.name=function name(){return LocalStorageFileSystem.Name};LocalStorageStore.prototype.clear=function clear(){global$1.localStorage.clear()};LocalStorageStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};LocalStorageStore.prototype.get=function get(key){try{var data=global$1.localStorage.getItem(key);if(data!==null){return Buffer2.from(data,binaryEncoding)}}catch(e){}return void 0};LocalStorageStore.prototype.put=function put(key,data,overwrite){try{if(!overwrite&&global$1.localStorage.getItem(key)!==null){return false}global$1.localStorage.setItem(key,data.toString(binaryEncoding));return true}catch(e){throw new ApiError(ErrorCode.ENOSPC,"LocalStorage is full.")}};LocalStorageStore.prototype.del=function del(key){try{global$1.localStorage.removeItem(key)}catch(e){throw new ApiError(ErrorCode.EIO,"Unable to delete key "+key+": "+e)}};var LocalStorageFileSystem=function(SyncKeyValueFileSystem$$1){function LocalStorageFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new LocalStorageStore})}if(SyncKeyValueFileSystem$$1)LocalStorageFileSystem2.__proto__=SyncKeyValueFileSystem$$1;LocalStorageFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);LocalStorageFileSystem2.prototype.constructor=LocalStorageFileSystem2;LocalStorageFileSystem2.Create=function Create(options,cb){cb(null,new LocalStorageFileSystem2)};LocalStorageFileSystem2.isAvailable=function isAvailable(){return typeof global$1.localStorage!=="undefined"};return LocalStorageFileSystem2}(SyncKeyValueFileSystem);LocalStorageFileSystem.Name="LocalStorage";LocalStorageFileSystem.Options={};var MountableFileSystem=function(BaseFileSystem$$1){function MountableFileSystem2(){BaseFileSystem$$1.call(this);this.mountList=[];this.mntMap={};this.rootFs=new InMemoryFileSystem}if(BaseFileSystem$$1)MountableFileSystem2.__proto__=BaseFileSystem$$1;MountableFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);MountableFileSystem2.prototype.constructor=MountableFileSystem2;MountableFileSystem2.Create=function Create(opts,cb){var fs4=new MountableFileSystem2;Object.keys(opts).forEach(function(mountPoint){fs4.mount(mountPoint,opts[mountPoint])});cb(null,fs4)};MountableFileSystem2.isAvailable=function isAvailable(){return true};MountableFileSystem2.prototype.mount=function mount(mountPoint,fs4){if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already taken.")}mkdirpSync(mountPoint,511,this.rootFs);this.mntMap[mountPoint]=fs4;this.mountList.push(mountPoint);this.mountList=this.mountList.sort(function(a,b){return b.length-a.length})};MountableFileSystem2.prototype.umount=function umount(mountPoint){var this$1=this;if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(!this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already unmounted.")}delete this.mntMap[mountPoint];this.mountList.splice(this.mountList.indexOf(mountPoint),1);while(mountPoint!=="/"){if(this$1.rootFs.readdirSync(mountPoint).length===0){this$1.rootFs.rmdirSync(mountPoint);mountPoint=path.dirname(mountPoint)}else{break}}};MountableFileSystem2.prototype._getFs=function _getFs(path$$1){var this$1=this;var mountList=this.mountList,len=mountList.length;for(var i2=0;i21?mountPoint.length:0);if(path$$1===""){path$$1="/"}return{fs:this$1.mntMap[mountPoint],path:path$$1}}}return{fs:this.rootFs,path:path$$1}};MountableFileSystem2.prototype.getName=function getName(){return MountableFileSystem2.Name};MountableFileSystem2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};MountableFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};MountableFileSystem2.prototype.supportsLinks=function supportsLinks(){return false};MountableFileSystem2.prototype.supportsProps=function supportsProps(){return false};MountableFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};MountableFileSystem2.prototype.standardizeError=function standardizeError(err,path$$1,realPath){var index=err.message.indexOf(path$$1);if(index!==-1){err.message=err.message.substr(0,index)+realPath+err.message.substr(index+path$$1.length);err.path=realPath}return err};MountableFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){return fs1rv.fs.rename(fs1rv.path,fs2rv.path,function(e){if(e){this$1.standardizeError(this$1.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath)}cb(e)})}return _fsMock.readFile(oldPath,function(err,data){if(err){return cb(err)}_fsMock.writeFile(newPath,data,function(err2){if(err2){return cb(err2)}_fsMock.unlink(oldPath,cb)})})};MountableFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){try{return fs1rv.fs.renameSync(fs1rv.path,fs2rv.path)}catch(e){this.standardizeError(this.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath);throw e}}var data=_fsMock.readFileSync(oldPath);_fsMock.writeFileSync(newPath,data);return _fsMock.unlinkSync(oldPath)};MountableFileSystem2.prototype.readdirSync=function readdirSync(p){var fsInfo=this._getFs(p);var rv=null;if(fsInfo.fs!==this.rootFs){try{rv=this.rootFs.readdirSync(p)}catch(e){}}try{var rv2=fsInfo.fs.readdirSync(fsInfo.path);if(rv===null){return rv2}else{return rv2.concat(rv.filter(function(val){return rv2.indexOf(val)===-1}))}}catch(e){if(rv===null){throw this.standardizeError(e,fsInfo.path,p)}else{return rv}}};MountableFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);fsInfo.fs.readdir(fsInfo.path,function(err,files){if(fsInfo.fs!==this$1.rootFs){try{var rv=this$1.rootFs.readdirSync(p);if(files){files=files.concat(rv.filter(function(val){return files.indexOf(val)===-1}))}else{files=rv}}catch(e){if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}}}else if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}cb(null,files)})};MountableFileSystem2.prototype.rmdirSync=function rmdirSync(p){var fsInfo=this._getFs(p);if(this._containsMountPt(p)){throw ApiError.ENOTEMPTY(p)}else{try{fsInfo.fs.rmdirSync(fsInfo.path)}catch(e){throw this.standardizeError(e,fsInfo.path,p)}}};MountableFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);if(this._containsMountPt(p)){cb(ApiError.ENOTEMPTY(p))}else{fsInfo.fs.rmdir(fsInfo.path,function(err){cb(err?this$1.standardizeError(err,fsInfo.path,p):null)})}};MountableFileSystem2.prototype._containsMountPt=function _containsMountPt(p){var mountPoints=this.mountList,len=mountPoints.length;for(var i2=0;i2=p.length&&pt.slice(0,p.length)===p){return true}}return false};return MountableFileSystem2}(BaseFileSystem);MountableFileSystem.Name="MountableFileSystem";MountableFileSystem.Options={};function defineFcn(name,isSync,numArgs){if(isSync){return function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;try{return rv.fs[name].apply(rv.fs,args)}catch(e){this.standardizeError(e,rv.path,path$$1);throw e}}}else{return function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;if(typeof args[args.length-1]==="function"){var cb=args[args.length-1];args[args.length-1]=function(){var args2=[],len2=arguments.length;while(len2--)args2[len2]=arguments[len2];if(args2.length>0&&args2[0]instanceof ApiError){this$1.standardizeError(args2[0],rv.path,path$$1)}cb.apply(null,args2)}}return rv.fs[name].apply(rv.fs,args)}}}var fsCmdMap=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]];for(var i=0;i0){var fn=timeouts.shift();return fn()}}};if(gScope.addEventListener){gScope.addEventListener("message",handleMessage,true)}else{gScope.attachEvent("onmessage",handleMessage)}}else if(gScope.MessageChannel){var channel=new gScope.MessageChannel;channel.port1.onmessage=function(event){if(timeouts.length>0){return timeouts.shift()()}};bfsSetImmediate=function(fn){timeouts.push(fn);channel.port2.postMessage("")}}else{bfsSetImmediate=function(fn){return setTimeout(fn,0)}}}var setImmediate$3=bfsSetImmediate;var Mutex=function Mutex2(){this._locked=false;this._waiters=[]};Mutex.prototype.lock=function lock(cb){if(this._locked){this._waiters.push(cb);return}this._locked=true;cb()};Mutex.prototype.unlock=function unlock(){if(!this._locked){throw new Error("unlock of a non-locked mutex")}var next=this._waiters.shift();if(next){setImmediate$3(next);return}this._locked=false};Mutex.prototype.tryLock=function tryLock(){if(this._locked){return false}this._locked=true;return true};Mutex.prototype.isLocked=function isLocked(){return this._locked};var LockedFS=function LockedFS2(fs4){this._fs=fs4;this._mu=new Mutex};LockedFS.prototype.getName=function getName(){return"LockedFS<"+this._fs.getName()+">"};LockedFS.prototype.getFSUnlocked=function getFSUnlocked(){return this._fs};LockedFS.prototype.initialize=function initialize3(cb){this._fs.initialize(cb)};LockedFS.prototype.diskSpace=function diskSpace(p,cb){this._fs.diskSpace(p,cb)};LockedFS.prototype.isReadOnly=function isReadOnly(){return this._fs.isReadOnly()};LockedFS.prototype.supportsLinks=function supportsLinks(){return this._fs.supportsLinks()};LockedFS.prototype.supportsProps=function supportsProps(){return this._fs.supportsProps()};LockedFS.prototype.supportsSynch=function supportsSynch(){return this._fs.supportsSynch()};LockedFS.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rename(oldPath,newPath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.renameSync=function renameSync(oldPath,newPath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.renameSync(oldPath,newPath)};LockedFS.prototype.stat=function stat(p,isLstat,cb){var this$1=this;this._mu.lock(function(){this$1._fs.stat(p,isLstat,function(err,stat2){this$1._mu.unlock();cb(err,stat2)})})};LockedFS.prototype.statSync=function statSync(p,isLstat){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.statSync(p,isLstat)};LockedFS.prototype.open=function open(p,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.open(p,flag,mode,function(err,fd){this$1._mu.unlock();cb(err,fd)})})};LockedFS.prototype.openSync=function openSync(p,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.openSync(p,flag,mode)};LockedFS.prototype.unlink=function unlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.unlink(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.unlinkSync=function unlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.unlinkSync(p)};LockedFS.prototype.rmdir=function rmdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rmdir(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.rmdirSync=function rmdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.rmdirSync(p)};LockedFS.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.mkdir(p,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.mkdirSync=function mkdirSync(p,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.mkdirSync(p,mode)};LockedFS.prototype.readdir=function readdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readdir(p,function(err,files){this$1._mu.unlock();cb(err,files)})})};LockedFS.prototype.readdirSync=function readdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readdirSync(p)};LockedFS.prototype.exists=function exists2(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.exists(p,function(exists3){this$1._mu.unlock();cb(exists3)})})};LockedFS.prototype.existsSync=function existsSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.existsSync(p)};LockedFS.prototype.realpath=function realpath(p,cache,cb){var this$1=this;this._mu.lock(function(){this$1._fs.realpath(p,cache,function(err,resolvedPath){this$1._mu.unlock();cb(err,resolvedPath)})})};LockedFS.prototype.realpathSync=function realpathSync(p,cache){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.realpathSync(p,cache)};LockedFS.prototype.truncate=function truncate(p,len,cb){var this$1=this;this._mu.lock(function(){this$1._fs.truncate(p,len,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.truncateSync=function truncateSync(p,len){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.truncateSync(p,len)};LockedFS.prototype.readFile=function readFile2(fname,encoding,flag,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readFile(fname,encoding,flag,function(err,data){this$1._mu.unlock();cb(err,data)})})};LockedFS.prototype.readFileSync=function readFileSync(fname,encoding,flag){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readFileSync(fname,encoding,flag)};LockedFS.prototype.writeFile=function writeFile2(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.writeFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.writeFileSync=function writeFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.writeFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.appendFile=function appendFile3(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.appendFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.appendFileSync=function appendFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.appendFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chmod(p,isLchmod,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chmodSync=function chmodSync(p,isLchmod,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chmodSync(p,isLchmod,mode)};LockedFS.prototype.chown=function chown(p,isLchown,uid,gid,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chown(p,isLchown,uid,gid,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chownSync=function chownSync(p,isLchown,uid,gid){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chownSync(p,isLchown,uid,gid)};LockedFS.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;this._mu.lock(function(){this$1._fs.utimes(p,atime,mtime,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.utimesSync=function utimesSync(p,atime,mtime){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.utimesSync(p,atime,mtime)};LockedFS.prototype.link=function link(srcpath,dstpath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.link(srcpath,dstpath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.linkSync=function linkSync(srcpath,dstpath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.linkSync(srcpath,dstpath)};LockedFS.prototype.symlink=function symlink(srcpath,dstpath,type,cb){var this$1=this;this._mu.lock(function(){this$1._fs.symlink(srcpath,dstpath,type,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.symlinkSync(srcpath,dstpath,type)};LockedFS.prototype.readlink=function readlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readlink(p,function(err,linkString){this$1._mu.unlock();cb(err,linkString)})})};LockedFS.prototype.readlinkSync=function readlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readlinkSync(p)};var deletionLogPath="/.deletedFiles.log";function makeModeWritable(mode){return 146|mode}function getFlag(f){return FileFlag.getFileFlag(f)}var OverlayFile=function(PreloadFile$$1){function OverlayFile2(fs4,path$$1,flag,stats,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stats,data)}if(PreloadFile$$1)OverlayFile2.__proto__=PreloadFile$$1;OverlayFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);OverlayFile2.prototype.constructor=OverlayFile2;OverlayFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){cb(null);return}this._fs._syncAsync(this,function(err){this$1.resetDirty();cb(err)})};OverlayFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};OverlayFile2.prototype.close=function close(cb){this.sync(cb)};OverlayFile2.prototype.closeSync=function closeSync(){this.syncSync()};return OverlayFile2}(PreloadFile);var UnlockedOverlayFS=function(BaseFileSystem$$1){function UnlockedOverlayFS2(writable,readable){BaseFileSystem$$1.call(this);this._isInitialized=false;this._initializeCallbacks=[];this._deletedFiles={};this._deleteLog="";this._deleteLogUpdatePending=false;this._deleteLogUpdateNeeded=false;this._deleteLogError=null;this._writable=writable;this._readable=readable;if(this._writable.isReadOnly()){throw new ApiError(ErrorCode.EINVAL,"Writable file system must be writable.")}}if(BaseFileSystem$$1)UnlockedOverlayFS2.__proto__=BaseFileSystem$$1;UnlockedOverlayFS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);UnlockedOverlayFS2.prototype.constructor=UnlockedOverlayFS2;UnlockedOverlayFS2.isAvailable=function isAvailable(){return true};UnlockedOverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return{readable:this._readable,writable:this._writable}};UnlockedOverlayFS2.prototype._syncAsync=function _syncAsync(file,cb){var this$1=this;this.createParentDirectoriesAsync(file.getPath(),function(err){if(err){return cb(err)}this$1._writable.writeFile(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode,cb)})};UnlockedOverlayFS2.prototype._syncSync=function _syncSync(file){this.createParentDirectories(file.getPath());this._writable.writeFileSync(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode)};UnlockedOverlayFS2.prototype.getName=function getName(){return OverlayFS.Name};UnlockedOverlayFS2.prototype.initialize=function initialize3(cb){var this$1=this;var callbackArray=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbackArray.forEach(function(cb2){return cb2(e)})};if(this._isInitialized){return cb()}callbackArray.push(cb);if(callbackArray.length!==1){return}this._writable.readFile(deletionLogPath,"utf8",getFlag("r"),function(err,data){if(err){if(err.errno!==ErrorCode.ENOENT){return end(err)}}else{this$1._deleteLog=data}this$1._reparseDeletionLog();end()})};UnlockedOverlayFS2.prototype.isReadOnly=function isReadOnly(){return false};UnlockedOverlayFS2.prototype.supportsSynch=function supportsSynch(){return this._readable.supportsSynch()&&this._writable.supportsSynch()};UnlockedOverlayFS2.prototype.supportsLinks=function supportsLinks(){return false};UnlockedOverlayFS2.prototype.supportsProps=function supportsProps(){return this._readable.supportsProps()&&this._writable.supportsProps()};UnlockedOverlayFS2.prototype.getDeletionLog=function getDeletionLog(){return this._deleteLog};UnlockedOverlayFS2.prototype.restoreDeletionLog=function restoreDeletionLog(log){this._deleteLog=log;this._reparseDeletionLog();this.updateLog("")};UnlockedOverlayFS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(oldPath,cb)||this.checkPathAsync(newPath,cb)){return}if(oldPath===deletionLogPath||newPath===deletionLogPath){return cb(ApiError.EPERM("Cannot rename deletion log."))}if(oldPath===newPath){return cb()}this.stat(oldPath,false,function(oldErr,oldStats){if(oldErr){return cb(oldErr)}return this$1.stat(newPath,false,function(newErr,newStats){var self2=this$1;function copyDirContents(files){var file=files.shift();if(!file){return cb()}var oldFile=path.resolve(oldPath,file);var newFile=path.resolve(newPath,file);self2.rename(oldFile,newFile,function(err){if(err){return cb(err)}copyDirContents(files)})}var mode=511;if(oldStats.isDirectory()){if(newErr){if(newErr.errno!==ErrorCode.ENOENT){return cb(newErr)}return this$1._writable.exists(oldPath,function(exists2){if(exists2){return this$1._writable.rename(oldPath,newPath,cb)}this$1._writable.mkdir(newPath,mode,function(mkdirErr){if(mkdirErr){return cb(mkdirErr)}this$1._readable.readdir(oldPath,function(err,files){if(err){return cb()}copyDirContents(files)})})})}mode=newStats.mode;if(!newStats.isDirectory()){return cb(ApiError.ENOTDIR(newPath))}this$1.readdir(newPath,function(readdirErr,files){if(files&&files.length){return cb(ApiError.ENOTEMPTY(newPath))}this$1._readable.readdir(oldPath,function(err,files2){if(err){return cb()}copyDirContents(files2)})})}if(newStats&&newStats.isDirectory()){return cb(ApiError.EISDIR(newPath))}this$1.readFile(oldPath,null,getFlag("r"),function(err,data){if(err){return cb(err)}return this$1.writeFile(newPath,data,null,getFlag("w"),oldStats.mode,function(err2){if(err2){return cb(err2)}return this$1.unlink(oldPath,cb)})})})})};UnlockedOverlayFS2.prototype.renameSync=function renameSync(oldPath,newPath){var this$1=this;this.checkInitialized();this.checkPath(oldPath);this.checkPath(newPath);if(oldPath===deletionLogPath||newPath===deletionLogPath){throw ApiError.EPERM("Cannot rename deletion log.")}var oldStats=this.statSync(oldPath,false);if(oldStats.isDirectory()){if(oldPath===newPath){return}var mode=511;if(this.existsSync(newPath)){var stats=this.statSync(newPath,false);mode=stats.mode;if(stats.isDirectory()){if(this.readdirSync(newPath).length>0){throw ApiError.ENOTEMPTY(newPath)}}else{throw ApiError.ENOTDIR(newPath)}}if(this._writable.existsSync(oldPath)){this._writable.renameSync(oldPath,newPath)}else if(!this._writable.existsSync(newPath)){this._writable.mkdirSync(newPath,mode)}if(this._readable.existsSync(oldPath)){this._readable.readdirSync(oldPath).forEach(function(name){this$1.renameSync(path.resolve(oldPath,name),path.resolve(newPath,name))})}}else{if(this.existsSync(newPath)&&this.statSync(newPath,false).isDirectory()){throw ApiError.EISDIR(newPath)}this.writeFileSync(newPath,this.readFileSync(oldPath,null,getFlag("r")),null,getFlag("w"),oldStats.mode)}if(oldPath!==newPath&&this.existsSync(oldPath)){this.unlinkSync(oldPath)}};UnlockedOverlayFS2.prototype.stat=function stat(p,isLstat,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this._writable.stat(p,isLstat,function(err,stat2){if(err&&err.errno===ErrorCode.ENOENT){if(this$1._deletedFiles[p]){cb(ApiError.ENOENT(p))}this$1._readable.stat(p,isLstat,function(err2,stat3){if(stat3){stat3=stat3.clone();stat3.mode=makeModeWritable(stat3.mode)}cb(err2,stat3)})}else{cb(err,stat2)}})};UnlockedOverlayFS2.prototype.statSync=function statSync(p,isLstat){this.checkInitialized();try{return this._writable.statSync(p,isLstat)}catch(e){if(this._deletedFiles[p]){throw ApiError.ENOENT(p)}var oldStat=this._readable.statSync(p,isLstat).clone();oldStat.mode=makeModeWritable(oldStat.mode);return oldStat}};UnlockedOverlayFS2.prototype.open=function open(p,flag,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.stat(p,false,function(err,stats){if(stats){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}this$1._writable.open(p,flag,mode,cb)});case ActionType.NOP:return this$1._writable.exists(p,function(exists2){if(exists2){this$1._writable.open(p,flag,mode,cb)}else{stats=stats.clone();stats.mode=mode;this$1._readable.readFile(p,null,getFlag("r"),function(readFileErr,data){if(readFileErr){return cb(readFileErr)}if(stats.size===-1){stats.size=data.length}var f=new OverlayFile(this$1,p,flag,stats,data);cb(null,f)})}});default:return cb(ApiError.EEXIST(p))}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}return this$1._writable.open(p,flag,mode,cb)});default:return cb(ApiError.ENOENT(p))}}})};UnlockedOverlayFS2.prototype.openSync=function openSync(p,flag,mode){this.checkInitialized();this.checkPath(p);if(p===deletionLogPath){throw ApiError.EPERM("Cannot open deletion log.")}if(this.existsSync(p)){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);case ActionType.NOP:if(this._writable.existsSync(p)){return this._writable.openSync(p,flag,mode)}else{var buf=this._readable.readFileSync(p,null,getFlag("r"));var stats=this._readable.statSync(p,false).clone();stats.mode=mode;return new OverlayFile(this,p,flag,stats,buf)}default:throw ApiError.EEXIST(p)}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);default:throw ApiError.ENOENT(p)}}};UnlockedOverlayFS2.prototype.unlink=function unlink(p,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){return this$1._writable.unlink(p,function(err){if(err){return cb(err)}this$1.exists(p,function(readableExists){if(readableExists){this$1.deletePath(p)}cb(null)})})}else{this$1.deletePath(p);cb(null)}})})};UnlockedOverlayFS2.prototype.unlinkSync=function unlinkSync(p){this.checkInitialized();this.checkPath(p);if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.unlinkSync(p)}if(this.existsSync(p)){this.deletePath(p)}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.rmdir=function rmdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}var rmdirLower=function(){this$1.readdir(p,function(err,files){if(err){return cb(err)}if(files.length){return cb(ApiError.ENOTEMPTY(p))}this$1.deletePath(p);cb(null)})};this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){this$1._writable.rmdir(p,function(err){if(err){return cb(err)}this$1._readable.exists(p,function(readableExists){if(readableExists){rmdirLower()}else{cb()}})})}else{rmdirLower()}})})};UnlockedOverlayFS2.prototype.rmdirSync=function rmdirSync(p){this.checkInitialized();if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.rmdirSync(p)}if(this.existsSync(p)){if(this.readdirSync(p).length>0){throw ApiError.ENOTEMPTY(p)}else{this.deletePath(p)}}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.exists(p,function(exists2){if(exists2){return cb(ApiError.EEXIST(p))}this$1.createParentDirectoriesAsync(p,function(err){if(err){return cb(err)}this$1._writable.mkdir(p,mode,cb)})})};UnlockedOverlayFS2.prototype.mkdirSync=function mkdirSync(p,mode){this.checkInitialized();if(this.existsSync(p)){throw ApiError.EEXIST(p)}else{this.createParentDirectories(p);this._writable.mkdirSync(p,mode)}};UnlockedOverlayFS2.prototype.readdir=function readdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.stat(p,false,function(err,dirStats){if(err){return cb(err)}if(!dirStats.isDirectory()){return cb(ApiError.ENOTDIR(p))}this$1._writable.readdir(p,function(err2,wFiles){if(err2&&err2.code!=="ENOENT"){return cb(err2)}else if(err2||!wFiles){wFiles=[]}this$1._readable.readdir(p,function(err3,rFiles){if(err3||!rFiles){rFiles=[]}var seenMap={};var filtered=wFiles.concat(rFiles.filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]})).filter(function(fPath){var result=!seenMap[fPath];seenMap[fPath]=true;return result});cb(null,filtered)})})})};UnlockedOverlayFS2.prototype.readdirSync=function readdirSync(p){var this$1=this;this.checkInitialized();var dirStats=this.statSync(p,false);if(!dirStats.isDirectory()){throw ApiError.ENOTDIR(p)}var contents=[];try{contents=contents.concat(this._writable.readdirSync(p))}catch(e){}try{contents=contents.concat(this._readable.readdirSync(p).filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]}))}catch(e){}var seenMap={};return contents.filter(function(fileP){var result=!seenMap[fileP];seenMap[fileP]=true;return result})};UnlockedOverlayFS2.prototype.exists=function exists2(p,cb){var this$1=this;this.checkInitialized();this._writable.exists(p,function(existsWritable){if(existsWritable){return cb(true)}this$1._readable.exists(p,function(existsReadable){cb(existsReadable&&this$1._deletedFiles[p]!==true)})})};UnlockedOverlayFS2.prototype.existsSync=function existsSync(p){this.checkInitialized();return this._writable.existsSync(p)||this._readable.existsSync(p)&&this._deletedFiles[p]!==true};UnlockedOverlayFS2.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chmod(p,isLchmod,mode,cb)}})};UnlockedOverlayFS2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chmodSync(p,isLchmod,mode)})};UnlockedOverlayFS2.prototype.chown=function chown(p,isLchmod,uid,gid,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chown(p,isLchmod,uid,gid,cb)}})};UnlockedOverlayFS2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chownSync(p,isLchown,uid,gid)})};UnlockedOverlayFS2.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.utimes(p,atime,mtime,cb)}})};UnlockedOverlayFS2.prototype.utimesSync=function utimesSync(p,atime,mtime){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.utimesSync(p,atime,mtime)})};UnlockedOverlayFS2.prototype.deletePath=function deletePath(p){this._deletedFiles[p]=true;this.updateLog("d"+p+"\n")};UnlockedOverlayFS2.prototype.updateLog=function updateLog(addition){var this$1=this;this._deleteLog+=addition;if(this._deleteLogUpdatePending){this._deleteLogUpdateNeeded=true}else{this._deleteLogUpdatePending=true;this._writable.writeFile(deletionLogPath,this._deleteLog,"utf8",FileFlag.getFileFlag("w"),420,function(e){this$1._deleteLogUpdatePending=false;if(e){this$1._deleteLogError=e}else if(this$1._deleteLogUpdateNeeded){this$1._deleteLogUpdateNeeded=false;this$1.updateLog("")}})}};UnlockedOverlayFS2.prototype._reparseDeletionLog=function _reparseDeletionLog(){var this$1=this;this._deletedFiles={};this._deleteLog.split("\n").forEach(function(path$$1){this$1._deletedFiles[path$$1.slice(1)]=path$$1.slice(0,1)==="d"})};UnlockedOverlayFS2.prototype.checkInitialized=function checkInitialized(){if(!this._isInitialized){throw new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;throw e}};UnlockedOverlayFS2.prototype.checkInitAsync=function checkInitAsync(cb){if(!this._isInitialized){cb(new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it."));return false}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;cb(e);return false}return true};UnlockedOverlayFS2.prototype.checkPath=function checkPath(p){if(p===deletionLogPath){throw ApiError.EPERM(p)}};UnlockedOverlayFS2.prototype.checkPathAsync=function checkPathAsync(p,cb){if(p===deletionLogPath){cb(ApiError.EPERM(p));return true}return false};UnlockedOverlayFS2.prototype.createParentDirectoriesAsync=function createParentDirectoriesAsync(p,cb){var parent=path.dirname(p);var toCreate=[];var self2=this;this._writable.stat(parent,false,statDone);function statDone(err,stat){if(err){toCreate.push(parent);parent=path.dirname(parent);self2._writable.stat(parent,false,statDone)}else{createParents()}}function createParents(){if(!toCreate.length){return cb()}var dir2=toCreate.pop();self2._readable.stat(dir2,false,function(err,stats){if(!stats){return cb()}self2._writable.mkdir(dir2,stats.mode,function(err2){if(err2){return cb(err2)}createParents()})})}};UnlockedOverlayFS2.prototype.createParentDirectories=function createParentDirectories(p){var this$1=this;var parent=path.dirname(p),toCreate=[];while(!this._writable.existsSync(parent)){toCreate.push(parent);parent=path.dirname(parent)}toCreate=toCreate.reverse();toCreate.forEach(function(p2){this$1._writable.mkdirSync(p2,this$1.statSync(p2,false).mode)})};UnlockedOverlayFS2.prototype.operateOnWritable=function operateOnWritable(p,f){if(this.existsSync(p)){if(!this._writable.existsSync(p)){this.copyToWritable(p)}f()}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.operateOnWritableAsync=function operateOnWritableAsync(p,cb){var this$1=this;this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(existsWritable){if(existsWritable){cb()}else{return this$1.copyToWritableAsync(p,cb)}})})};UnlockedOverlayFS2.prototype.copyToWritable=function copyToWritable(p){var pStats=this.statSync(p,false);if(pStats.isDirectory()){this._writable.mkdirSync(p,pStats.mode)}else{this.writeFileSync(p,this._readable.readFileSync(p,null,getFlag("r")),null,getFlag("w"),this.statSync(p,false).mode)}};UnlockedOverlayFS2.prototype.copyToWritableAsync=function copyToWritableAsync(p,cb){var this$1=this;this.stat(p,false,function(err,pStats){if(err){return cb(err)}if(pStats.isDirectory()){return this$1._writable.mkdir(p,pStats.mode,cb)}this$1._readable.readFile(p,null,getFlag("r"),function(err2,data){if(err2){return cb(err2)}this$1.writeFile(p,data,null,getFlag("w"),pStats.mode,cb)})})};return UnlockedOverlayFS2}(BaseFileSystem);var OverlayFS=function(LockedFS$$1){function OverlayFS2(writable,readable,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;LockedFS$$1.call(this,new UnlockedOverlayFS(writable,readable));deprecationMessage(deprecateMsg,OverlayFS2.Name,{readable:"readable file system",writable:"writable file system"})}if(LockedFS$$1)OverlayFS2.__proto__=LockedFS$$1;OverlayFS2.prototype=Object.create(LockedFS$$1&&LockedFS$$1.prototype);OverlayFS2.prototype.constructor=OverlayFS2;OverlayFS2.Create=function Create(opts,cb){try{var fs4=new OverlayFS2(opts.writable,opts.readable,false);fs4.initialize(function(e){cb(e,fs4)},false)}catch(e){cb(e)}};OverlayFS2.isAvailable=function isAvailable(){return UnlockedOverlayFS.isAvailable()};OverlayFS2.prototype.initialize=function initialize3(cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.")}LockedFS$$1.prototype.initialize.call(this,cb)};OverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()};OverlayFS2.prototype.unwrap=function unwrap(){return LockedFS$$1.prototype.getFSUnlocked.call(this)};return OverlayFS2}(LockedFS);OverlayFS.Name="OverlayFS";OverlayFS.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var SpecialArgType;(function(SpecialArgType2){SpecialArgType2[SpecialArgType2["CB"]=0]="CB";SpecialArgType2[SpecialArgType2["FD"]=1]="FD";SpecialArgType2[SpecialArgType2["API_ERROR"]=2]="API_ERROR";SpecialArgType2[SpecialArgType2["STATS"]=3]="STATS";SpecialArgType2[SpecialArgType2["PROBE"]=4]="PROBE";SpecialArgType2[SpecialArgType2["FILEFLAG"]=5]="FILEFLAG";SpecialArgType2[SpecialArgType2["BUFFER"]=6]="BUFFER";SpecialArgType2[SpecialArgType2["ERROR"]=7]="ERROR"})(SpecialArgType||(SpecialArgType={}));var CallbackArgumentConverter=function CallbackArgumentConverter2(){this._callbacks={};this._nextId=0};CallbackArgumentConverter.prototype.toRemoteArg=function toRemoteArg(cb){var id=this._nextId++;this._callbacks[id]=cb;return{type:SpecialArgType.CB,id}};CallbackArgumentConverter.prototype.toLocalArg=function toLocalArg(id){var cb=this._callbacks[id];delete this._callbacks[id];return cb};var FileDescriptorArgumentConverter=function FileDescriptorArgumentConverter2(){this._fileDescriptors={};this._nextId=0};FileDescriptorArgumentConverter.prototype.toRemoteArg=function toRemoteArg(fd,p,flag,cb){var id=this._nextId++;var data;var stat;this._fileDescriptors[id]=fd;fd.stat(function(err,stats){if(err){cb(err)}else{stat=bufferToTransferrableObject(stats.toBuffer());if(flag.isReadable()){fd.read(Buffer2.alloc(stats.size),0,stats.size,0,function(err2,bytesRead,buff){if(err2){cb(err2)}else{data=bufferToTransferrableObject(buff);cb(null,{type:SpecialArgType.FD,id,data,stat,path:p,flag:flag.getFlagString()})}})}else{cb(null,{type:SpecialArgType.FD,id,data:new ArrayBuffer(0),stat,path:p,flag:flag.getFlagString()})}}})};FileDescriptorArgumentConverter.prototype.applyFdAPIRequest=function applyFdAPIRequest(request,cb){var this$1=this;var fdArg=request.args[0];this._applyFdChanges(fdArg,function(err,fd){if(err){cb(err)}else{fd[request.method](function(e){if(request.method==="close"){delete this$1._fileDescriptors[fdArg.id]}cb(e)})}})};FileDescriptorArgumentConverter.prototype._applyFdChanges=function _applyFdChanges(remoteFd,cb){var fd=this._fileDescriptors[remoteFd.id],data=transferrableObjectToBuffer(remoteFd.data),remoteStats=Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));var flag=FileFlag.getFileFlag(remoteFd.flag);if(flag.isWriteable()){fd.write(data,0,data.length,flag.isAppendable()?fd.getPos():0,function(e){function applyStatChanges(){fd.stat(function(e2,stats){if(e2){cb(e2)}else{if(stats.mode!==remoteStats.mode){fd.chmod(remoteStats.mode,function(e3){cb(e3,fd)})}else{cb(e2,fd)}}})}if(e){cb(e)}else{if(!flag.isAppendable()){fd.truncate(data.length,function(){applyStatChanges()})}else{applyStatChanges()}}})}else{cb(null,fd)}};function apiErrorLocal2Remote(e){return{type:SpecialArgType.API_ERROR,errorData:bufferToTransferrableObject(e.writeToBuffer())}}function apiErrorRemote2Local(e){return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData))}function errorLocal2Remote(e){return{type:SpecialArgType.ERROR,name:e.name,message:e.message,stack:e.stack}}function errorRemote2Local(e){var cnstr=global$1[e.name];if(typeof cnstr!=="function"){cnstr=Error}var err=new cnstr(e.message);err.stack=e.stack;return err}function statsLocal2Remote(stats){return{type:SpecialArgType.STATS,statsData:bufferToTransferrableObject(stats.toBuffer())}}function statsRemote2Local(stats){return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData))}function fileFlagLocal2Remote(flag){return{type:SpecialArgType.FILEFLAG,flagStr:flag.getFlagString()}}function fileFlagRemote2Local(remoteFlag){return FileFlag.getFileFlag(remoteFlag.flagStr)}function bufferToTransferrableObject(buff){return buffer2ArrayBuffer(buff)}function transferrableObjectToBuffer(buff){return arrayBuffer2Buffer(buff)}function bufferLocal2Remote(buff){return{type:SpecialArgType.BUFFER,data:bufferToTransferrableObject(buff)}}function bufferRemote2Local(buffArg){return transferrableObjectToBuffer(buffArg.data)}function isAPIRequest(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}function isAPIResponse(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}var WorkerFile=function(PreloadFile$$1){function WorkerFile2(_fs,_path,_flag,_stat,remoteFdId,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents);this._remoteFdId=remoteFdId}if(PreloadFile$$1)WorkerFile2.__proto__=PreloadFile$$1;WorkerFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);WorkerFile2.prototype.constructor=WorkerFile2;WorkerFile2.prototype.getRemoteFdId=function getRemoteFdId(){return this._remoteFdId};WorkerFile2.prototype.toRemoteArg=function toRemoteArg(){return{type:SpecialArgType.FD,id:this._remoteFdId,data:bufferToTransferrableObject(this.getBuffer()),stat:bufferToTransferrableObject(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}};WorkerFile2.prototype.sync=function sync(cb){this._syncClose("sync",cb)};WorkerFile2.prototype.close=function close(cb){this._syncClose("close",cb)};WorkerFile2.prototype._syncClose=function _syncClose(type,cb){var this$1=this;if(this.isDirty()){this._fs.syncClose(type,this,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};return WorkerFile2}(PreloadFile);var WorkerFS=function(BaseFileSystem$$1){function WorkerFS2(worker,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._callbackConverter=new CallbackArgumentConverter;this._isInitialized=false;this._isReadOnly=false;this._supportLinks=false;this._supportProps=false;this._worker=worker;deprecationMessage(deprecateMsg,WorkerFS2.Name,{worker:"Web Worker instance"});this._worker.addEventListener("message",function(e){var resp=e.data;if(isAPIResponse(resp)){var i2;var args=resp.args;var fixedArgs=new Array(args.length);for(i2=0;i20){countdown=-1;message={browserfsMessage:true,cbId,args:[apiErrorLocal2Remote(err)]};worker.postMessage(message)}}for(i2=0;i20){var inode=void 0;var next=queue.pop();var pwd=next[0];var tree=next[1];var parent=next[2];for(var node in tree){if(tree.hasOwnProperty(node)){var children=tree[node];var name=pwd+"/"+node;if(children){idx._index[name]=inode=new DirInode;queue.push([name,children,inode])}else{inode=new FileInode(new Stats(FileType.FILE,-1,365))}if(parent){parent._ls[node]=inode}}}}return idx};FileIndex.prototype.fileIterator=function fileIterator(cb){var this$1=this;for(var path$$1 in this$1._index){if(this$1._index.hasOwnProperty(path$$1)){var dir2=this$1._index[path$$1];var files=dir2.getListing();for(var i2=0,list2=files;i20&&prefixUrl.charAt(prefixUrl.length-1)!=="/"){prefixUrl=prefixUrl+"/"}this.prefixUrl=prefixUrl;var listing=null;if(typeof listingUrlOrObj==="string"){listing=this._requestFileSync(listingUrlOrObj,"json");if(!listing){throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}}else{listing=listingUrlOrObj}deprecationMessage(deprecateMsg,XmlHttpRequest2.Name,{index:typeof listingUrlOrObj==="string"?listingUrlOrObj:"file index as an object",baseUrl:prefixUrl});this._index=FileIndex.fromListing(listing)}if(BaseFileSystem$$1)XmlHttpRequest2.__proto__=BaseFileSystem$$1;XmlHttpRequest2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);XmlHttpRequest2.prototype.constructor=XmlHttpRequest2;XmlHttpRequest2.Create=function Create(opts,cb){if(opts.index===void 0){opts.index="index.json"}if(typeof opts.index==="string"){XmlHttpRequest2.FromURL(opts.index,cb,opts.baseUrl,false)}else{cb(null,new XmlHttpRequest2(opts.index,opts.baseUrl,false))}};XmlHttpRequest2.isAvailable=function isAvailable(){return typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest!==null};XmlHttpRequest2.FromURL=function FromURL(url,cb,baseUrl,deprecateMsg){if(baseUrl===void 0)baseUrl=url.slice(0,url.lastIndexOf("/")+1);if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: "`+url+'", baseUrl: "'+baseUrl+`" }, cb)' instead.`)}asyncDownloadFile(url,"json",function(e,data){if(e){cb(e)}else{cb(null,new XmlHttpRequest2(data,baseUrl,false))}})};XmlHttpRequest2.prototype.empty=function empty(){this._index.fileIterator(function(file){file.fileData=null})};XmlHttpRequest2.prototype.getName=function getName(){return XmlHttpRequest2.Name};XmlHttpRequest2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};XmlHttpRequest2.prototype.isReadOnly=function isReadOnly(){return true};XmlHttpRequest2.prototype.supportsLinks=function supportsLinks(){return false};XmlHttpRequest2.prototype.supportsProps=function supportsProps(){return false};XmlHttpRequest2.prototype.supportsSynch=function supportsSynch(){return true};XmlHttpRequest2.prototype.preloadFile=function preloadFile(path$$1,buffer$$1){var inode=this._index.getInode(path$$1);if(isFileInode(inode)){if(inode===null){throw ApiError.ENOENT(path$$1)}var stats=inode.getData();stats.size=buffer$$1.length;stats.fileData=buffer$$1}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.stat=function stat(path$$1,isLstat,cb){var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){this._requestFileSizeAsync(path$$1,function(e,size){if(e){return cb(e)}stats.size=size;cb(null,stats.clone())})}else{cb(null,stats.clone())}}else if(isDirInode(inode)){stats=inode.getStats();cb(null,stats)}else{cb(ApiError.FileError(ErrorCode.EINVAL,path$$1))}};XmlHttpRequest2.prototype.statSync=function statSync(path$$1,isLstat){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){stats.size=this._requestFileSizeSync(path$$1)}}else if(isDirInode(inode)){stats=inode.getStats()}else{throw ApiError.FileError(ErrorCode.EINVAL,path$$1)}return stats};XmlHttpRequest2.prototype.open=function open(path$$1,flags,mode,cb){if(flags.isWriteable()){return cb(new ApiError(ErrorCode.EPERM,path$$1))}var self2=this;var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:return cb(ApiError.EEXIST(path$$1));case ActionType.NOP:if(stats.fileData){return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),stats.fileData))}this._requestFileAsync(path$$1,"buffer",function(err,buffer$$1){if(err){return cb(err)}stats.size=buffer$$1.length;stats.fileData=buffer$$1;return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),buffer$$1))});break;default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileMode object."))}}else{return cb(ApiError.EISDIR(path$$1))}};XmlHttpRequest2.prototype.openSync=function openSync(path$$1,flags,mode){if(flags.isWriteable()){throw new ApiError(ErrorCode.EPERM,path$$1)}var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:throw ApiError.EEXIST(path$$1);case ActionType.NOP:if(stats.fileData){return new NoSyncFile(this,path$$1,flags,stats.clone(),stats.fileData)}var buffer$$1=this._requestFileSync(path$$1,"buffer");stats.size=buffer$$1.length;stats.fileData=buffer$$1;return new NoSyncFile(this,path$$1,flags,stats.clone(),buffer$$1);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileMode object.")}}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.readdir=function readdir(path$$1,cb){try{cb(null,this.readdirSync(path$$1))}catch(e){cb(e)}};XmlHttpRequest2.prototype.readdirSync=function readdirSync(path$$1){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}else if(isDirInode(inode)){return inode.getListing()}else{throw ApiError.ENOTDIR(path$$1)}};XmlHttpRequest2.prototype.readFile=function readFile2(fname,encoding,flag,cb){var oldCb=cb;this.open(fname,flag,420,function(err,fd){if(err){return cb(err)}cb=function(err2,arg){fd.close(function(err22){if(!err2){err2=err22}return oldCb(err2,arg)})};var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){cb(err,copyingSlice(fdBuff))}else{tryToString(fdBuff,encoding,cb)}})};XmlHttpRequest2.prototype.readFileSync=function readFileSync(fname,encoding,flag){var fd=this.openSync(fname,flag,420);try{var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){return copyingSlice(fdBuff)}return fdBuff.toString(encoding)}finally{fd.closeSync()}};XmlHttpRequest2.prototype.getXhrPath=function getXhrPath(filePath){if(filePath.charAt(0)==="/"){filePath=filePath.slice(1)}return this.prefixUrl+filePath};XmlHttpRequest2.prototype._requestFileAsync=function _requestFileAsync(p,type,cb){asyncDownloadFile(this.getXhrPath(p),type,cb)};XmlHttpRequest2.prototype._requestFileSync=function _requestFileSync(p,type){return syncDownloadFile(this.getXhrPath(p),type)};XmlHttpRequest2.prototype._requestFileSizeAsync=function _requestFileSizeAsync(path$$1,cb){getFileSizeAsync(this.getXhrPath(path$$1),cb)};XmlHttpRequest2.prototype._requestFileSizeSync=function _requestFileSizeSync(path$$1){return getFileSizeSync(this.getXhrPath(path$$1))};return XmlHttpRequest2}(BaseFileSystem);XmlHttpRequest.Name="XmlHttpRequest";XmlHttpRequest.Options={index:{type:["string","object"],optional:true,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:true,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var ExtendedASCII=function ExtendedASCII2(){};ExtendedASCII.str2byte=function str2byte(str,buf){var length=str.length>buf.length?buf.length:str.length;for(var i2=0;i2127){var charIdx=ExtendedASCII.extendedChars.indexOf(str.charAt(i2));if(charIdx>-1){charCode=charIdx+128}}buf[charCode]=i2}return length};ExtendedASCII.byte2str=function byte2str(buff){var chars=new Array(buff.length);for(var i2=0;i2127){chars[i2]=ExtendedASCII.extendedChars[charCode-128]}else{chars[i2]=String.fromCharCode(charCode)}}return chars.join("")};ExtendedASCII.byteLength=function byteLength(str){return str.length};ExtendedASCII.extendedChars=["\xC7","\xFC","\xE9","\xE2","\xE4","\xE0","\xE5","\xE7","\xEA","\xEB","\xE8","\xEF","\xEE","\xEC","\xC4","\xC5","\xC9","\xE6","\xC6","\xF4","\xF6","\xF2","\xFB","\xF9","\xFF","\xD6","\xDC","\xF8","\xA3","\xD8","\xD7","\u0192","\xE1","\xED","\xF3","\xFA","\xF1","\xD1","\xAA","\xBA","\xBF","\xAE","\xAC","\xBD","\xBC","\xA1","\xAB","\xBB","_","_","_","\xA6","\xA6","\xC1","\xC2","\xC0","\xA9","\xA6","\xA6","+","+","\xA2","\xA5","+","+","-","-","+","-","+","\xE3","\xC3","+","+","-","-","\xA6","-","+","\xA4","\xF0","\xD0","\xCA","\xCB","\xC8","i","\xCD","\xCE","\xCF","+","+","_","_","\xA6","\xCC","_","\xD3","\xDF","\xD4","\xD2","\xF5","\xD5","\xB5","\xFE","\xDE","\xDA","\xDB","\xD9","\xFD","\xDD","\xAF","\xB4","\xAD","\xB1","_","\xBE","\xB6","\xA7","\xF7","\xB8","\xB0","\xA8","\xB7","\xB9","\xB3","\xB2","_"," "];var inflateRaw=__webpack_require__(31).inflateRaw;var decompressionMethods={};var ExternalFileAttributeType;(function(ExternalFileAttributeType2){ExternalFileAttributeType2[ExternalFileAttributeType2["MSDOS"]=0]="MSDOS";ExternalFileAttributeType2[ExternalFileAttributeType2["AMIGA"]=1]="AMIGA";ExternalFileAttributeType2[ExternalFileAttributeType2["OPENVMS"]=2]="OPENVMS";ExternalFileAttributeType2[ExternalFileAttributeType2["UNIX"]=3]="UNIX";ExternalFileAttributeType2[ExternalFileAttributeType2["VM_CMS"]=4]="VM_CMS";ExternalFileAttributeType2[ExternalFileAttributeType2["ATARI_ST"]=5]="ATARI_ST";ExternalFileAttributeType2[ExternalFileAttributeType2["OS2_HPFS"]=6]="OS2_HPFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MAC"]=7]="MAC";ExternalFileAttributeType2[ExternalFileAttributeType2["Z_SYSTEM"]=8]="Z_SYSTEM";ExternalFileAttributeType2[ExternalFileAttributeType2["CP_M"]=9]="CP_M";ExternalFileAttributeType2[ExternalFileAttributeType2["NTFS"]=10]="NTFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MVS"]=11]="MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["VSE"]=12]="VSE";ExternalFileAttributeType2[ExternalFileAttributeType2["ACORN_RISC"]=13]="ACORN_RISC";ExternalFileAttributeType2[ExternalFileAttributeType2["VFAT"]=14]="VFAT";ExternalFileAttributeType2[ExternalFileAttributeType2["ALT_MVS"]=15]="ALT_MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["BEOS"]=16]="BEOS";ExternalFileAttributeType2[ExternalFileAttributeType2["TANDEM"]=17]="TANDEM";ExternalFileAttributeType2[ExternalFileAttributeType2["OS_400"]=18]="OS_400";ExternalFileAttributeType2[ExternalFileAttributeType2["OSX"]=19]="OSX"})(ExternalFileAttributeType||(ExternalFileAttributeType={}));var CompressionMethod;(function(CompressionMethod2){CompressionMethod2[CompressionMethod2["STORED"]=0]="STORED";CompressionMethod2[CompressionMethod2["SHRUNK"]=1]="SHRUNK";CompressionMethod2[CompressionMethod2["REDUCED_1"]=2]="REDUCED_1";CompressionMethod2[CompressionMethod2["REDUCED_2"]=3]="REDUCED_2";CompressionMethod2[CompressionMethod2["REDUCED_3"]=4]="REDUCED_3";CompressionMethod2[CompressionMethod2["REDUCED_4"]=5]="REDUCED_4";CompressionMethod2[CompressionMethod2["IMPLODE"]=6]="IMPLODE";CompressionMethod2[CompressionMethod2["DEFLATE"]=8]="DEFLATE";CompressionMethod2[CompressionMethod2["DEFLATE64"]=9]="DEFLATE64";CompressionMethod2[CompressionMethod2["TERSE_OLD"]=10]="TERSE_OLD";CompressionMethod2[CompressionMethod2["BZIP2"]=12]="BZIP2";CompressionMethod2[CompressionMethod2["LZMA"]=14]="LZMA";CompressionMethod2[CompressionMethod2["TERSE_NEW"]=18]="TERSE_NEW";CompressionMethod2[CompressionMethod2["LZ77"]=19]="LZ77";CompressionMethod2[CompressionMethod2["WAVPACK"]=97]="WAVPACK";CompressionMethod2[CompressionMethod2["PPMD"]=98]="PPMD"})(CompressionMethod||(CompressionMethod={}));function msdos2date(time,date){var day=date&31;var month=(date>>5&15)-1;var year=(date>>9)+1980;var second=time&31;var minute=time>>5&63;var hour=time>>11;return new Date(year,month,day,hour,minute,second)}function safeToString(buff,useUTF8,start,length){if(length===0){return""}else if(useUTF8){return buff.toString("utf8",start,start+length)}else{return ExtendedASCII.byte2str(buff.slice(start,start+length))}}var FileHeader=function FileHeader2(data){this.data=data;if(data.readUInt32LE(0)!==67324752){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))}};FileHeader.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(4)};FileHeader.prototype.flags=function flags(){return this.data.readUInt16LE(6)};FileHeader.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(8)};FileHeader.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(10),this.data.readUInt16LE(12))};FileHeader.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(10)};FileHeader.prototype.crc32=function crc32(){return this.data.readUInt32LE(14)};FileHeader.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(26)};FileHeader.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(28)};FileHeader.prototype.fileName=function fileName(){return safeToString(this.data,this.useUTF8(),30,this.fileNameLength())};FileHeader.prototype.extraField=function extraField(){var start=30+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};FileHeader.prototype.totalSize=function totalSize(){return 30+this.fileNameLength()+this.extraFieldLength()};FileHeader.prototype.useUTF8=function useUTF8(){return(this.flags()&2048)===2048};var FileData=function FileData2(header,record,data){this.header=header;this.record=record;this.data=data};FileData.prototype.decompress=function decompress(){var compressionMethod=this.header.compressionMethod();var fcn=decompressionMethods[compressionMethod];if(fcn){return fcn(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag())}else{var name=CompressionMethod[compressionMethod];if(!name){name="Unknown: "+compressionMethod}throw new ApiError(ErrorCode.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+name)}};FileData.prototype.getHeader=function getHeader(){return this.header};FileData.prototype.getRecord=function getRecord(){return this.record};FileData.prototype.getRawData=function getRawData(){return this.data};var DataDescriptor=function DataDescriptor2(data){this.data=data};DataDescriptor.prototype.crc32=function crc32(){return this.data.readUInt32LE(0)};DataDescriptor.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(4)};DataDescriptor.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(8)};var ArchiveExtraDataRecord=function ArchiveExtraDataRecord2(data){this.data=data;if(this.data.readUInt32LE(0)!==134630224){throw new ApiError(ErrorCode.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))}};ArchiveExtraDataRecord.prototype.length=function length(){return this.data.readUInt32LE(4)};ArchiveExtraDataRecord.prototype.extraFieldData=function extraFieldData(){return this.data.slice(8,8+this.length())};var DigitalSignature=function DigitalSignature2(data){this.data=data;if(this.data.readUInt32LE(0)!==84233040){throw new ApiError(ErrorCode.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))}};DigitalSignature.prototype.size=function size(){return this.data.readUInt16LE(4)};DigitalSignature.prototype.signatureData=function signatureData(){return this.data.slice(6,6+this.size())};var CentralDirectory=function CentralDirectory2(zipData,data){this.zipData=zipData;this.data=data;if(this.data.readUInt32LE(0)!==33639248){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0))}this._filename=this.produceFilename()};CentralDirectory.prototype.versionMadeBy=function versionMadeBy(){return this.data.readUInt16LE(4)};CentralDirectory.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(6)};CentralDirectory.prototype.flag=function flag(){return this.data.readUInt16LE(8)};CentralDirectory.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(10)};CentralDirectory.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(12),this.data.readUInt16LE(14))};CentralDirectory.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(12)};CentralDirectory.prototype.crc32=function crc32(){return this.data.readUInt32LE(16)};CentralDirectory.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(20)};CentralDirectory.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(24)};CentralDirectory.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(28)};CentralDirectory.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(30)};CentralDirectory.prototype.fileCommentLength=function fileCommentLength(){return this.data.readUInt16LE(32)};CentralDirectory.prototype.diskNumberStart=function diskNumberStart(){return this.data.readUInt16LE(34)};CentralDirectory.prototype.internalAttributes=function internalAttributes(){return this.data.readUInt16LE(36)};CentralDirectory.prototype.externalAttributes=function externalAttributes(){return this.data.readUInt32LE(38)};CentralDirectory.prototype.headerRelativeOffset=function headerRelativeOffset(){return this.data.readUInt32LE(42)};CentralDirectory.prototype.produceFilename=function produceFilename(){var fileName=safeToString(this.data,this.useUTF8(),46,this.fileNameLength());return fileName.replace(/\\/g,"/")};CentralDirectory.prototype.fileName=function fileName(){return this._filename};CentralDirectory.prototype.rawFileName=function rawFileName(){return this.data.slice(46,46+this.fileNameLength())};CentralDirectory.prototype.extraField=function extraField(){var start=44+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};CentralDirectory.prototype.fileComment=function fileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return safeToString(this.data,this.useUTF8(),start,this.fileCommentLength())};CentralDirectory.prototype.rawFileComment=function rawFileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(start,start+this.fileCommentLength())};CentralDirectory.prototype.totalSize=function totalSize(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()};CentralDirectory.prototype.isDirectory=function isDirectory(){var fileName=this.fileName();return(this.externalAttributes()&16?true:false)||fileName.charAt(fileName.length-1)==="/"};CentralDirectory.prototype.isFile=function isFile(){return!this.isDirectory()};CentralDirectory.prototype.useUTF8=function useUTF8(){return(this.flag()&2048)===2048};CentralDirectory.prototype.isEncrypted=function isEncrypted(){return(this.flag()&1)===1};CentralDirectory.prototype.getFileData=function getFileData(){var start=this.headerRelativeOffset();var header=new FileHeader(this.zipData.slice(start));return new FileData(header,this,this.zipData.slice(start+header.totalSize()))};CentralDirectory.prototype.getData=function getData(){return this.getFileData().decompress()};CentralDirectory.prototype.getRawData=function getRawData(){return this.getFileData().getRawData()};CentralDirectory.prototype.getStats=function getStats(){return new Stats(FileType.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var EndOfCentralDirectory=function EndOfCentralDirectory2(data){this.data=data;if(this.data.readUInt32LE(0)!==101010256){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))}};EndOfCentralDirectory.prototype.diskNumber=function diskNumber(){return this.data.readUInt16LE(4)};EndOfCentralDirectory.prototype.cdDiskNumber=function cdDiskNumber(){return this.data.readUInt16LE(6)};EndOfCentralDirectory.prototype.cdDiskEntryCount=function cdDiskEntryCount(){return this.data.readUInt16LE(8)};EndOfCentralDirectory.prototype.cdTotalEntryCount=function cdTotalEntryCount(){return this.data.readUInt16LE(10)};EndOfCentralDirectory.prototype.cdSize=function cdSize(){return this.data.readUInt32LE(12)};EndOfCentralDirectory.prototype.cdOffset=function cdOffset(){return this.data.readUInt32LE(16)};EndOfCentralDirectory.prototype.cdZipCommentLength=function cdZipCommentLength(){return this.data.readUInt16LE(20)};EndOfCentralDirectory.prototype.cdZipComment=function cdZipComment(){return safeToString(this.data,true,22,this.cdZipCommentLength())};EndOfCentralDirectory.prototype.rawCdZipComment=function rawCdZipComment(){return this.data.slice(22,22+this.cdZipCommentLength())};var ZipTOC=function ZipTOC2(index,directoryEntries,eocd,data){this.index=index;this.directoryEntries=directoryEntries;this.eocd=eocd;this.data=data};var ZipFS=function(SynchronousFileSystem$$1){function ZipFS2(input,name,deprecateMsg){if(name===void 0)name="";if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this.name=name;this._index=new FileIndex;this._directoryEntries=[];this._eocd=null;deprecationMessage(deprecateMsg,ZipFS2.Name,{zipData:"zip data as a Buffer",name});if(input instanceof ZipTOC){this._index=input.index;this._directoryEntries=input.directoryEntries;this._eocd=input.eocd;this.data=input.data}else{this.data=input;this.populateIndex()}}if(SynchronousFileSystem$$1)ZipFS2.__proto__=SynchronousFileSystem$$1;ZipFS2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);ZipFS2.prototype.constructor=ZipFS2;ZipFS2.Create=function Create(opts,cb){try{ZipFS2.computeIndex(opts.zipData,function(zipTOC){var fs4=new ZipFS2(zipTOC,opts.name,false);cb(null,fs4)},false)}catch(e){cb(e)}};ZipFS2.isAvailable=function isAvailable(){return true};ZipFS2.RegisterDecompressionMethod=function RegisterDecompressionMethod(m,fcn){decompressionMethods[m]=fcn};ZipFS2.computeIndex=function computeIndex(data,cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.")}var index=new FileIndex;var eocd=ZipFS2.getEOCD(data);if(eocd.diskNumber()!==eocd.cdDiskNumber()){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support spanned zip files.")}var cdPtr=eocd.cdOffset();if(cdPtr===4294967295){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support Zip64.")}var cdEnd=cdPtr+eocd.cdSize();ZipFS2.computeIndexResponsive(data,index,cdPtr,cdEnd,cb,[],eocd)};ZipFS2.getEOCD=function getEOCD(data){var startOffset=22;var endOffset=Math.min(startOffset+65535,data.length-1);for(var i2=startOffset;i2-1};DirectoryRecord.prototype.getRockRidgeOffset=function getRockRidgeOffset(){return this._rockRidgeOffset};DirectoryRecord.prototype.rootCheckForRockRidge=function rootCheckForRockRidge(isoData){var dir2=this.getDirectory(isoData);this._rockRidgeOffset=dir2.getDotEntry(isoData)._getRockRidgeOffset(isoData);if(this._rockRidgeOffset>-1){this._fileOrDir=null}};DirectoryRecord.prototype.length=function length(){return this._data[0]};DirectoryRecord.prototype.extendedAttributeRecordLength=function extendedAttributeRecordLength(){return this._data[1]};DirectoryRecord.prototype.lba=function lba(){return this._data.readUInt32LE(2)*2048};DirectoryRecord.prototype.dataLength=function dataLength(){return this._data.readUInt32LE(10)};DirectoryRecord.prototype.recordingDate=function recordingDate(){return getShortFormDate(this._data,18)};DirectoryRecord.prototype.fileFlags=function fileFlags(){return this._data[25]};DirectoryRecord.prototype.fileUnitSize=function fileUnitSize(){return this._data[26]};DirectoryRecord.prototype.interleaveGapSize=function interleaveGapSize(){return this._data[27]};DirectoryRecord.prototype.volumeSequenceNumber=function volumeSequenceNumber(){return this._data.readUInt16LE(28)};DirectoryRecord.prototype.identifier=function identifier(){return this._getString(33,this._data[32])};DirectoryRecord.prototype.fileName=function fileName(isoData){if(this.hasRockRidge()){var fn=this._rockRidgeFilename(isoData);if(fn!==null){return fn}}var ident=this.identifier();if(this.isDirectory(isoData)){return ident}var versionSeparator=ident.indexOf(";");if(versionSeparator===-1){return ident}else if(ident[versionSeparator-1]==="."){return ident.slice(0,versionSeparator-1)}else{return ident.slice(0,versionSeparator)}};DirectoryRecord.prototype.isDirectory=function isDirectory(isoData){var rv=!!(this.fileFlags()&2);if(!rv&&this.hasRockRidge()){rv=this.getSUEntries(isoData).filter(function(e){return e instanceof CLEntry}).length>0}return rv};DirectoryRecord.prototype.isSymlink=function isSymlink(isoData){return this.hasRockRidge()&&this.getSUEntries(isoData).filter(function(e){return e instanceof SLEntry}).length>0};DirectoryRecord.prototype.getSymlinkPath=function getSymlinkPath(isoData){var p="";var entries=this.getSUEntries(isoData);var getStr=this._getGetString();for(var i2=0,list2=entries;i21&&p[p.length-1]==="/"){return p.slice(0,p.length-1)}else{return p}};DirectoryRecord.prototype.getFile=function getFile(isoData){if(this.isDirectory(isoData)){throw new Error("Tried to get a File from a directory.")}if(this._fileOrDir===null){this._fileOrDir=isoData.slice(this.lba(),this.lba()+this.dataLength())}return this._fileOrDir};DirectoryRecord.prototype.getDirectory=function getDirectory(isoData){if(!this.isDirectory(isoData)){throw new Error("Tried to get a Directory from a file.")}if(this._fileOrDir===null){this._fileOrDir=this._constructDirectory(isoData)}return this._fileOrDir};DirectoryRecord.prototype.getSUEntries=function getSUEntries(isoData){if(!this._suEntries){this._constructSUEntries(isoData)}return this._suEntries};DirectoryRecord.prototype._rockRidgeFilename=function _rockRidgeFilename(isoData){var nmEntries=this.getSUEntries(isoData).filter(function(e2){return e2 instanceof NMEntry});if(nmEntries.length===0||nmEntries[0].flags()&(2|4)){return null}var str="";var getString=this._getGetString();for(var i2=0,list2=nmEntries;i20){var spEntry=suEntries[0];if(spEntry instanceof SPEntry&&spEntry.checkBytesPass()){for(var i2=1;i2K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer2.prototype;return buf}function Buffer2(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer2[Symbol.species]===Buffer2){Object.defineProperty(Buffer2,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer2.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer2.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer2.prototype.__proto__=Uint8Array.prototype;Buffer2.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==void 0){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer2.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer2.allocUnsafe=function(size){return allocUnsafe(size)};Buffer2.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer2.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer2.alloc(+length)}Buffer2.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer2.compare=function compare(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer2.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===void 0||start<0){start=0}if(start>this.length){return""}if(end===void 0||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer2.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer2.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer2.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer2.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===void 0){start=0}if(end===void 0){end=target?target.length:0}if(thisStart===void 0){thisStart=0}if(thisEnd===void 0){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir2?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir2)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir2)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer2.from(val,encoding)}if(Buffer2.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir2)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir2){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir2)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir2){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==void 0){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i2){if(indexSize===1){return buf[i2]}else{return buf.readUInt16BE(i2*indexSize)}}var i;if(dir2){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===void 0)encoding="utf8"}else{encoding=length;length=void 0}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===void 0||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer2.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer2.prototype.readUIntLE=function readUIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){checkOffset(offset,byteLength2,this.length)}var val=this[offset+--byteLength2];var mul=1;while(byteLength2>0&&(mul*=256)){val+=this[offset+--byteLength2]*mul}return val};Buffer2.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer2.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer2.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer2.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer2.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer2.prototype.readIntLE=function readIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readIntBE=function readIntBE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var i=byteLength2;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer2.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer2.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer2.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer2.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer2.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer2.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer2.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer2.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var i=byteLength2-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength2};Buffer2.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer2.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer2.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer2.prototype.writeIntLE=function writeIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeIntBE=function writeIntBE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=byteLength2-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer2.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer2.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer2.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer2.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer2.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer2.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer2.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i>>0;end=end===void 0?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}}).call(exports2,__webpack_require__(1))},function(module2,exports2){"use strict";exports2.byteLength=byteLength;exports2.toByteArray=toByteArray;exports2.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len2-2]==="="?2:b64[len2-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i2,j,l,tmp,placeHolders,arr;var len2=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len2*3/4-placeHolders);l=placeHolders>0?len2-4:len2;var L=0;for(i2=0,j=0;i2>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i2=start;i2len22?len22:i2+maxChunkLength))}if(extraBytes===1){tmp=uint8[len2-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len2-2]<<8)+uint8[len2-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},function(module2,exports2){exports2.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports2.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},function(module2,exports2){module2.exports=function(module3){if(!module3.webpackPolyfill){module3.deprecate=function(){};module3.paths=[];module3.children=[];module3.webpackPolyfill=1}return module3}},function(module2,exports2,__webpack_require__){"use strict";var Process=__webpack_require__(7);var process=new Process,processProxy={};function defineKey(key2){if(processProxy[key2]){return}if(typeof process[key2]==="function"){processProxy[key2]=function(){return process[key2].apply(process,arguments)}}else{processProxy[key2]=process[key2]}}for(var key in process){defineKey(key)}processProxy.initializeTTYs=function(){if(process.stdin===null){process.initializeTTYs();processProxy.stdin=process.stdin;processProxy.stdout=process.stdout;processProxy.stderr=process.stderr}};process.nextTick(function(){processProxy.initializeTTYs()});module2.exports=processProxy},function(module2,exports2,__webpack_require__){(function(__dirname){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var events=__webpack_require__(8);var path=null;var Item=function(){function Item2(fun,array){this.fun=fun;this.array=array}Item2.prototype.run=function(){this.fun.apply(null,this.array)};return Item2}();var NextTickQueue=function(){function NextTickQueue2(){this._queue=[];this._draining=false;this._currentQueue=null;this._queueIndex=-1}NextTickQueue2.prototype.push=function(item){var _this=this;if(this._queue.push(item)===1&&!this._draining){setTimeout(function(){return _this._drainQueue()},0)}};NextTickQueue2.prototype._cleanUpNextTick=function(){this._draining=false;if(this._currentQueue&&this._currentQueue.length){this._queue=this._currentQueue.concat(this._queue)}else{this._queueIndex=-1}if(this._queue.length){this._drainQueue()}};NextTickQueue2.prototype._drainQueue=function(){var _this=this;if(this._draining){return}var timeout=setTimeout(function(){return _this._cleanUpNextTick()});this._draining=true;var len=this._queue.length;while(len){this._currentQueue=this._queue;this._queue=[];while(++this._queueIndex0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module2,exports2,__webpack_require__){(function(process){"use strict";var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;function posixSplitPath(filename){var out=splitPathRe.exec(filename);out.shift();return out}var path=function(){function path2(){}path2.normalize=function(p){if(p===""){p="."}var absolute=p.charAt(0)===path2.sep;p=path2._removeDuplicateSeps(p);var components=p.split(path2.sep);var goodComponents=[];for(var idx=0;idx0&&goodComponents[0]!=="..")){goodComponents.pop()}else{goodComponents.push(c)}}if(!absolute&&goodComponents.length<2){switch(goodComponents.length){case 1:if(goodComponents[0]===""){goodComponents.unshift(".")}break;default:goodComponents.push(".")}}p=goodComponents.join(path2.sep);if(absolute&&p.charAt(0)!==path2.sep){p=path2.sep+p}return p};path2.join=function(){var paths=[];for(var _i=0;_i1&&resolved.charAt(resolved.length-1)===path2.sep){return resolved.substr(0,resolved.length-1)}if(resolved.charAt(0)!==path2.sep){if(resolved.charAt(0)==="."&&(resolved.length===1||resolved.charAt(1)===path2.sep)){resolved=resolved.length===1?"":resolved.substr(2)}var cwd=process.cwd();if(resolved!==""){resolved=this.normalize(cwd+(cwd!=="/"?path2.sep:"")+resolved)}else{resolved=cwd}}return resolved};path2.relative=function(from,to){var i;from=path2.resolve(from);to=path2.resolve(to);var fromSegs=from.split(path2.sep);var toSegs=to.split(path2.sep);toSegs.shift();fromSegs.shift();var upCount=0;var downSegs=[];for(i=0;ifromSegs.length){upCount=fromSegs.length}var rv="";for(i=0;i1&&rv.charAt(rv.length-1)===path2.sep){rv=rv.substr(0,rv.length-1)}return rv};path2.dirname=function(p){p=path2._removeDuplicateSeps(p);var absolute=p.charAt(0)===path2.sep;var sections=p.split(path2.sep);if(sections.pop()===""&§ions.length>0){sections.pop()}if(sections.length>1||sections.length===1&&!absolute){return sections.join(path2.sep)}else if(absolute){return path2.sep}else{return"."}};path2.basename=function(p,ext){if(ext===void 0){ext=""}if(p===""){return p}p=path2.normalize(p);var sections=p.split(path2.sep);var lastPart=sections[sections.length-1];if(lastPart===""&§ions.length>1){return sections[sections.length-2]}if(ext.length>0){var lastPartExt=lastPart.substr(lastPart.length-ext.length);if(lastPartExt===ext){return lastPart.substr(0,lastPart.length-ext.length)}}return lastPart};path2.extname=function(p){p=path2.normalize(p);var sections=p.split(path2.sep);p=sections.pop();if(p===""&§ions.length>0){p=sections.pop()}if(p===".."){return""}var i=p.lastIndexOf(".");if(i===-1||i===0){return""}return p.substr(i)};path2.isAbsolute=function(p){return p.length>0&&p.charAt(0)===path2.sep};path2._makeLong=function(p){return p};path2.parse=function(p){var allParts=posixSplitPath(p);return{root:allParts[0],dir:allParts[0]+allParts[1].slice(0,-1),base:allParts[2],ext:allParts[3],name:allParts[2].slice(0,allParts[2].length-allParts[3].length)}};path2.format=function(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof pathObject)}var root=pathObject.root||"";if(typeof root!=="string"){throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof pathObject.root)}var dir2=pathObject.dir?pathObject.dir+path2.sep:"";var base=pathObject.base||"";return dir2+base};path2._removeDuplicateSeps=function(p){p=p.replace(this._replaceRegex,this.sep);return p};path2.sep="/";path2._replaceRegex=new RegExp("//+","g");path2.delimiter=":";path2.posix=path2;path2.win32=path2;return path2}();var _=path;module2.exports=path}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(Buffer2){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var stream=__webpack_require__(11);var TTY=function(_super){__extends(TTY2,_super);function TTY2(){_super.call(this);this.isRaw=false;this.columns=80;this.rows=120;this.isTTY=true;this._bufferedWrites=[];this._waitingForWrites=false}TTY2.prototype.setRawMode=function(mode){if(this.isRaw!==mode){this.isRaw=mode;this.emit("modeChange")}};TTY2.prototype.changeColumns=function(columns){if(columns!==this.columns){this.columns=columns;this.emit("resize")}};TTY2.prototype.changeRows=function(rows){if(rows!==this.rows){this.rows=rows;this.emit("resize")}};TTY2.isatty=function(fd){return fd&&fd instanceof TTY2};TTY2.prototype._write=function(chunk,encoding,cb){var error;try{var data;if(typeof chunk==="string"){data=new Buffer2(chunk,encoding)}else{data=chunk}this._bufferedWrites.push(data);if(this._waitingForWrites){this._read(1024)}}catch(e){error=e}finally{cb(error)}};TTY2.prototype._read=function(size){if(this._bufferedWrites.length===0){this._waitingForWrites=true}else{while(this._bufferedWrites.length>0){this._waitingForWrites=this.push(this._bufferedWrites.shift());if(!this._waitingForWrites){break}}}};return TTY2}(stream.Duplex);module2.exports=TTY}).call(exports2,__webpack_require__(1))},function(module2,exports2,__webpack_require__){module2.exports=Stream;var EE=__webpack_require__(8).EventEmitter;var inherits=__webpack_require__(12);inherits(Stream,EE);Stream.Readable=__webpack_require__(13);Stream.Writable=__webpack_require__(27);Stream.Duplex=__webpack_require__(28);Stream.Transform=__webpack_require__(29);Stream.PassThrough=__webpack_require__(30);Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},function(module2,exports2){if(typeof Object.create==="function"){module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},function(module2,exports2,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(11)}catch(_){}}();exports2=module2.exports=__webpack_require__(14);exports2.Stream=Stream||exports2;exports2.Readable=exports2;exports2.Writable=__webpack_require__(22);exports2.Duplex=__webpack_require__(21);exports2.Transform=__webpack_require__(25);exports2.PassThrough=__webpack_require__(26);if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module2.exports=Stream}}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(process){"use strict";module2.exports=Readable;var processNextTick=__webpack_require__(15);var isArray=__webpack_require__(16);var Duplex;Readable.ReadableState=ReadableState;var EE=__webpack_require__(8).EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var debugUtil=__webpack_require__(19);var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=__webpack_require__(20);var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=__webpack_require__(24).StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||__webpack_require__(21);if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer2.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;iMAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===void 0){enc=void 0;_fill=0}var buf=new Buffer2(size);if(typeof _fill==="string"){var fillBuf=new Buffer2(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer2(size)};exports2.from=function from(value,encodingOrOffset,length){if(typeof Buffer2.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer2.from)){return Buffer2.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer2(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer2(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer2(value.slice(offset,offset+len))}if(Buffer2.isBuffer(value)){var out=new Buffer2(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer2(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer2(value.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")};exports2.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer2.allocUnsafeSlow==="function"){return Buffer2.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(exports2,function(){return this}())},function(module2,exports2,__webpack_require__){(function(Buffer2){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports2.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports2.isBoolean=isBoolean;function isNull(arg){return arg===null}exports2.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports2.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports2.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports2.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports2.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports2.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports2.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports2.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports2.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports2.isError=isError;function isFunction(arg){return typeof arg==="function"}exports2.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports2.isPrimitive=isPrimitive;exports2.isBuffer=Buffer2.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(exports2,__webpack_require__(1))},function(module2,exports2){},function(module2,exports2,__webpack_require__){"use strict";var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);module2.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},function(module2,exports2,__webpack_require__){"use strict";var objectKeys=Object.keys||function(obj){var keys2=[];for(var key in obj){keys2.push(key)}return keys2};module2.exports=Duplex;var processNextTick=__webpack_require__(15);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var Readable=__webpack_require__(14);var Writable=__webpack_require__(22);util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var internalUtil={deprecate:__webpack_require__(23)};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||__webpack_require__(21);if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer2.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer2.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},function(module2,exports2,__webpack_require__){"use strict";module2.exports=Transform;var Duplex=__webpack_require__(21);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==void 0)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg||msg[inflator.err]}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports2.Inflate=Inflate;exports2.inflate=inflate;exports2.inflateRaw=inflateRaw;exports2.ungzip=inflate},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var adler32=__webpack_require__(34);var crc32=__webpack_require__(35);var inflate_fast=__webpack_require__(36);var inflate_table=__webpack_require__(37);var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&©>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module2.exports=adler32},function(module2,exports2){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255]}return crc^-1}module2.exports=crc32},function(module2,exports2){"use strict";var BAD=30;var TYPE=12;module2.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits>>=op;bits-=op}if(bits<15){hold+=input[_in++]<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bitsdmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3;_in-=len;bits-=len<<3;hold&=(1<=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}for(;;){here_bits=len-drop;if(work[sym]end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports2.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports2.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},function(module2,exports2){"use strict";module2.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(module2,exports2){"use strict";module2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(module2,exports2){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module2.exports=ZStream},function(module2,exports2){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module2.exports=GZheader}])})}});var CSV=class{constructor(onOpen=this.onOpen,saveButtonId=null,openButtonId=null){this.onOpen=onOpen;this.notes=[{idx:0,text:"comment"}];if(saveButtonId!==null){document.getElementById(saveButtonId).addEventListener("click",this.saveCSV)}if(openButtonId!==null){document.getElementById(openButtonId).addEventListener("click",this.openCSV)}}processArraysForCSV(data=["1|2|3","3|2|1"],delimiter="|",header="a,b,c",saveNotes=false){let csvDat=header+"\n";let noteIdx=0;data.forEach((line,i)=>{if(data[i]==="string"&&delimiter!==","){csvDat+=line.split(delimiter).join(",")}else{csvData+=line.join(",")}if(saveNotes===true){if(this.notes[noteIdx].idx===i){line+=this.notes[noteIdx].text;noteIdx++}}if(line.indexOf("\n")<0){csvDat+="\n"}});return csvDat}static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){var hiddenElement=document.createElement("a");hiddenElement.href="data:text/csv;charset=utf-8,"+encodeURI(csvDat);hiddenElement.target="_blank";if(name!==""){hiddenElement.download=name}else{hiddenElement.download=Date().toISOString()}hiddenElement.click()}static openCSV(delimiter=",",onOpen=(csvDat,header,path)=>{return csvDat,header,path}){var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;var tempcsvArr=tempcsvData.split("\n");let header=[];var csvDat=[];tempcsvArr.pop();tempcsvArr.forEach((row,i)=>{if(i==0){header=row.split(delimiter)}else{var temp=row.split(delimiter);csvDat.push(temp)}});onOpen(csvDat,header,input.value);input.value=""};reader.readAsText(file)};input.click()}static openCSVRaw(onOpen=(csvDat,path)=>{return csvDat,path}){var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;onOpen(tempcsvData,input.value);input.value=""};reader.readAsText(file)};input.click()}onOpen(csvDat=[],header=[]){console.log("CSV Opened!",header,csvDat)}};var parseCSVData=(data,filename,head,hasend=true,parser=(lines,filename2,head2)=>{let result={filename:filename2};let header=head2;if(typeof head2==="string")header=head2.split(",");result.header=header;for(let i=0;i{let lines=data.split("\n");if(!head)head=lines[0];lines.shift();if(hasend===false)lines.pop();let result=parser(lines,filename,head);return result};function toISOLocal(d){d=new Date(d);var z=n=>("0"+n).slice(-2);var zz=n=>("00"+n).slice(-3);var off=d.getTimezoneOffset();var sign=off<0?"+":"-";off=Math.abs(off);return d.getFullYear()+"-"+z(d.getMonth()+1)+"-"+z(d.getDate())+"T"+z(d.getHours())+":"+z(d.getMinutes())+":"+z(d.getSeconds())+"."+zz(d.getMilliseconds())+"(UTC"+sign+z(off/60|0)+":00)"}var processDataForCSV=(options={})=>{let header="";if(typeof options.data[0]==="object"&&!Array.isArray(options.data[0])){if(options.data[0].x)header="x,";else if(options.data[0].timestamp)header="timestamp,localtime,"}let headeridx=0;let lines={};options.data.forEach((obj,i)=>{if(Array.isArray(obj)){for(let j=0;j{if(exists2)appendFile(options.filename,joined,options.dir);else appendFile(options.filename,header+joined,options.dir)})}return result};var BrowserFS=__toESM(require_browserfs());var fsInited=false;var fs2=BrowserFS.BFSRequire("fs");var BFSBuffer=BrowserFS.BFSRequire("buffer").Buffer;var initFS=async(dirs=["data"],oninit=(exists2=[])=>{},onerror=e=>{},filesystem="IndexedDB")=>{if(fsInited)return true;else{fsInited=true;return new Promise(resolve=>{let oldmfs=fs2.getRootFS();BrowserFS.FileSystem[filesystem].Create({},(e,mountableFileSystem)=>{if(e)throw e;if(!mountableFileSystem){onerror(e);throw new Error(`Error creating BrowserFS`)}BrowserFS.initialize(mountableFileSystem);let promises=[];dirs.forEach(async dir2=>{promises.push(dirExists(fs2,dir2))});Promise.all(promises).then(values=>{oninit(values);fsInited=true;resolve(true)})})})}};var exists=async(path="")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.exists("/"+path,function(exists2){resolve(exists2)})})};var readFile=async(path="data")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.readFile("/"+path,function(e,output){resolve(output)})})};async function readFileChunk(path="data",begin=0,end=5120,onread=data=>{}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);if(path!=""){return new Promise(async resolve=>{fs2.open("/"+path,"r",(e,fd)=>{if(e)throw e;fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er)throw er;if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})}else{console.error("Path name is not defined");return void 0}}var getFilenames=async(directory="data",onload=directory2=>{})=>{if(!fsInited)await initFS([directory]);else await dirExists(fs2,directory);return new Promise(resolve=>{fs2.readdir("/"+directory,(e,dir2)=>{if(e)throw e;if(dir2){onload(dir2);resolve(dir2)}else resolve(void 0)})})};var writeFile=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.writeFile("/"+path,data,err=>{if(err)throw err;onwrite(data);resolve(true)})})};var appendFile2=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.appendFile("/"+path,data,err=>{if(err)throw err;onwrite(data);resolve(true)})})};var deleteFile=async(path="data",ondelete=()=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{if(path!=""){fs2.unlink("/"+path,e=>{if(e)console.error(e);ondelete();resolve(true)})}else{console.error("Path name is not defined");resolve(false)}})};var readFileAsText=async(path="data",end="end",begin=0,onread=(data,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(async resolve=>{let size=await getFileSize(path,dir);if(end==="end"){end=size}else if(typeof end==="number"){if(end>size)end=size}fs2.open("/"+path,"r",(e,fd)=>{if(e)throw e;fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er)throw er;if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})};var listFiles=async(dir2="data",onload=directory=>{})=>{if(!fsInited)await initFS([dir2]);else await dirExists(fs2,dir2);return new Promise(resolve=>{fs2.readdir("/"+dir2,(e,directory)=>{if(e)throw e;if(directory){onload(directory)}resolve(directory)})})};var getFileSize=async(path="data",onread=size=>{console.log(size)})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.stat("/"+path,(e,stats)=>{if(e)throw e;let filesize=stats.size;onread(filesize);resolve(filesize)})})};var getCSVHeader=async(path="data",onopen=(header,filename)=>{console.log(header,filename)})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.open("/"+path,"r",(e,fd)=>{if(e)throw e;fs2.read(fd,65535,0,"utf-8",(er,output,bytesRead)=>{if(er)throw er;if(bytesRead!==0){let data=output.toString();let lines=data.split("\n");let header=lines[0];fs2.close(fd,()=>{onopen(header,path);resolve(header)})}else resolve(void 0)})})})};var writeToCSVFromDB=async(path="data",fileSizeLimitMb=10)=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{if(path!=""){fs2.stat("/"+path,(e,stats)=>{if(e)throw e;let filesize=stats.size;console.log(filesize);fs2.open(path,"r",(e2,fd)=>{if(e2)throw e2;let i=0;let maxFileSize=fileSizeLimitMb*1024*1024;let end=maxFileSize;if(filesize{if(e3)throw e3;if(bytesRead!==0)CSV.saveCSV(output.toString(),path);fs2.close(fd);resolve(true)})}else{const writeChunkToFile=async()=>{if(ifilesize){end=filesize-i}let chunk=0;fs2.read(fd,end,i,"utf-8",(e3,output,bytesRead)=>{if(e3)throw e3;if(bytesRead!==0){CSV.saveCSV(output.toString(),path+"_"+chunk);i+=maxFileSize;chunk++;writeChunkToFile();fs2.close(fd);resolve(true)}})}}}})})}else{console.error("File name is not defined.");resolve(false)}})};async function readCSVChunkFromDB(path="data",start=0,end="end"){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);let head=await getCSVHeader(path);if(head)head=head.split(",");else return void 0;let resultLengths=[];let resultNames=[];let results={};head.forEach(v=>{if(v){resultNames.push(v);resultLengths.push(1)}else resultLengths[resultLengths.length-1]++});let size=await getFileSize(path);if(end==="end")end=size;else if(end>size){start=size-(end-start);end=size}let data=await readFileChunk(path,start,end);let headeridx=0;let lastIdx=0;data.forEach((r,i)=>{let row=r.split(",");while(lastIdx{return new Promise((resolve,reject)=>{if(directories[directory]==="exists"||directories[directory]==="created"){resolve()}else{fs3.exists(`/${directory}`,exists2=>{if(exists2){directories[directory]="exists";console.log(`/${directory} exists!`);resolve()}else if(directories[directory]==="creating"){console.log(directory+" is still being created.");resolve()}else{console.log(`creating /${directory}`,fs3);directories[directory]="creating";fs3.mkdir(`/${directory}`,1,err=>{if(err){throw err}directories[directory]="created";setTimeout(resolve,500)})}})}})};var BFSRoutes={initFS,dirExists,exists,readFile,readFileChunk,getFilenames,writeFile,appendFile:appendFile2,deleteFile,readFileAsText,getFileSize,getCSVHeader,listFiles};var CSV_REFERENCE={};function lerp(v0,v1,t){return(1-t)*v0+t*v1}function interpolerp(v0,v1,fit,floor=true){if(fit<=2)return[v0,v1];let a=1/fit;let result=new Array(fit);result[0]=v0;for(let i=1;i<=fit;i++){result[i]=lerp(v0,v1,a*i);if(floor)result[i]=Math.floor(result[i])}return result}var appendCSV=async(newData,filename,header,toFixed=5)=>{if(!filename){let keys=Object.keys(CSV_REFERENCE);if(keys.length>0)filename=keys[keys.length-1];else filename=`csv${new Date().toISOString()}`}let csv=CSV_REFERENCE[filename];if(!csv){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);CSV_REFERENCE[filename]={header:header?header:["timestamp","localized",...keys],lastX:void 0,buffer:"",buffered:0,bufferSize:0,xIncrement:void 0};csv=CSV_REFERENCE[filename];header=csv.header}if(!csv.header||csv.header?.length===0){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);csv.header=header?header:["timestamp","localized",...keys]}else if(header)csv.header=header;let maxLen=1;for(const key in newData){if(csv.header.indexOf(key)>-1&&newData[key]?.length>maxLen){maxLen=newData[key]?.length}}let x;if(csv.xIncrement){if(!csv.lastX){if(typeof newData[csv.header[0]]!=="undefined"){x=newData[csv.header[0]]}else if(csv.header[0].toLowerCase().includes("time")||csv.header[0].toLowerCase().includes("unix"))x=Date.now()}else{if(newData[csv.header[2]]){if(Array.isArray(newData[csv.header[2]]))x=csv.lastX+csv.xIncrement*newData[csv.header[2]].length;else x=csv.lastX+csv.xIncrement}else if(newData[csv.header[0]]){if(Array.isArray(newData[csv.header[0]]))x=csv.lastX+csv.xIncrement*newData[csv.header[0]].length;else x=csv.lastX+csv.xIncrement}else x=csv.lastX+csv.xIncrement}}else x=newData[csv.header[0]];if(typeof csv.lastX==="undefined")csv.lastX=Array.isArray(x)?x[0]:x;if(typeof x==="undefined"){if(csv.header[0].includes("time")){let now=Date.now();if(maxLen===1)x=Date.now();else{x=interpolerp(csv.lastX,now,maxLen);x.shift()}}else{let newX=csv.lastX+1;if(maxLen>1){x=new Array(maxLen).fill("");x[maxLen-1]=newX}else x=newX}}else if(maxLen>1&&x?.length!==maxLen){if(!Array.isArray(x)||x.length===1){x=interpolerp(csv.lastX,x,maxLen);x.shift()}else{x=interpolerp(x[0],x[x.length-1],maxLen);x.shift()}}let toAppend=[];if(Array.isArray(x)){let curIdcs={};for(let i=0;icurIdcs[csv.header[j]]){curIdcs[csv.header[j]]++;toAppend[i][j]=d[curIdcs[csv.header[j]]]}else{toAppend[i][j]=""}}}}else{if(i===x.length-1){toAppend[i][j]=d}else{toAppend[i][j]=""}}if(typeof toAppend[i][j]==="number"&&Math.floor(toAppend[i][j])!==toAppend[i][j])toAppend[i][j]=toAppend[i][j].toFixed(toFixed)}}}else{toAppend.push([]);for(let j=0;j{csvProcessed+=arr.join(",")+"\n";if(csv.bufferSize)csv.buffered++});csv.lastX=toAppend[toAppend.length-1][0];if(csv.bufferSize){csv.buffer+=csvProcessed;if(csv.buffered>csv.bufferSize){let r=new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csv.buffer,written=>{res(written)})}else{appendFile2(filename,csv.buffer,written=>{res(written)})}})});await r;csv.buffer="";csv.buffered=0;return r}else return Promise.resolve(true)}else{return new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csvProcessed,written=>{res(written)})}else{appendFile2(filename,csvProcessed,written=>{res(written)})}})})}};var updateCSVHeader=(header,filename)=>{if(CSV_REFERENCE[filename]){CSV_REFERENCE[filename].header=header}};var createCSV=(filename,header,bufferSize=0,xIncrement)=>{if(header?.indexOf("timestamp")>1){header.splice(header.indexOf("timestamp"),1);header.unshift("timestamp")}if((header?.[0].toLowerCase().includes("time")||header?.[0].toLowerCase().includes("unix"))&&header[1]!=="localized"){header.splice(1,0,"localized")}CSV_REFERENCE[filename]={header,lastX:header[1]==="localized"?Date.now():0,bufferSize,buffer:"",buffered:0,xIncrement};return new Promise((res,rej)=>{writeFile(filename,CSV_REFERENCE[filename].header?CSV_REFERENCE[filename].header.join(",")+"\n":"",written=>{res(written)}).catch(rej)})};var visualizeDirectory=(dir2,parentNode=document.body)=>{return new Promise(async(res,rej)=>{if(parentNode.querySelector("#bfs"+dir2))parentNode.querySelector("#bfs"+dir2)?.remove();parentNode.insertAdjacentHTML("beforeend",`
`);let div=parentNode.querySelector("#bfs"+dir2);await listFiles(dir2).then(directory=>{if(directory.length===0)div.innerHTML="No Files!";else directory.forEach(listing=>{div?.insertAdjacentHTML("beforeend",`
+ Data: + ${listing} + + ${listing.indexOf(".")>-1?``:""} +
`);if(document.getElementById(`delete${listing}`)){document.getElementById(`delete${listing}`).onclick=()=>{deleteFile(dir2+"/"+listing,()=>{visualizeDirectory(dir2,parentNode)})}}if(document.getElementById(`download${listing}`)){document.getElementById(`download${listing}`).onclick=()=>{writeToCSVFromDB(dir2+"/"+listing,10)}}});res(directory)}).catch(rej)})};var csvRoutes={appendCSV,updateCSVHeader,createCSV,visualizeDirectory,openCSV:CSV.openCSV,saveCSV:CSV.saveCSV,openCSVRaw:CSV.openCSVRaw,parseCSVData,getCSVHeader,writeToCSVFromDB,readCSVChunkFromDB,toISOLocal};export{BFSRoutes,CSV,appendCSV,appendFile2 as appendFile,createCSV,csvRoutes,deleteFile,dirExists,exists,fs2 as fs,fsInited,getCSVHeader,getFileSize,getFilenames,initFS,listFiles,parseCSVData,processDataForCSV,readCSVChunkFromDB,readFile,readFileAsText,readFileChunk,toISOLocal,updateCSVHeader,visualizeDirectory,writeFile,writeToCSVFromDB}; +/*! +* The buffer module from node.js, for the browser. +* +* @author Feross Aboukhadijeh +* @license MIT +*/ diff --git a/extras/dist/index.storage.services.js b/extras/dist/index.storage.services.js new file mode 100644 index 00000000..da33e7dd --- /dev/null +++ b/extras/dist/index.storage.services.js @@ -0,0 +1,12 @@ +(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browserfs=__commonJS({"node_modules/browserfs/dist/browserfs.js"(exports,module){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["BrowserFS"]=factory();else root["BrowserFS"]=factory()})(exports,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module2=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__);module2.loaded=true;return module2.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module2,exports2,__webpack_require__){(function(Buffer2,global,module3,process){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var buffer=__webpack_require__(2);var path=__webpack_require__(9);var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2["EPERM"]=1]="EPERM";ErrorCode2[ErrorCode2["ENOENT"]=2]="ENOENT";ErrorCode2[ErrorCode2["EIO"]=5]="EIO";ErrorCode2[ErrorCode2["EBADF"]=9]="EBADF";ErrorCode2[ErrorCode2["EACCES"]=13]="EACCES";ErrorCode2[ErrorCode2["EBUSY"]=16]="EBUSY";ErrorCode2[ErrorCode2["EEXIST"]=17]="EEXIST";ErrorCode2[ErrorCode2["ENOTDIR"]=20]="ENOTDIR";ErrorCode2[ErrorCode2["EISDIR"]=21]="EISDIR";ErrorCode2[ErrorCode2["EINVAL"]=22]="EINVAL";ErrorCode2[ErrorCode2["EFBIG"]=27]="EFBIG";ErrorCode2[ErrorCode2["ENOSPC"]=28]="ENOSPC";ErrorCode2[ErrorCode2["EROFS"]=30]="EROFS";ErrorCode2[ErrorCode2["ENOTEMPTY"]=39]="ENOTEMPTY";ErrorCode2[ErrorCode2["ENOTSUP"]=95]="ENOTSUP"})(ErrorCode||(ErrorCode={}));var ErrorStrings={};ErrorStrings[ErrorCode.EPERM]="Operation not permitted.";ErrorStrings[ErrorCode.ENOENT]="No such file or directory.";ErrorStrings[ErrorCode.EIO]="Input/output error.";ErrorStrings[ErrorCode.EBADF]="Bad file descriptor.";ErrorStrings[ErrorCode.EACCES]="Permission denied.";ErrorStrings[ErrorCode.EBUSY]="Resource busy or locked.";ErrorStrings[ErrorCode.EEXIST]="File exists.";ErrorStrings[ErrorCode.ENOTDIR]="File is not a directory.";ErrorStrings[ErrorCode.EISDIR]="File is a directory.";ErrorStrings[ErrorCode.EINVAL]="Invalid argument.";ErrorStrings[ErrorCode.EFBIG]="File is too big.";ErrorStrings[ErrorCode.ENOSPC]="No space left on disk.";ErrorStrings[ErrorCode.EROFS]="Cannot modify a read-only file system.";ErrorStrings[ErrorCode.ENOTEMPTY]="Directory is not empty.";ErrorStrings[ErrorCode.ENOTSUP]="Operation is not supported.";var ApiError=function(Error2){function ApiError2(type,message,path$$1){if(message===void 0)message=ErrorStrings[type];Error2.call(this,message);this.syscall="";this.errno=type;this.code=ErrorCode[type];this.path=path$$1;this.stack=new Error2().stack;this.message="Error: "+this.code+": "+message+(this.path?", '"+this.path+"'":"")}if(Error2)ApiError2.__proto__=Error2;ApiError2.prototype=Object.create(Error2&&Error2.prototype);ApiError2.prototype.constructor=ApiError2;ApiError2.fromJSON=function fromJSON(json){var err=new ApiError2(0);err.errno=json.errno;err.code=json.code;err.path=json.path;err.stack=json.stack;err.message=json.message;return err};ApiError2.fromBuffer=function fromBuffer(buffer$$1,i2){if(i2===void 0)i2=0;return ApiError2.fromJSON(JSON.parse(buffer$$1.toString("utf8",i2+4,i2+4+buffer$$1.readUInt32LE(i2))))};ApiError2.FileError=function FileError(code,p){return new ApiError2(code,ErrorStrings[code],p)};ApiError2.ENOENT=function ENOENT(path$$1){return this.FileError(ErrorCode.ENOENT,path$$1)};ApiError2.EEXIST=function EEXIST(path$$1){return this.FileError(ErrorCode.EEXIST,path$$1)};ApiError2.EISDIR=function EISDIR(path$$1){return this.FileError(ErrorCode.EISDIR,path$$1)};ApiError2.ENOTDIR=function ENOTDIR(path$$1){return this.FileError(ErrorCode.ENOTDIR,path$$1)};ApiError2.EPERM=function EPERM(path$$1){return this.FileError(ErrorCode.EPERM,path$$1)};ApiError2.ENOTEMPTY=function ENOTEMPTY(path$$1){return this.FileError(ErrorCode.ENOTEMPTY,path$$1)};ApiError2.prototype.toString=function toString(){return this.message};ApiError2.prototype.toJSON=function toJSON(){return{errno:this.errno,code:this.code,path:this.path,stack:this.stack,message:this.message}};ApiError2.prototype.writeToBuffer=function writeToBuffer(buffer$$1,i2){if(buffer$$1===void 0)buffer$$1=Buffer2.alloc(this.bufferSize());if(i2===void 0)i2=0;var bytesWritten=buffer$$1.write(JSON.stringify(this.toJSON()),i2+4);buffer$$1.writeUInt32LE(bytesWritten,i2);return buffer$$1};ApiError2.prototype.bufferSize=function bufferSize(){return 4+Buffer2.byteLength(JSON.stringify(this.toJSON()))};return ApiError2}(Error);var api_error=Object.freeze({get ErrorCode(){return ErrorCode},ErrorStrings,ApiError});var ActionType;(function(ActionType2){ActionType2[ActionType2["NOP"]=0]="NOP";ActionType2[ActionType2["THROW_EXCEPTION"]=1]="THROW_EXCEPTION";ActionType2[ActionType2["TRUNCATE_FILE"]=2]="TRUNCATE_FILE";ActionType2[ActionType2["CREATE_FILE"]=3]="CREATE_FILE"})(ActionType||(ActionType={}));var FileFlag=function FileFlag2(flagStr){this.flagStr=flagStr;if(FileFlag2.validFlagStrs.indexOf(flagStr)<0){throw new ApiError(ErrorCode.EINVAL,"Invalid flag: "+flagStr)}};FileFlag.getFileFlag=function getFileFlag(flagStr){if(FileFlag.flagCache.hasOwnProperty(flagStr)){return FileFlag.flagCache[flagStr]}return FileFlag.flagCache[flagStr]=new FileFlag(flagStr)};FileFlag.prototype.getFlagString=function getFlagString(){return this.flagStr};FileFlag.prototype.isReadable=function isReadable(){return this.flagStr.indexOf("r")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isWriteable=function isWriteable(){return this.flagStr.indexOf("w")!==-1||this.flagStr.indexOf("a")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isTruncating=function isTruncating(){return this.flagStr.indexOf("w")!==-1};FileFlag.prototype.isAppendable=function isAppendable(){return this.flagStr.indexOf("a")!==-1};FileFlag.prototype.isSynchronous=function isSynchronous(){return this.flagStr.indexOf("s")!==-1};FileFlag.prototype.isExclusive=function isExclusive(){return this.flagStr.indexOf("x")!==-1};FileFlag.prototype.pathExistsAction=function pathExistsAction(){if(this.isExclusive()){return ActionType.THROW_EXCEPTION}else if(this.isTruncating()){return ActionType.TRUNCATE_FILE}else{return ActionType.NOP}};FileFlag.prototype.pathNotExistsAction=function pathNotExistsAction(){if((this.isWriteable()||this.isAppendable())&&this.flagStr!=="r+"){return ActionType.CREATE_FILE}else{return ActionType.THROW_EXCEPTION}};FileFlag.flagCache={};FileFlag.validFlagStrs=["r","r+","rs","rs+","w","wx","w+","wx+","a","ax","a+","ax+"];var FileType;(function(FileType2){FileType2[FileType2["FILE"]=32768]="FILE";FileType2[FileType2["DIRECTORY"]=16384]="DIRECTORY";FileType2[FileType2["SYMLINK"]=40960]="SYMLINK"})(FileType||(FileType={}));var Stats=function Stats2(itemType,size,mode,atime,mtime,ctime){if(atime===void 0)atime=new Date;if(mtime===void 0)mtime=new Date;if(ctime===void 0)ctime=new Date;this.size=size;this.atime=atime;this.mtime=mtime;this.ctime=ctime;this.dev=0;this.ino=0;this.rdev=0;this.nlink=1;this.blksize=4096;this.uid=0;this.gid=0;this.birthtime=new Date(0);this.fileData=null;if(!mode){switch(itemType){case FileType.FILE:this.mode=420;break;case FileType.DIRECTORY:default:this.mode=511}}else{this.mode=mode}this.blocks=Math.ceil(size/512);if(this.mode<4096){this.mode|=itemType}};Stats.fromBuffer=function fromBuffer(buffer$$1){var size=buffer$$1.readUInt32LE(0),mode=buffer$$1.readUInt32LE(4),atime=buffer$$1.readDoubleLE(8),mtime=buffer$$1.readDoubleLE(16),ctime=buffer$$1.readDoubleLE(24);return new Stats(mode&61440,size,mode&4095,new Date(atime),new Date(mtime),new Date(ctime))};Stats.prototype.toBuffer=function toBuffer(){var buffer$$1=Buffer2.alloc(32);buffer$$1.writeUInt32LE(this.size,0);buffer$$1.writeUInt32LE(this.mode,4);buffer$$1.writeDoubleLE(this.atime.getTime(),8);buffer$$1.writeDoubleLE(this.mtime.getTime(),16);buffer$$1.writeDoubleLE(this.ctime.getTime(),24);return buffer$$1};Stats.prototype.clone=function clone(){return new Stats(this.mode&61440,this.size,this.mode&4095,this.atime,this.mtime,this.ctime)};Stats.prototype.isFile=function isFile(){return(this.mode&61440)===FileType.FILE};Stats.prototype.isDirectory=function isDirectory(){return(this.mode&61440)===FileType.DIRECTORY};Stats.prototype.isSymbolicLink=function isSymbolicLink(){return(this.mode&61440)===FileType.SYMLINK};Stats.prototype.chmod=function chmod(mode){this.mode=this.mode&61440|mode};Stats.prototype.isSocket=function isSocket(){return false};Stats.prototype.isBlockDevice=function isBlockDevice(){return false};Stats.prototype.isCharacterDevice=function isCharacterDevice(){return false};Stats.prototype.isFIFO=function isFIFO(){return false};var wrapCb=function(cb,numArgs){return cb};function assertRoot(fs4){if(fs4){return fs4}throw new ApiError(ErrorCode.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function normalizeMode(mode,def){switch(typeof mode){case"number":return mode;case"string":var trueMode=parseInt(mode,8);if(!isNaN(trueMode)){return trueMode}return def;default:return def}}function normalizeTime(time){if(time instanceof Date){return time}else if(typeof time==="number"){return new Date(time*1e3)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid time.")}}function normalizePath(p){if(p.indexOf("\0")>=0){throw new ApiError(ErrorCode.EINVAL,"Path must be a string without null bytes.")}else if(p===""){throw new ApiError(ErrorCode.EINVAL,"Path must not be empty.")}return path.resolve(p)}function normalizeOptions(options,defEnc,defFlag,defMode){switch(typeof options){case"object":return{encoding:typeof options["encoding"]!=="undefined"?options["encoding"]:defEnc,flag:typeof options["flag"]!=="undefined"?options["flag"]:defFlag,mode:normalizeMode(options["mode"],defMode)};case"string":return{encoding:options,flag:defFlag,mode:defMode};default:return{encoding:defEnc,flag:defFlag,mode:defMode}}}function nopCb(){}var FS=function FS2(){this.F_OK=0;this.R_OK=4;this.W_OK=2;this.X_OK=1;this.root=null;this.fdMap={};this.nextFd=100};FS.prototype.initialize=function initialize3(rootFS){if(!rootFS.constructor.isAvailable()){throw new ApiError(ErrorCode.EINVAL,"Tried to instantiate BrowserFS with an unavailable file system.")}return this.root=rootFS};FS.prototype._toUnixTimestamp=function _toUnixTimestamp(time){if(typeof time==="number"){return time}else if(time instanceof Date){return time.getTime()/1e3}throw new Error("Cannot parse time: "+time)};FS.prototype.getRootFS=function getRootFS(){if(this.root){return this.root}else{return null}};FS.prototype.rename=function rename(oldPath,newPath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).rename(normalizePath(oldPath),normalizePath(newPath),newCb)}catch(e){newCb(e)}};FS.prototype.renameSync=function renameSync(oldPath,newPath){assertRoot(this.root).renameSync(normalizePath(oldPath),normalizePath(newPath))};FS.prototype.exists=function exists2(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).exists(normalizePath(path$$1),newCb)}catch(e){return newCb(false)}};FS.prototype.existsSync=function existsSync(path$$1){try{return assertRoot(this.root).existsSync(normalizePath(path$$1))}catch(e){return false}};FS.prototype.stat=function stat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),false,newCb)}catch(e){return newCb(e)}};FS.prototype.statSync=function statSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),false)};FS.prototype.lstat=function lstat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),true,newCb)}catch(e){return newCb(e)}};FS.prototype.lstatSync=function lstatSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),true)};FS.prototype.truncate=function truncate(path$$1,arg2,cb){if(arg2===void 0)arg2=0;if(cb===void 0)cb=nopCb;var len=0;if(typeof arg2==="function"){cb=arg2}else if(typeof arg2==="number"){len=arg2}var newCb=wrapCb(cb,1);try{if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncate(normalizePath(path$$1),len,newCb)}catch(e){return newCb(e)}};FS.prototype.truncateSync=function truncateSync(path$$1,len){if(len===void 0)len=0;if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncateSync(normalizePath(path$$1),len)};FS.prototype.unlink=function unlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).unlink(normalizePath(path$$1),newCb)}catch(e){return newCb(e)}};FS.prototype.unlinkSync=function unlinkSync(path$$1){return assertRoot(this.root).unlinkSync(normalizePath(path$$1))};FS.prototype.open=function open(path$$1,flag,arg2,cb){var this$1=this;if(cb===void 0)cb=nopCb;var mode=normalizeMode(arg2,420);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{assertRoot(this.root).open(normalizePath(path$$1),FileFlag.getFileFlag(flag),mode,function(e,file){if(file){newCb(e,this$1.getFdForFile(file))}else{newCb(e)}})}catch(e){newCb(e)}};FS.prototype.openSync=function openSync(path$$1,flag,mode){if(mode===void 0)mode=420;return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1),FileFlag.getFileFlag(flag),normalizeMode(mode,420)))};FS.prototype.readFile=function readFile2(filename,arg2,cb){if(arg2===void 0)arg2={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg2,null,"r",null);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{var flag=FileFlag.getFileFlag(options["flag"]);if(!flag.isReadable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading."))}return assertRoot(this.root).readFile(normalizePath(filename),options.encoding,flag,newCb)}catch(e){return newCb(e)}};FS.prototype.readFileSync=function readFileSync(filename,arg2){if(arg2===void 0)arg2={};var options=normalizeOptions(arg2,null,"r",null);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isReadable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading.")}return assertRoot(this.root).readFileSync(normalizePath(filename),options.encoding,flag)};FS.prototype.writeFile=function writeFile2(filename,data,arg3,cb){if(arg3===void 0)arg3={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","w",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing."))}return assertRoot(this.root).writeFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){return newCb(e)}};FS.prototype.writeFileSync=function writeFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","w",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing.")}return assertRoot(this.root).writeFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.appendFile=function appendFile3(filename,data,arg3,cb){if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","a",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending."))}assertRoot(this.root).appendFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){newCb(e)}};FS.prototype.appendFileSync=function appendFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","a",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending.")}return assertRoot(this.root).appendFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.fstat=function fstat(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{var file=this.fd2file(fd);file.stat(newCb)}catch(e){newCb(e)}};FS.prototype.fstatSync=function fstatSync(fd){return this.fd2file(fd).statSync()};FS.prototype.close=function close(fd,cb){var this$1=this;if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).close(function(e){if(!e){this$1.closeFd(fd)}newCb(e)})}catch(e){newCb(e)}};FS.prototype.closeSync=function closeSync(fd){this.fd2file(fd).closeSync();this.closeFd(fd)};FS.prototype.ftruncate=function ftruncate(fd,arg2,cb){if(cb===void 0)cb=nopCb;var length=typeof arg2==="number"?arg2:0;cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(length<0){throw new ApiError(ErrorCode.EINVAL)}file.truncate(length,newCb)}catch(e){newCb(e)}};FS.prototype.ftruncateSync=function ftruncateSync(fd,len){if(len===void 0)len=0;var file=this.fd2file(fd);if(len<0){throw new ApiError(ErrorCode.EINVAL)}file.truncateSync(len)};FS.prototype.fsync=function fsync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).sync(newCb)}catch(e){newCb(e)}};FS.prototype.fsyncSync=function fsyncSync(fd){this.fd2file(fd).syncSync()};FS.prototype.fdatasync=function fdatasync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).datasync(newCb)}catch(e){newCb(e)}};FS.prototype.fdatasyncSync=function fdatasyncSync(fd){this.fd2file(fd).datasyncSync()};FS.prototype.write=function write(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var buffer$$1,offset,length,position=null;if(typeof arg2==="string"){var encoding="utf8";switch(typeof arg3){case"function":cb=arg3;break;case"number":position=arg3;encoding=typeof arg4==="string"?arg4:"utf8";cb=typeof arg5==="function"?arg5:cb;break;default:cb=typeof arg4==="function"?arg4:typeof arg5==="function"?arg5:cb;return cb(new ApiError(ErrorCode.EINVAL,"Invalid arguments."))}buffer$$1=Buffer2.from(arg2,encoding);offset=0;length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null;cb=typeof arg5==="function"?arg5:cb}var newCb=wrapCb(cb,3);try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.write(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.writeSync=function writeSync(fd,arg2,arg3,arg4,arg5){var buffer$$1,offset=0,length,position;if(typeof arg2==="string"){position=typeof arg3==="number"?arg3:null;var encoding=typeof arg4==="string"?arg4:"utf8";offset=0;buffer$$1=Buffer2.from(arg2,encoding);length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}return file.writeSync(buffer$$1,offset,length,position)};FS.prototype.read=function read(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var position,offset,length,buffer$$1,newCb;if(typeof arg2==="number"){length=arg2;position=arg3;var encoding=arg4;cb=typeof arg5==="function"?arg5:cb;offset=0;buffer$$1=Buffer2.alloc(length);newCb=wrapCb(function(err,bytesRead,buf){if(err){return cb(err)}cb(err,buf.toString(encoding),bytesRead)},3)}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5;newCb=wrapCb(cb,3)}try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.read(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.readSync=function readSync(fd,arg2,arg3,arg4,arg5){var shenanigans=false;var buffer$$1,offset,length,position,encoding="utf8";if(typeof arg2==="number"){length=arg2;position=arg3;encoding=arg4;offset=0;buffer$$1=Buffer2.alloc(length);shenanigans=true}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}var rv=file.readSync(buffer$$1,offset,length,position);if(!shenanigans){return rv}else{return[buffer$$1.toString(encoding),rv]}};FS.prototype.fchown=function fchown(fd,uid,gid,callback){if(callback===void 0)callback=nopCb;var newCb=wrapCb(callback,1);try{this.fd2file(fd).chown(uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.fchownSync=function fchownSync(fd,uid,gid){this.fd2file(fd).chownSync(uid,gid)};FS.prototype.fchmod=function fchmod(fd,mode,cb){var newCb=wrapCb(cb,1);try{var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmod(numMode,newCb)}catch(e){newCb(e)}};FS.prototype.fchmodSync=function fchmodSync(fd,mode){var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmodSync(numMode)};FS.prototype.futimes=function futimes(fd,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(typeof atime==="number"){atime=new Date(atime*1e3)}if(typeof mtime==="number"){mtime=new Date(mtime*1e3)}file.utimes(atime,mtime,newCb)}catch(e){newCb(e)}};FS.prototype.futimesSync=function futimesSync(fd,atime,mtime){this.fd2file(fd).utimesSync(normalizeTime(atime),normalizeTime(mtime))};FS.prototype.rmdir=function rmdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).rmdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.rmdirSync=function rmdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).rmdirSync(path$$1)};FS.prototype.mkdir=function mkdir(path$$1,mode,cb){if(cb===void 0)cb=nopCb;if(typeof mode==="function"){cb=mode;mode=511}var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).mkdir(path$$1,mode,newCb)}catch(e){newCb(e)}};FS.prototype.mkdirSync=function mkdirSync(path$$1,mode){assertRoot(this.root).mkdirSync(normalizePath(path$$1),normalizeMode(mode,511))};FS.prototype.readdir=function readdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readdirSync=function readdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readdirSync(path$$1)};FS.prototype.link=function link(srcpath,dstpath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).link(srcpath,dstpath,newCb)}catch(e){newCb(e)}};FS.prototype.linkSync=function linkSync(srcpath,dstpath){srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).linkSync(srcpath,dstpath)};FS.prototype.symlink=function symlink(srcpath,dstpath,arg3,cb){if(cb===void 0)cb=nopCb;var type=typeof arg3==="string"?arg3:"file";cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{if(type!=="file"&&type!=="dir"){return newCb(new ApiError(ErrorCode.EINVAL,"Invalid type: "+type))}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).symlink(srcpath,dstpath,type,newCb)}catch(e){newCb(e)}};FS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(!type){type="file"}else if(type!=="file"&&type!=="dir"){throw new ApiError(ErrorCode.EINVAL,"Invalid type: "+type)}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).symlinkSync(srcpath,dstpath,type)};FS.prototype.readlink=function readlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readlink(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readlinkSync=function readlinkSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readlinkSync(path$$1)};FS.prototype.chown=function chown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,false,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.chownSync=function chownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,false,uid,gid)};FS.prototype.lchown=function lchown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,true,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.lchownSync=function lchownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,true,uid,gid)};FS.prototype.chmod=function chmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),false,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.chmodSync=function chmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}path$$1=normalizePath(path$$1);assertRoot(this.root).chmodSync(path$$1,false,numMode)};FS.prototype.lchmod=function lchmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),true,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.lchmodSync=function lchmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<1){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmodSync(normalizePath(path$$1),true,numMode)};FS.prototype.utimes=function utimes(path$$1,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).utimes(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime),newCb)}catch(e){newCb(e)}};FS.prototype.utimesSync=function utimesSync(path$$1,atime,mtime){assertRoot(this.root).utimesSync(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime))};FS.prototype.realpath=function realpath(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;var cache=typeof arg2==="object"?arg2:{};cb=typeof arg2==="function"?arg2:nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).realpath(path$$1,cache,newCb)}catch(e){newCb(e)}};FS.prototype.realpathSync=function realpathSync(path$$1,cache){if(cache===void 0)cache={};path$$1=normalizePath(path$$1);return assertRoot(this.root).realpathSync(path$$1,cache)};FS.prototype.watchFile=function watchFile(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.unwatchFile=function unwatchFile(filename,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.watch=function watch(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.access=function access(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.accessSync=function accessSync(path$$1,mode){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createReadStream=function createReadStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createWriteStream=function createWriteStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.wrapCallbacks=function wrapCallbacks(cbWrapper){wrapCb=cbWrapper};FS.prototype.getFdForFile=function getFdForFile(file){var fd=this.nextFd++;this.fdMap[fd]=file;return fd};FS.prototype.fd2file=function fd2file(fd){var rv=this.fdMap[fd];if(rv){return rv}else{throw new ApiError(ErrorCode.EBADF,"Invalid file descriptor.")}};FS.prototype.closeFd=function closeFd(fd){delete this.fdMap[fd]};FS.Stats=Stats;var fs3=new FS;var _fsMock={};var fsProto=FS.prototype;Object.keys(fsProto).forEach(function(key){if(typeof fs3[key]==="function"){_fsMock[key]=function(){return fs3[key].apply(fs3,arguments)}}else{_fsMock[key]=fs3[key]}});_fsMock["changeFSModule"]=function(newFs){fs3=newFs};_fsMock["getFSModule"]=function(){return fs3};_fsMock["FS"]=FS;function _min(d0,d1,d2,bx,ay){return d0d2?d2+1:d0+1:bx===ay?d1:d1+1}function levenshtein(a,b){if(a===b){return 0}if(a.length>b.length){var tmp=a;a=b;b=tmp}var la=a.length;var lb=b.length;while(la>0&&a.charCodeAt(la-1)===b.charCodeAt(lb-1)){la--;lb--}var offset=0;while(offsetdd?dd+1:dy$1+1:bx0$1===vector[la+y$2]?d0:d0+1;d0=dy$1}}return dd}function deprecationMessage(print,fsName,opts){if(print){console.warn("["+fsName+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+fsName+".Create("+JSON.stringify(opts)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}}var isIE=typeof navigator!=="undefined"&&!!(/(msie) ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||navigator.userAgent.indexOf("Trident")!==-1);var isWebWorker=typeof window==="undefined";function fail(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function mkdirpSync(p,mode,fs4){if(!fs4.existsSync(p)){mkdirpSync(path.dirname(p),mode,fs4);fs4.mkdirSync(p,mode)}}function buffer2ArrayBuffer(buff){var u8=buffer2Uint8array(buff),u8offset=u8.byteOffset,u8Len=u8.byteLength;if(u8offset===0&&u8Len===u8.buffer.byteLength){return u8.buffer}else{return u8.buffer.slice(u8offset,u8offset+u8Len)}}function buffer2Uint8array(buff){if(buff instanceof Uint8Array){return buff}else{return new Uint8Array(buff)}}function arrayish2Buffer(arr){if(arr instanceof Buffer2){return arr}else if(arr instanceof Uint8Array){return uint8Array2Buffer(arr)}else{return Buffer2.from(arr)}}function uint8Array2Buffer(u8){if(u8 instanceof Buffer2){return u8}else if(u8.byteOffset===0&&u8.byteLength===u8.buffer.byteLength){return arrayBuffer2Buffer(u8.buffer)}else{return Buffer2.from(u8.buffer,u8.byteOffset,u8.byteLength)}}function arrayBuffer2Buffer(ab){return Buffer2.from(ab)}function copyingSlice(buff,start,end){if(start===void 0)start=0;if(end===void 0)end=buff.length;if(start<0||end<0||end>buff.length||start>end){throw new TypeError("Invalid slice bounds on buffer of length "+buff.length+": ["+start+", "+end+"]")}if(buff.length===0){return emptyBuffer()}else{var u8=buffer2Uint8array(buff),s0=buff[0],newS0=(s0+1)%255;buff[0]=newS0;if(u8[0]===newS0){u8[0]=s0;return uint8Array2Buffer(u8.slice(start,end))}else{buff[0]=s0;return uint8Array2Buffer(u8.subarray(start,end))}}}var emptyBuff=null;function emptyBuffer(){if(emptyBuff){return emptyBuff}return emptyBuff=Buffer2.alloc(0)}function bufferValidator(v,cb){if(Buffer2.isBuffer(v)){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"option must be a Buffer."))}}function checkOptions(fsType,opts,cb){var optsInfo=fsType.Options;var fsName=fsType.Name;var pendingValidators=0;var callbackCalled=false;var loopEnded=false;function validatorCallback(e){if(!callbackCalled){if(e){callbackCalled=true;cb(e)}pendingValidators--;if(pendingValidators===0&&loopEnded){cb()}}}var loop=function(optName2){if(optsInfo.hasOwnProperty(optName2)){var opt=optsInfo[optName2];var providedValue=opts[optName2];if(providedValue===void 0||providedValue===null){if(!opt.optional){var incorrectOptions=Object.keys(opts).filter(function(o){return!(o in optsInfo)}).map(function(a){return{str:a,distance:levenshtein(optName2,a)}}).filter(function(o){return o.distance<5}).sort(function(a,b){return a.distance-b.distance});if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Required option '"+optName2+"' not provided."+(incorrectOptions.length>0?" You provided unrecognized option '"+incorrectOptions[0].str+"'; perhaps you meant to type '"+optName2+"'.":"")+"\nOption description: "+opt.description))}}}else{var typeMatches=false;if(Array.isArray(opt.type)){typeMatches=opt.type.indexOf(typeof providedValue)!==-1}else{typeMatches=typeof providedValue===opt.type}if(!typeMatches){if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Value provided for option "+optName2+" is not the proper type. Expected "+(Array.isArray(opt.type)?"one of {"+opt.type.join(", ")+"}":opt.type)+", but received "+typeof providedValue+"\nOption description: "+opt.description))}}else if(opt.validator){pendingValidators++;opt.validator(providedValue,validatorCallback)}}}};for(var optName in optsInfo){var returned=loop(optName);if(returned)return returned.v}loopEnded=true;if(pendingValidators===0&&!callbackCalled){cb()}}var BFSUtils=Object.freeze({deprecationMessage,isIE,isWebWorker,fail,mkdirpSync,buffer2ArrayBuffer,buffer2Uint8array,arrayish2Buffer,uint8Array2Buffer,arrayBuffer2Buffer,copyingSlice,emptyBuffer,bufferValidator,checkOptions});var BFSEmscriptenStreamOps=function BFSEmscriptenStreamOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenStreamOps.prototype.open=function open(stream){var path$$1=this.fs.realPath(stream.node);var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)){stream.nfd=this.nodefs.openSync(path$$1,this.fs.flagsToPermissionString(stream.flags))}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.close=function close(stream){var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)&&stream.nfd){this.nodefs.closeSync(stream.nfd)}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.read=function read(stream,buffer$$1,offset,length,position){try{return this.nodefs.readSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.write=function write(stream,buffer$$1,offset,length,position){try{return this.nodefs.writeSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.llseek=function llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(this.FS.isFile(stream.node.mode)){try{var stat=this.nodefs.fstatSync(stream.nfd);position+=stat.size}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}}if(position<0){throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL)}stream.position=position;return position};var BFSEmscriptenNodeOps=function BFSEmscriptenNodeOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenNodeOps.prototype.getattr=function getattr(node){var path$$1=this.fs.realPath(node);var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}};BFSEmscriptenNodeOps.prototype.setattr=function setattr(node,attr){var path$$1=this.fs.realPath(node);try{if(attr.mode!==void 0){this.nodefs.chmodSync(path$$1,attr.mode);node.mode=attr.mode}if(attr.timestamp!==void 0){var date=new Date(attr.timestamp);this.nodefs.utimesSync(path$$1,date,date)}}catch(e){if(!e.code){throw e}if(e.code!=="ENOTSUP"){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}if(attr.size!==void 0){try{this.nodefs.truncateSync(path$$1,attr.size)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}};BFSEmscriptenNodeOps.prototype.lookup=function lookup(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);var mode=this.fs.getMode(path$$1);return this.fs.createNode(parent,name,mode)};BFSEmscriptenNodeOps.prototype.mknod=function mknod(parent,name,mode,dev){var node=this.fs.createNode(parent,name,mode,dev);var path$$1=this.fs.realPath(node);try{if(this.FS.isDir(node.mode)){this.nodefs.mkdirSync(path$$1,node.mode)}else{this.nodefs.writeFileSync(path$$1,"",{mode:node.mode})}}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return node};BFSEmscriptenNodeOps.prototype.rename=function rename(oldNode,newDir,newName){var oldPath=this.fs.realPath(oldNode);var newPath=this.PATH.join2(this.fs.realPath(newDir),newName);try{this.nodefs.renameSync(oldPath,newPath);oldNode.name=newName;oldNode.parent=newDir}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.unlink=function unlink(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.unlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.rmdir=function rmdir(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.rmdirSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readdir=function readdir(node){var path$$1=this.fs.realPath(node);try{var contents=this.nodefs.readdirSync(path$$1);contents.push(".","..");return contents}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.symlink=function symlink(parent,newName,oldPath){var newPath=this.PATH.join2(this.fs.realPath(parent),newName);try{this.nodefs.symlinkSync(oldPath,newPath)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readlink=function readlink(node){var path$$1=this.fs.realPath(node);try{return this.nodefs.readlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};var BFSEmscriptenFS=function BFSEmscriptenFS2(_FS,_PATH,_ERRNO_CODES,nodefs){if(_FS===void 0)_FS=self["FS"];if(_PATH===void 0)_PATH=self["PATH"];if(_ERRNO_CODES===void 0)_ERRNO_CODES=self["ERRNO_CODES"];if(nodefs===void 0)nodefs=_fsMock;this.flagsToPermissionStringMap={0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"};this.nodefs=nodefs;this.FS=_FS;this.PATH=_PATH;this.ERRNO_CODES=_ERRNO_CODES;this.node_ops=new BFSEmscriptenNodeOps(this);this.stream_ops=new BFSEmscriptenStreamOps(this)};BFSEmscriptenFS.prototype.mount=function mount(m){return this.createNode(null,"/",this.getMode(m.opts.root),0)};BFSEmscriptenFS.prototype.createNode=function createNode(parent,name,mode,dev){var FS2=this.FS;if(!FS2.isDir(mode)&&!FS2.isFile(mode)&&!FS2.isLink(mode)){throw new FS2.ErrnoError(this.ERRNO_CODES.EINVAL)}var node=FS2.createNode(parent,name,mode);node.node_ops=this.node_ops;node.stream_ops=this.stream_ops;return node};BFSEmscriptenFS.prototype.getMode=function getMode(path$$1){var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return stat.mode};BFSEmscriptenFS.prototype.realPath=function realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return this.PATH.join.apply(null,parts)};BFSEmscriptenFS.prototype.flagsToPermissionString=function flagsToPermissionString(flags){var parsedFlags=typeof flags==="string"?parseInt(flags,10):flags;parsedFlags&=8191;if(parsedFlags in this.flagsToPermissionStringMap){return this.flagsToPermissionStringMap[parsedFlags]}else{return flags}};BFSEmscriptenFS.prototype.getNodeFS=function getNodeFS(){return this.nodefs};BFSEmscriptenFS.prototype.getFS=function getFS(){return this.FS};BFSEmscriptenFS.prototype.getPATH=function getPATH(){return this.PATH};BFSEmscriptenFS.prototype.getERRNO_CODES=function getERRNO_CODES(){return this.ERRNO_CODES};var BaseFileSystem=function BaseFileSystem2(){};BaseFileSystem.prototype.supportsLinks=function supportsLinks(){return false};BaseFileSystem.prototype.diskSpace=function diskSpace(p,cb){cb(0,0)};BaseFileSystem.prototype.openFile=function openFile(p,flag,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFile=function createFile(p,flag,mode,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.open=function open(p,flag,mode,cb){var this$1=this;var mustBeFile=function(e,stats){if(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.stat(path.dirname(p),false,function(e2,parentStats){if(e2){cb(e2)}else if(parentStats&&!parentStats.isDirectory()){cb(ApiError.ENOTDIR(path.dirname(p)))}else{this$1.createFile(p,flag,mode,cb)}});case ActionType.THROW_EXCEPTION:return cb(ApiError.ENOENT(p));default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}else{if(stats&&stats.isDirectory()){return cb(ApiError.EISDIR(p))}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:return cb(ApiError.EEXIST(p));case ActionType.TRUNCATE_FILE:return this$1.openFile(p,flag,function(e2,fd){if(e2){cb(e2)}else if(fd){fd.truncate(0,function(){fd.sync(function(){cb(null,fd)})})}else{fail()}});case ActionType.NOP:return this$1.openFile(p,flag,cb);default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}};this.stat(p,false,mustBeFile)};BaseFileSystem.prototype.rename=function rename(oldPath,newPath,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.renameSync=function renameSync(oldPath,newPath){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.stat=function stat(p,isLstat,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.statSync=function statSync(p,isLstat){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openFileSync=function openFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFileSync=function createFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openSync=function openSync(p,flag,mode){var stats;try{stats=this.statSync(p,false)}catch(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:var parentStats=this.statSync(path.dirname(p),false);if(!parentStats.isDirectory()){throw ApiError.ENOTDIR(path.dirname(p))}return this.createFileSync(p,flag,mode);case ActionType.THROW_EXCEPTION:throw ApiError.ENOENT(p);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}}if(stats.isDirectory()){throw ApiError.EISDIR(p)}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:throw ApiError.EEXIST(p);case ActionType.TRUNCATE_FILE:this.unlinkSync(p);return this.createFileSync(p,flag,stats.mode);case ActionType.NOP:return this.openFileSync(p,flag,mode);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}};BaseFileSystem.prototype.unlink=function unlink(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.unlinkSync=function unlinkSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.rmdir=function rmdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.rmdirSync=function rmdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.mkdir=function mkdir(p,mode,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.mkdirSync=function mkdirSync(p,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.readdir=function readdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.readdirSync=function readdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.exists=function exists2(p,cb){this.stat(p,null,function(err){cb(!err)})};BaseFileSystem.prototype.existsSync=function existsSync(p){try{this.statSync(p,true);return true}catch(e){return false}};BaseFileSystem.prototype.realpath=function realpath(p,cache,cb){if(this.supportsLinks()){var splitPath=p.split(path.sep);for(var i2=0;i2this._buffer.length){var buf=Buffer2.alloc(len-this._buffer.length,0);this.writeSync(buf,0,buf.length,this._buffer.length);if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}return}this._stat.size=len;var newBuff=Buffer2.alloc(len);this._buffer.copy(newBuff,0,0,len);this._buffer=newBuff;if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}};PreloadFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){this._dirty=true;if(position===void 0||position===null){position=this.getPos()}if(!this._flag.isWriteable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a writeable mode.")}var endFp=position+length;if(endFp>this._stat.size){this._stat.size=endFp;if(endFp>this._buffer.length){var newBuff=Buffer2.alloc(endFp);this._buffer.copy(newBuff);this._buffer=newBuff}}var len=buffer$$1.copy(this._buffer,position,offset,offset+length);this._stat.mtime=new Date;if(this._flag.isSynchronous()){this.syncSync();return len}this.setPos(position+len);return len};PreloadFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){if(!this._flag.isReadable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a readable mode.")}if(position===void 0||position===null){position=this.getPos()}var endRead=position+length;if(endRead>this._stat.size){length=this._stat.size-position}var rv=this._buffer.copy(buffer$$1,offset,position,position+length);this._stat.atime=new Date;this._pos=position+length;return rv};PreloadFile2.prototype.chmod=function chmod(mode,cb){try{this.chmodSync(mode);cb()}catch(e){cb(e)}};PreloadFile2.prototype.chmodSync=function chmodSync(mode){if(!this._fs.supportsProps()){throw new ApiError(ErrorCode.ENOTSUP)}this._dirty=true;this._stat.chmod(mode);this.syncSync()};PreloadFile2.prototype.isDirty=function isDirty(){return this._dirty};PreloadFile2.prototype.resetDirty=function resetDirty(){this._dirty=false};return PreloadFile2}(BaseFile);var NoSyncFile=function(PreloadFile2){function NoSyncFile2(_fs,_path,_flag,_stat,contents){PreloadFile2.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile2)NoSyncFile2.__proto__=PreloadFile2;NoSyncFile2.prototype=Object.create(PreloadFile2&&PreloadFile2.prototype);NoSyncFile2.prototype.constructor=NoSyncFile2;NoSyncFile2.prototype.sync=function sync(cb){cb()};NoSyncFile2.prototype.syncSync=function syncSync(){};NoSyncFile2.prototype.close=function close(cb){cb()};NoSyncFile2.prototype.closeSync=function closeSync(){};return NoSyncFile2}(PreloadFile);var MirrorFile=function(PreloadFile$$1){function MirrorFile2(fs4,path$$1,flag,stat,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,data)}if(PreloadFile$$1)MirrorFile2.__proto__=PreloadFile$$1;MirrorFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);MirrorFile2.prototype.constructor=MirrorFile2;MirrorFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};MirrorFile2.prototype.closeSync=function closeSync(){this.syncSync()};return MirrorFile2}(PreloadFile);var AsyncMirror=function(SynchronousFileSystem$$1){function AsyncMirror2(sync,async,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this._queue=[];this._queueRunning=false;this._isInitialized=false;this._initializeCallbacks=[];this._sync=sync;this._async=async;if(!sync.supportsSynch()){throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.")}deprecationMessage(deprecateMsg,AsyncMirror2.Name,{sync:"sync file system instance",async:"async file system instance"})}if(SynchronousFileSystem$$1)AsyncMirror2.__proto__=SynchronousFileSystem$$1;AsyncMirror2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);AsyncMirror2.prototype.constructor=AsyncMirror2;AsyncMirror2.Create=function Create(opts,cb){try{var fs4=new AsyncMirror2(opts.sync,opts.async,false);fs4.initialize(function(e){if(e){cb(e)}else{cb(null,fs4)}},false)}catch(e){cb(e)}};AsyncMirror2.isAvailable=function isAvailable(){return true};AsyncMirror2.prototype.getName=function getName(){return AsyncMirror2.Name};AsyncMirror2.prototype._syncSync=function _syncSync(fd){this._sync.writeFileSync(fd.getPath(),fd.getBuffer(),null,FileFlag.getFileFlag("w"),fd.getStats().mode);this.enqueueOp({apiMethod:"writeFile",arguments:[fd.getPath(),fd.getBuffer(),null,fd.getFlag(),fd.getStats().mode]})};AsyncMirror2.prototype.initialize=function initialize3(userCb,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.")}var callbacks=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbacks.forEach(function(cb){return cb(e)})};if(!this._isInitialized){if(callbacks.push(userCb)===1){var copyDirectory=function(p,mode,cb){if(p!=="/"){this$1._sync.mkdirSync(p,mode)}this$1._async.readdir(p,function(err,files){var i2=0;function copyNextFile(err2){if(err2){cb(err2)}else if(i20){var op2=this$1._queue.shift(),args=op2.arguments;args.push(doNextOp);this$1._async[op2.apiMethod].apply(this$1._async,args)}else{this$1._queueRunning=false}};doNextOp()}};return AsyncMirror2}(SynchronousFileSystem);AsyncMirror.Name="AsyncMirror";AsyncMirror.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var nativeMax=Math.max;function overRest$1(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}var breakLoop={};function noop(){}function once(fn){return function(){if(fn===null){return}var callFn=fn;fn=null;callFn.apply(this,arguments)}}var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index-1&&value%1==0&&value++numRun){switch(error.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){performOp(interceptCb)},timeoutDuration*1e3);break;default:cb.apply(null,arguments);break}}else{cb.apply(null,arguments)}};performOp(interceptCb)};CachedDropboxClient.prototype.getCachedInfo=function getCachedInfo(p){return this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.putCachedInfo=function putCachedInfo(p,cache){this._cache[p.toLowerCase()]=cache};CachedDropboxClient.prototype.deleteCachedInfo=function deleteCachedInfo(p){delete this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.getCachedDirInfo=function getCachedDirInfo(p){var info=this.getCachedInfo(p);if(isDirInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.getCachedFileInfo=function getCachedFileInfo(p){var info=this.getCachedInfo(p);if(isFileInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.updateCachedDirInfo=function updateCachedDirInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.contentHash!==null&&(cachedInfo===void 0||cachedInfo.stat.contentHash!==stat.contentHash)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedFileInfo=function updateCachedFileInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.versionTag!==null&&(cachedInfo===void 0||cachedInfo.stat.versionTag!==stat.versionTag)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedInfo=function updateCachedInfo(p,stat,contents){if(contents===void 0)contents=null;if(stat.isFile&&isArrayBuffer(contents)){this.updateCachedFileInfo(p,stat,contents)}else if(stat.isFolder&&Array.isArray(contents)){this.updateCachedDirInfo(p,stat,contents)}};var DropboxFile=function(PreloadFile$$1){function DropboxFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)DropboxFile2.__proto__=PreloadFile$$1;DropboxFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);DropboxFile2.prototype.constructor=DropboxFile2;DropboxFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){var buffer$$1=this.getBuffer(),arrayBuffer=buffer2ArrayBuffer(buffer$$1);this._fs._writeFileStrict(this.getPath(),arrayBuffer,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};DropboxFile2.prototype.close=function close(cb){this.sync(cb)};return DropboxFile2}(PreloadFile);var DropboxFileSystem=function(BaseFileSystem$$1){function DropboxFileSystem2(client,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._client=new CachedDropboxClient(client);deprecationMessage(deprecateMsg,DropboxFileSystem2.Name,{client:"authenticated dropbox client instance"});constructErrorCodeLookup()}if(BaseFileSystem$$1)DropboxFileSystem2.__proto__=BaseFileSystem$$1;DropboxFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);DropboxFileSystem2.prototype.constructor=DropboxFileSystem2;DropboxFileSystem2.Create=function Create(opts,cb){cb(null,new DropboxFileSystem2(opts.client,false))};DropboxFileSystem2.isAvailable=function isAvailable(){return typeof Dropbox!=="undefined"};DropboxFileSystem2.prototype.getName=function getName(){return DropboxFileSystem2.Name};DropboxFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};DropboxFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};DropboxFileSystem2.prototype.supportsProps=function supportsProps(){return false};DropboxFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};DropboxFileSystem2.prototype.empty=function empty(mainCb){var this$1=this;this._client.readdir("/",function(error,files){if(error){mainCb(this$1.convert(error,"/"))}else{var deleteFile2=function(file,cb){var p=path.join("/",file);this$1._client.remove(p,function(err){cb(err?this$1.convert(err,p):null)})};var finished=function(err){if(err){mainCb(err)}else{mainCb()}};eachLimit(files,deleteFile2,finished)}})};DropboxFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._client.move(oldPath,newPath,function(error){if(error){this$1._client.stat(newPath,function(error2,stat){if(error2||stat.isFolder){var missingPath=error.response.error.indexOf(oldPath)>-1?oldPath:newPath;cb(this$1.convert(error,missingPath))}else{this$1._client.remove(newPath,function(error22){if(error22){cb(this$1.convert(error22,newPath))}else{this$1.rename(oldPath,newPath,cb)}})}})}else{cb()}})};DropboxFileSystem2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;this._client.stat(path$$1,function(error,stat2){if(error){cb(this$1.convert(error,path$$1))}else if(stat2&&stat2.isRemoved){cb(ApiError.FileError(ErrorCode.ENOENT,path$$1))}else{var stats=new Stats(this$1._statType(stat2),stat2.size);return cb(null,stats)}})};DropboxFileSystem2.prototype.open=function open(path$$1,flags,mode,cb){var this$1=this;this._client.readFile(path$$1,function(error,content,dbStat){if(error){if(flags.isReadable()){cb(this$1.convert(error,path$$1))}else{switch(error.status){case Dropbox.ApiError.NOT_FOUND:var ab=new ArrayBuffer(0);return this$1._writeFileStrict(path$$1,ab,function(error2,stat){if(error2){cb(error2)}else{var file2=this$1._makeFile(path$$1,flags,stat,arrayBuffer2Buffer(ab));cb(null,file2)}});default:return cb(this$1.convert(error,path$$1))}}}else{var buffer$$1;if(content===null){buffer$$1=emptyBuffer()}else{buffer$$1=arrayBuffer2Buffer(content)}var file=this$1._makeFile(path$$1,flags,dbStat,buffer$$1);return cb(null,file)}})};DropboxFileSystem2.prototype._writeFileStrict=function _writeFileStrict(p,data,cb){var this$1=this;var parent=path.dirname(p);this.stat(parent,false,function(error,stat){if(error){cb(ApiError.FileError(ErrorCode.ENOENT,parent))}else{this$1._client.writeFile(p,data,function(error2,stat2){if(error2){cb(this$1.convert(error2,p))}else{cb(null,stat2)}})}})};DropboxFileSystem2.prototype._statType=function _statType(stat){return stat.isFile?FileType.FILE:FileType.DIRECTORY};DropboxFileSystem2.prototype._makeFile=function _makeFile(path$$1,flag,stat,buffer$$1){var type=this._statType(stat);var stats=new Stats(type,stat.size);return new DropboxFile(this,path$$1,flag,stats,buffer$$1)};DropboxFileSystem2.prototype._remove=function _remove(path$$1,cb,isFile){var this$1=this;this._client.stat(path$$1,function(error,stat){if(error){cb(this$1.convert(error,path$$1))}else{if(stat.isFile&&!isFile){cb(ApiError.FileError(ErrorCode.ENOTDIR,path$$1))}else if(!stat.isFile&&isFile){cb(ApiError.FileError(ErrorCode.EISDIR,path$$1))}else{this$1._client.remove(path$$1,function(error2){if(error2){cb(this$1.convert(error2,path$$1))}else{cb(null)}})}}})};DropboxFileSystem2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};DropboxFileSystem2.prototype.rmdir=function rmdir(path$$1,cb){this._remove(path$$1,cb,false)};DropboxFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;var parent=path.dirname(p);this._client.stat(parent,function(error,stat){if(error){cb(this$1.convert(error,parent))}else{this$1._client.mkdir(p,function(error2){if(error2){cb(ApiError.FileError(ErrorCode.EEXIST,p))}else{cb(null)}})}})};DropboxFileSystem2.prototype.readdir=function readdir(path$$1,cb){var this$1=this;this._client.readdir(path$$1,function(error,files){if(error){return cb(this$1.convert(error))}else{return cb(null,files)}})};DropboxFileSystem2.prototype.convert=function convert(err,path$$1){if(path$$1===void 0)path$$1=null;var errorCode=errorCodeLookup[err.status];if(errorCode===void 0){errorCode=ErrorCode.EIO}if(!path$$1){return new ApiError(errorCode)}else{return ApiError.FileError(errorCode,path$$1)}};return DropboxFileSystem2}(BaseFileSystem);DropboxFileSystem.Name="Dropbox";DropboxFileSystem.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(opt,cb){if(opt.isAuthenticated&&opt.isAuthenticated()){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}}};function convertError(e,path$$1){if(path$$1===void 0)path$$1="";var errno=e.errno;var parent=e.node;var paths=[];while(parent){paths.unshift(parent.name);if(parent===parent.parent){break}parent=parent.parent}return new ApiError(errno,ErrorStrings[errno],paths.length>0?"/"+paths.join("/"):path$$1)}var EmscriptenFile=function(BaseFile$$1){function EmscriptenFile2(_fs,_FS,_path,_stream){BaseFile$$1.call(this);this._fs=_fs;this._FS=_FS;this._path=_path;this._stream=_stream}if(BaseFile$$1)EmscriptenFile2.__proto__=BaseFile$$1;EmscriptenFile2.prototype=Object.create(BaseFile$$1&&BaseFile$$1.prototype);EmscriptenFile2.prototype.constructor=EmscriptenFile2;EmscriptenFile2.prototype.getPos=function getPos(){return void 0};EmscriptenFile2.prototype.close=function close(cb){var err=null;try{this.closeSync()}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.closeSync=function closeSync(){try{this._FS.close(this._stream)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.stat=function stat(cb){try{cb(null,this.statSync())}catch(e){cb(e)}};EmscriptenFile2.prototype.statSync=function statSync(){try{return this._fs.statSync(this._path,false)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.truncate=function truncate(len,cb){var err=null;try{this.truncateSync(len)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.truncateSync=function truncateSync(len){try{this._FS.ftruncate(this._stream.fd,len)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.write(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.read(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.sync=function sync(cb){cb()};EmscriptenFile2.prototype.syncSync=function syncSync(){};EmscriptenFile2.prototype.chown=function chown(uid,gid,cb){var err=null;try{this.chownSync(uid,gid)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chownSync=function chownSync(uid,gid){try{this._FS.fchown(this._stream.fd,uid,gid)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.chmod=function chmod(mode,cb){var err=null;try{this.chmodSync(mode)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chmodSync=function chmodSync(mode){try{this._FS.fchmod(this._stream.fd,mode)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.utimes=function utimes(atime,mtime,cb){var err=null;try{this.utimesSync(atime,mtime)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.utimesSync=function utimesSync(atime,mtime){this._fs.utimesSync(this._path,atime,mtime)};return EmscriptenFile2}(BaseFile);var EmscriptenFileSystem=function(SynchronousFileSystem$$1){function EmscriptenFileSystem2(_FS){SynchronousFileSystem$$1.call(this);this._FS=_FS}if(SynchronousFileSystem$$1)EmscriptenFileSystem2.__proto__=SynchronousFileSystem$$1;EmscriptenFileSystem2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);EmscriptenFileSystem2.prototype.constructor=EmscriptenFileSystem2;EmscriptenFileSystem2.Create=function Create(opts,cb){cb(null,new EmscriptenFileSystem2(opts.FS))};EmscriptenFileSystem2.isAvailable=function isAvailable(){return true};EmscriptenFileSystem2.prototype.getName=function getName(){return this._FS.DB_NAME()};EmscriptenFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};EmscriptenFileSystem2.prototype.supportsLinks=function supportsLinks(){return true};EmscriptenFileSystem2.prototype.supportsProps=function supportsProps(){return true};EmscriptenFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};EmscriptenFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){try{this._FS.rename(oldPath,newPath)}catch(e){if(e.errno===ErrorCode.ENOENT){throw convertError(e,this.existsSync(oldPath)?newPath:oldPath)}else{throw convertError(e)}}};EmscriptenFileSystem2.prototype.statSync=function statSync(p,isLstat){try{var stats=isLstat?this._FS.lstat(p):this._FS.stat(p);var itemType=this.modeToFileType(stats.mode);return new Stats(itemType,stats.size,stats.mode,stats.atime,stats.mtime,stats.ctime)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.openSync=function openSync(p,flag,mode){try{var stream=this._FS.open(p,flag.getFlagString(),mode);if(this._FS.isDir(stream.node.mode)){this._FS.close(stream);throw ApiError.EISDIR(p)}return new EmscriptenFile(this,this._FS,p,stream)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.unlinkSync=function unlinkSync(p){try{this._FS.unlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.rmdirSync=function rmdirSync(p){try{this._FS.rmdir(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){try{this._FS.mkdir(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readdirSync=function readdirSync(p){try{return this._FS.readdir(p).filter(function(p2){return p2!=="."&&p2!==".."})}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.truncateSync=function truncateSync(p,len){try{this._FS.truncate(p,len)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readFileSync=function readFileSync(p,encoding,flag){try{var data=this._FS.readFile(p,{flags:flag.getFlagString()});var buff=uint8Array2Buffer(data);if(encoding){return buff.toString(encoding)}else{return buff}}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.writeFileSync=function writeFileSync(p,data,encoding,flag,mode){try{if(encoding){data=Buffer2.from(data,encoding)}var u8=buffer2Uint8array(data);this._FS.writeFile(p,u8,{flags:flag.getFlagString(),encoding:"binary"});this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){try{isLchmod?this._FS.lchmod(p,mode):this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){try{isLchown?this._FS.lchown(p,uid,gid):this._FS.chown(p,uid,gid)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){try{this._FS.symlink(srcpath,dstpath)}catch(e){throw convertError(e)}};EmscriptenFileSystem2.prototype.readlinkSync=function readlinkSync(p){try{return this._FS.readlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.utimesSync=function utimesSync(p,atime,mtime){try{this._FS.utime(p,atime.getTime(),mtime.getTime())}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.modeToFileType=function modeToFileType(mode){if(this._FS.isDir(mode)){return FileType.DIRECTORY}else if(this._FS.isFile(mode)){return FileType.FILE}else if(this._FS.isLink(mode)){return FileType.SYMLINK}else{throw ApiError.EPERM("Invalid mode: "+mode)}};return EmscriptenFileSystem2}(SynchronousFileSystem);EmscriptenFileSystem.Name="EmscriptenFileSystem";EmscriptenFileSystem.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var FolderAdapter=function(BaseFileSystem$$1){function FolderAdapter2(folder,wrapped){BaseFileSystem$$1.call(this);this._folder=folder;this._wrapped=wrapped}if(BaseFileSystem$$1)FolderAdapter2.__proto__=BaseFileSystem$$1;FolderAdapter2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);FolderAdapter2.prototype.constructor=FolderAdapter2;FolderAdapter2.Create=function Create(opts,cb){cb(null,new FolderAdapter2(opts.folder,opts.wrapped))};FolderAdapter2.isAvailable=function isAvailable(){return true};FolderAdapter2.prototype.initialize=function initialize3(cb){var this$1=this;this._wrapped.exists(this._folder,function(exists2){if(exists2){cb()}else if(this$1._wrapped.isReadOnly()){cb(ApiError.ENOENT(this$1._folder))}else{this$1._wrapped.mkdir(this$1._folder,511,cb)}})};FolderAdapter2.prototype.getName=function getName(){return this._wrapped.getName()};FolderAdapter2.prototype.isReadOnly=function isReadOnly(){return this._wrapped.isReadOnly()};FolderAdapter2.prototype.supportsProps=function supportsProps(){return this._wrapped.supportsProps()};FolderAdapter2.prototype.supportsSynch=function supportsSynch(){return this._wrapped.supportsSynch()};FolderAdapter2.prototype.supportsLinks=function supportsLinks(){return false};return FolderAdapter2}(BaseFileSystem);FolderAdapter.Name="FolderAdapter";FolderAdapter.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}};function translateError(folder,e){if(e!==null&&typeof e==="object"){var err=e;var p=err.path;if(p){p="/"+path.relative(folder,p);err.message=err.message.replace(err.path,p);err.path=p}}return e}function wrapCallback(folder,cb){if(typeof cb==="function"){return function(err){if(arguments.length>0){arguments[0]=translateError(folder,err)}cb.apply(null,arguments)}}else{return cb}}function wrapFunction(name,wrapFirst,wrapSecond){if(name.slice(name.length-4)!=="Sync"){return function(){if(arguments.length>0){if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}arguments[arguments.length-1]=wrapCallback(this._folder,arguments[arguments.length-1])}return this._wrapped[name].apply(this._wrapped,arguments)}}else{return function(){try{if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}return this._wrapped[name].apply(this._wrapped,arguments)}catch(e){throw translateError(this._folder,e)}}}}["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,false)});["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,true)});var toExport;if(typeof window!=="undefined"){toExport=window}else if(typeof self!=="undefined"){toExport=self}else{toExport=global}var global$1=toExport;function isDirectoryEntry(entry){return entry.isDirectory}var _getFS=global$1.webkitRequestFileSystem||global$1.requestFileSystem||null;function _requestQuota(type,size,success,errorCallback){if(typeof navigator["webkitPersistentStorage"]!=="undefined"){switch(type){case global$1.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(size,success,errorCallback);break;case global$1.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(size,success,errorCallback);break;default:errorCallback(new TypeError("Invalid storage type: "+type));break}}else{global$1.webkitStorageInfo.requestQuota(type,size,success,errorCallback)}}function _toArray(list2){return Array.prototype.slice.call(list2||[],0)}function convertError$1(err,p,expectedDir){switch(err.name){case"PathExistsError":return ApiError.EEXIST(p);case"QuotaExceededError":return ApiError.FileError(ErrorCode.ENOSPC,p);case"NotFoundError":return ApiError.ENOENT(p);case"SecurityError":return ApiError.FileError(ErrorCode.EACCES,p);case"InvalidModificationError":return ApiError.FileError(ErrorCode.EPERM,p);case"TypeMismatchError":return ApiError.FileError(expectedDir?ErrorCode.ENOTDIR:ErrorCode.EISDIR,p);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return ApiError.FileError(ErrorCode.EINVAL,p)}}var HTML5FSFile=function(PreloadFile$$1){function HTML5FSFile2(fs4,entry,path$$1,flag,stat,contents){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,contents);this._entry=entry}if(PreloadFile$$1)HTML5FSFile2.__proto__=PreloadFile$$1;HTML5FSFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);HTML5FSFile2.prototype.constructor=HTML5FSFile2;HTML5FSFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){return cb()}this._entry.createWriter(function(writer){var buffer$$1=this$1.getBuffer();var blob=new Blob([buffer2ArrayBuffer(buffer$$1)]);var length=blob.size;writer.onwriteend=function(err){writer.onwriteend=null;writer.onerror=null;writer.truncate(length);this$1.resetDirty();cb()};writer.onerror=function(err){cb(convertError$1(err,this$1.getPath(),false))};writer.write(blob)})};HTML5FSFile2.prototype.close=function close(cb){this.sync(cb)};return HTML5FSFile2}(PreloadFile);var HTML5FS=function(BaseFileSystem$$1){function HTML5FS2(size,type,deprecateMsg){if(size===void 0)size=5;if(type===void 0)type=global$1.PERSISTENT;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this.size=1024*1024*size;this.type=type;deprecationMessage(deprecateMsg,HTML5FS2.Name,{size,type})}if(BaseFileSystem$$1)HTML5FS2.__proto__=BaseFileSystem$$1;HTML5FS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);HTML5FS2.prototype.constructor=HTML5FS2;HTML5FS2.Create=function Create(opts,cb){var fs4=new HTML5FS2(opts.size,opts.type,false);fs4.allocate(function(e){return e?cb(e):cb(null,fs4)},false)};HTML5FS2.isAvailable=function isAvailable(){return!!_getFS};HTML5FS2.prototype.getName=function getName(){return HTML5FS2.Name};HTML5FS2.prototype.isReadOnly=function isReadOnly(){return false};HTML5FS2.prototype.supportsSymlinks=function supportsSymlinks(){return false};HTML5FS2.prototype.supportsProps=function supportsProps(){return false};HTML5FS2.prototype.supportsSynch=function supportsSynch(){return false};HTML5FS2.prototype.allocate=function allocate(cb,deprecateMsg){var this$1=this;if(cb===void 0)cb=function(){};if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.")}var success=function(fs4){this$1.fs=fs4;cb()};var error=function(err){cb(convertError$1(err,"/",true))};if(this.type===global$1.PERSISTENT){_requestQuota(this.type,this.size,function(granted){_getFS(this$1.type,granted,success,error)},error)}else{_getFS(this.type,this.size,success,error)}};HTML5FS2.prototype.empty=function empty(mainCb){this._readdir("/",function(err,entries){if(err){console.error("Failed to empty FS");mainCb(err)}else{var finished=function(er){if(err){console.error("Failed to empty FS");mainCb(err)}else{mainCb()}};var deleteEntry=function(entry,cb){var succ=function(){cb()};var error=function(err2){cb(convertError$1(err2,entry.fullPath,!entry.isDirectory))};if(isDirectoryEntry(entry)){entry.removeRecursively(succ,error)}else{entry.remove(succ,error)}};eachLimit(entries,deleteEntry,finished)}})};HTML5FS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var semaphore=2;var successCount=0;var root2=this.fs.root;var currentPath=oldPath;var error=function(err){if(--semaphore<=0){cb(convertError$1(err,currentPath,false))}};var success=function(file){if(++successCount===2){return cb(new ApiError(ErrorCode.EINVAL,"Something was identified as both a file and a directory. This should never happen."))}if(oldPath===newPath){return cb()}currentPath=path.dirname(newPath);root2.getDirectory(currentPath,{},function(parentDir){currentPath=path.basename(newPath);file.moveTo(parentDir,currentPath,function(entry){cb()},function(err){if(file.isDirectory){currentPath=newPath;this$1.unlink(newPath,function(e){if(e){error(err)}else{this$1.rename(oldPath,newPath,cb)}})}else{error(err)}})},error)};root2.getFile(oldPath,{},success,error);root2.getDirectory(oldPath,{},success,error)};HTML5FS2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;var opts={create:false};var loadAsFile=function(entry){var fileFromEntry=function(file){var stat2=new Stats(FileType.FILE,file.size);cb(null,stat2)};entry.file(fileFromEntry,failedToLoad)};var loadAsDir=function(dir$$1){var size=4096;var stat2=new Stats(FileType.DIRECTORY,size);cb(null,stat2)};var failedToLoad=function(err){cb(convertError$1(err,path$$1,false))};var failedToLoadAsFile=function(){this$1.fs.root.getDirectory(path$$1,opts,loadAsDir,failedToLoad)};this.fs.root.getFile(path$$1,opts,loadAsFile,failedToLoadAsFile)};HTML5FS2.prototype.open=function open(p,flags,mode,cb){var this$1=this;var error=function(err){if(err.name==="InvalidModificationError"&&flags.isExclusive()){cb(ApiError.EEXIST(p))}else{cb(convertError$1(err,p,false))}};this.fs.root.getFile(p,{create:flags.pathNotExistsAction()===ActionType.CREATE_FILE,exclusive:flags.isExclusive()},function(entry){entry.file(function(file){var reader=new FileReader;reader.onloadend=function(event){var bfsFile=this$1._makeFile(p,entry,flags,file,reader.result);cb(null,bfsFile)};reader.onerror=function(ev){error(reader.error)};reader.readAsArrayBuffer(file)},error)},error)};HTML5FS2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};HTML5FS2.prototype.rmdir=function rmdir(path$$1,cb){var this$1=this;this.readdir(path$$1,function(e,files){if(e){cb(e)}else if(files.length>0){cb(ApiError.ENOTEMPTY(path$$1))}else{this$1._remove(path$$1,cb,false)}})};HTML5FS2.prototype.mkdir=function mkdir(path$$1,mode,cb){var opts={create:true,exclusive:true};var success=function(dir$$1){cb()};var error=function(err){cb(convertError$1(err,path$$1,true))};this.fs.root.getDirectory(path$$1,opts,success,error)};HTML5FS2.prototype.readdir=function readdir(path$$1,cb){this._readdir(path$$1,function(e,entries){if(entries){var rv=[];for(var i2=0,list2=entries;i20){throw ApiError.ENOTEMPTY(p)}else{this.removeEntry(p,true)}};SyncKeyValueFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data)};SyncKeyValueFileSystem2.prototype.readdirSync=function readdirSync(p){var tx=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(tx,p,this.findINode(tx,p)))};SyncKeyValueFileSystem2.prototype._syncSync=function _syncSync(p,data,stats){var tx=this.store.beginTransaction("readwrite"),fileInodeId=this._findINode(tx,path.dirname(p),path.basename(p)),fileInode=this.getINode(tx,p,fileInodeId),inodeChanged=fileInode.update(stats);try{tx.put(fileInode.id,data,true);if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true)}}catch(e){tx.abort();throw e}tx.commit()};SyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(){var tx=this.store.beginTransaction("readwrite");if(tx.get(ROOT_NODE_ID)===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false);tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false);tx.commit()}};SyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename){var this$1=this;var readDirectory=function(inode){var dirList=this$1.getDirListing(tx,parent,inode);if(dirList[filename]){return dirList[filename]}else{throw ApiError.ENOENT(path.resolve(parent,filename))}};if(parent==="/"){if(filename===""){return ROOT_NODE_ID}else{return readDirectory(this.getINode(tx,parent,ROOT_NODE_ID))}}else{return readDirectory(this.getINode(tx,parent+path.sep+filename,this._findINode(tx,path.dirname(parent),path.basename(parent))))}};SyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p){return this.getINode(tx,p,this._findINode(tx,path.dirname(p),path.basename(p)))};SyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id){var inode=tx.get(id);if(inode===void 0){throw ApiError.ENOENT(p)}return Inode.fromBuffer(inode)};SyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode){if(!inode.isDirectory()){throw ApiError.ENOTDIR(p)}var data=tx.get(inode.id);if(data===void 0){throw ApiError.ENOENT(p)}return JSON.parse(data.toString())};SyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data){var retries=0;var currId;while(retries<5){try{currId=GenerateRandomID();tx.put(currId,data,false);return currId}catch(e){}}throw new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store.")};SyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data){var parentDir=path.dirname(p),fname=path.basename(p),parentNode=this.findINode(tx,parentDir),dirListing=this.getDirListing(tx,parentDir,parentNode),currTime=new Date().getTime();if(p==="/"){throw ApiError.EEXIST(p)}if(dirListing[fname]){throw ApiError.EEXIST(p)}var fileNode;try{var dataId=this.addNewNode(tx,data);fileNode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);var fileNodeId=this.addNewNode(tx,fileNode.toBuffer());dirListing[fname]=fileNodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true)}catch(e){tx.abort();throw e}tx.commit();return fileNode};SyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir){var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),parentNode=this.findINode(tx,parent),parentListing=this.getDirListing(tx,parent,parentNode),fileName=path.basename(p);if(!parentListing[fileName]){throw ApiError.ENOENT(p)}var fileNodeId=parentListing[fileName];delete parentListing[fileName];var fileNode=this.getINode(tx,p,fileNodeId);if(!isDir&&fileNode.isDirectory()){throw ApiError.EISDIR(p)}else if(isDir&&!fileNode.isDirectory()){throw ApiError.ENOTDIR(p)}try{tx.del(fileNode.id);tx.del(fileNodeId);tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true)}catch(e){tx.abort();throw e}tx.commit()};return SyncKeyValueFileSystem2}(SynchronousFileSystem);var AsyncKeyValueFile=function(PreloadFile$$1){function AsyncKeyValueFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)AsyncKeyValueFile2.__proto__=PreloadFile$$1;AsyncKeyValueFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);AsyncKeyValueFile2.prototype.constructor=AsyncKeyValueFile2;AsyncKeyValueFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};AsyncKeyValueFile2.prototype.close=function close(cb){this.sync(cb)};return AsyncKeyValueFile2}(PreloadFile);var AsyncKeyValueFileSystem=function(BaseFileSystem$$1){function AsyncKeyValueFileSystem2(){BaseFileSystem$$1.apply(this,arguments)}if(BaseFileSystem$$1)AsyncKeyValueFileSystem2.__proto__=BaseFileSystem$$1;AsyncKeyValueFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);AsyncKeyValueFileSystem2.prototype.constructor=AsyncKeyValueFileSystem2;AsyncKeyValueFileSystem2.isAvailable=function isAvailable(){return true};AsyncKeyValueFileSystem2.prototype.init=function init(store,cb){this.store=store;this.makeRootDirectory(cb)};AsyncKeyValueFileSystem2.prototype.getName=function getName(){return this.store.name()};AsyncKeyValueFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};AsyncKeyValueFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};AsyncKeyValueFileSystem2.prototype.supportsProps=function supportsProps(){return false};AsyncKeyValueFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};AsyncKeyValueFileSystem2.prototype.empty=function empty(cb){var this$1=this;this.store.clear(function(e){if(noError(e,cb)){this$1.makeRootDirectory(cb)}})};AsyncKeyValueFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");var oldParent=path.dirname(oldPath),oldName=path.basename(oldPath);var newParent=path.dirname(newPath),newName=path.basename(newPath);var inodes={};var lists={};var errorOccurred=false;if((newParent+"/").indexOf(oldPath+"/")===0){return cb(new ApiError(ErrorCode.EBUSY,oldParent))}var theOleSwitcharoo=function(){if(errorOccurred||!lists.hasOwnProperty(oldParent)||!lists.hasOwnProperty(newParent)){return}var oldParentList=lists[oldParent],oldParentINode=inodes[oldParent],newParentList=lists[newParent],newParentINode=inodes[newParent];if(!oldParentList[oldName]){cb(ApiError.ENOENT(oldPath))}else{var fileId=oldParentList[oldName];delete oldParentList[oldName];var completeRename=function(){newParentList[newName]=fileId;tx.put(oldParentINode.id,Buffer2.from(JSON.stringify(oldParentList)),true,function(e){if(noErrorTx(e,tx,cb)){if(oldParent===newParent){tx.commit(cb)}else{tx.put(newParentINode.id,Buffer2.from(JSON.stringify(newParentList)),true,function(e2){if(noErrorTx(e2,tx,cb)){tx.commit(cb)}})}}})};if(newParentList[newName]){this$1.getINode(tx,newPath,newParentList[newName],function(e,inode){if(noErrorTx(e,tx,cb)){if(inode.isFile()){tx.del(inode.id,function(e2){if(noErrorTx(e2,tx,cb)){tx.del(newParentList[newName],function(e3){if(noErrorTx(e3,tx,cb)){completeRename()}})}})}else{tx.abort(function(e2){cb(ApiError.EPERM(newPath))})}}})}else{completeRename()}}};var processInodeAndListings=function(p){this$1.findINodeAndDirListing(tx,p,function(e,node,dirList){if(e){if(!errorOccurred){errorOccurred=true;tx.abort(function(){cb(e)})}}else{inodes[p]=node;lists[p]=dirList;theOleSwitcharoo()}})};processInodeAndListings(oldParent);if(oldParent!==newParent){processInodeAndListings(newParent)}};AsyncKeyValueFileSystem2.prototype.stat=function stat(p,isLstat,cb){var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){cb(null,inode.toStats())}})};AsyncKeyValueFileSystem2.prototype.createFile=function createFile(p,flag,mode,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),data=emptyBuffer();this.commitNewFile(tx,p,FileType.FILE,mode,data,function(e,newFile){if(noError(e,cb)){cb(null,new AsyncKeyValueFile(this$1,p,flag,newFile.toStats(),data))}})};AsyncKeyValueFileSystem2.prototype.openFile=function openFile(p,flag,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){tx.get(inode.id,function(e2,data){if(noError(e2,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,new AsyncKeyValueFile(this$1,p,flag,inode.toStats(),data))}}})}})};AsyncKeyValueFileSystem2.prototype.unlink=function unlink(p,cb){this.removeEntry(p,false,cb)};AsyncKeyValueFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;this.readdir(p,function(err,files){if(err){cb(err)}else if(files.length>0){cb(ApiError.ENOTEMPTY(p))}else{this$1.removeEntry(p,true,cb)}})};AsyncKeyValueFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data,cb)};AsyncKeyValueFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,dirListing){if(noError(e2,cb)){cb(null,Object.keys(dirListing))}})}})};AsyncKeyValueFileSystem2.prototype._sync=function _sync(p,data,stats,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");this._findINode(tx,path.dirname(p),path.basename(p),function(e,fileInodeId){if(noErrorTx(e,tx,cb)){this$1.getINode(tx,p,fileInodeId,function(e2,fileInode){if(noErrorTx(e2,tx,cb)){var inodeChanged=fileInode.update(stats);tx.put(fileInode.id,data,true,function(e3){if(noErrorTx(e3,tx,cb)){if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(cb)}})}else{tx.commit(cb)}}})}})}})};AsyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(cb){var tx=this.store.beginTransaction("readwrite");tx.get(ROOT_NODE_ID,function(e,data){if(e||data===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false,function(e2){if(noErrorTx(e2,tx,cb)){tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false,function(e3){if(e3){tx.abort(function(){cb(e3)})}else{tx.commit(cb)}})}})}else{tx.commit(cb)}})};AsyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename,cb){var this$1=this;var handleDirectoryListings=function(e,inode,dirList){if(e){cb(e)}else if(dirList[filename]){cb(null,dirList[filename])}else{cb(ApiError.ENOENT(path.resolve(parent,filename)))}};if(parent==="/"){if(filename===""){cb(null,ROOT_NODE_ID)}else{this.getINode(tx,parent,ROOT_NODE_ID,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,parent,inode,function(e2,dirList){handleDirectoryListings(e2,inode,dirList)})}})}}else{this.findINodeAndDirListing(tx,parent,handleDirectoryListings)}};AsyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p,cb){var this$1=this;this._findINode(tx,path.dirname(p),path.basename(p),function(e,id){if(noError(e,cb)){this$1.getINode(tx,p,id,cb)}})};AsyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id,cb){tx.get(id,function(e,data){if(noError(e,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,Inode.fromBuffer(data))}}})};AsyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode,cb){if(!inode.isDirectory()){cb(ApiError.ENOTDIR(p))}else{tx.get(inode.id,function(e,data){if(noError(e,cb)){try{cb(null,JSON.parse(data.toString()))}catch(e2){cb(ApiError.ENOENT(p))}}})}};AsyncKeyValueFileSystem2.prototype.findINodeAndDirListing=function findINodeAndDirListing(tx,p,cb){var this$1=this;this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,listing){if(noError(e2,cb)){cb(null,inode,listing)}})}})};AsyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data,cb){var retries=0,currId;var reroll=function(){if(++retries===5){cb(new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store."))}else{currId=GenerateRandomID();tx.put(currId,data,false,function(e,committed){if(e||!committed){reroll()}else{cb(null,currId)}})}};reroll()};AsyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data,cb){var this$1=this;var parentDir=path.dirname(p),fname=path.basename(p),currTime=new Date().getTime();if(p==="/"){return cb(ApiError.EEXIST(p))}this.findINodeAndDirListing(tx,parentDir,function(e,parentNode,dirListing){if(noErrorTx(e,tx,cb)){if(dirListing[fname]){tx.abort(function(){cb(ApiError.EEXIST(p))})}else{this$1.addNewNode(tx,data,function(e2,dataId){if(noErrorTx(e2,tx,cb)){var fileInode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);this$1.addNewNode(tx,fileInode.toBuffer(),function(e3,fileInodeId){if(noErrorTx(e3,tx,cb)){dirListing[fname]=fileInodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(function(e5){if(noErrorTx(e5,tx,cb)){cb(null,fileInode)}})}})}})}})}}})};AsyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),fileName=path.basename(p);this.findINodeAndDirListing(tx,parent,function(e,parentNode,parentListing){if(noErrorTx(e,tx,cb)){if(!parentListing[fileName]){tx.abort(function(){cb(ApiError.ENOENT(p))})}else{var fileNodeId=parentListing[fileName];delete parentListing[fileName];this$1.getINode(tx,p,fileNodeId,function(e2,fileNode){if(noErrorTx(e2,tx,cb)){if(!isDir&&fileNode.isDirectory()){tx.abort(function(){cb(ApiError.EISDIR(p))})}else if(isDir&&!fileNode.isDirectory()){tx.abort(function(){cb(ApiError.ENOTDIR(p))})}else{tx.del(fileNode.id,function(e3){if(noErrorTx(e3,tx,cb)){tx.del(fileNodeId,function(e4){if(noErrorTx(e4,tx,cb)){tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true,function(e5){if(noErrorTx(e5,tx,cb)){tx.commit(cb)}})}})}})}}})}}})};return AsyncKeyValueFileSystem2}(BaseFileSystem);var InMemoryStore=function InMemoryStore2(){this.store={}};InMemoryStore.prototype.name=function name(){return InMemoryFileSystem.Name};InMemoryStore.prototype.clear=function clear(){this.store={}};InMemoryStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};InMemoryStore.prototype.get=function get(key){return this.store[key]};InMemoryStore.prototype.put=function put(key,data,overwrite){if(!overwrite&&this.store.hasOwnProperty(key)){return false}this.store[key]=data;return true};InMemoryStore.prototype.del=function del(key){delete this.store[key]};var InMemoryFileSystem=function(SyncKeyValueFileSystem$$1){function InMemoryFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new InMemoryStore})}if(SyncKeyValueFileSystem$$1)InMemoryFileSystem2.__proto__=SyncKeyValueFileSystem$$1;InMemoryFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);InMemoryFileSystem2.prototype.constructor=InMemoryFileSystem2;InMemoryFileSystem2.Create=function Create(options,cb){cb(null,new InMemoryFileSystem2)};return InMemoryFileSystem2}(SyncKeyValueFileSystem);InMemoryFileSystem.Name="InMemory";InMemoryFileSystem.Options={};var indexedDB=global$1.indexedDB||global$1.mozIndexedDB||global$1.webkitIndexedDB||global$1.msIndexedDB;function convertError$2(e,message){if(message===void 0)message=e.toString();switch(e.name){case"NotFoundError":return new ApiError(ErrorCode.ENOENT,message);case"QuotaExceededError":return new ApiError(ErrorCode.ENOSPC,message);default:return new ApiError(ErrorCode.EIO,message)}}function onErrorHandler(cb,code,message){if(code===void 0)code=ErrorCode.EIO;if(message===void 0)message=null;return function(e){e.preventDefault();cb(new ApiError(code,message!==null?message:void 0))}}var IndexedDBROTransaction=function IndexedDBROTransaction2(tx,store){this.tx=tx;this.store=store};IndexedDBROTransaction.prototype.get=function get(key,cb){try{var r=this.store.get(key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){var result=event.target.result;if(result===void 0){cb(null,result)}else{cb(null,arrayBuffer2Buffer(result))}}}catch(e){cb(convertError$2(e))}};var IndexedDBRWTransaction=function(IndexedDBROTransaction2){function IndexedDBRWTransaction2(tx,store){IndexedDBROTransaction2.call(this,tx,store)}if(IndexedDBROTransaction2)IndexedDBRWTransaction2.__proto__=IndexedDBROTransaction2;IndexedDBRWTransaction2.prototype=Object.create(IndexedDBROTransaction2&&IndexedDBROTransaction2.prototype);IndexedDBRWTransaction2.prototype.constructor=IndexedDBRWTransaction2;IndexedDBRWTransaction2.prototype.put=function put(key,data,overwrite,cb){try{var arraybuffer=buffer2ArrayBuffer(data);var r;if(overwrite){r=this.store.put(arraybuffer,key)}else{r=this.store.add(arraybuffer,key)}r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb(null,true)}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.del=function del(key,cb){try{var r=this.store["delete"](key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb()}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.commit=function commit(cb){setTimeout(cb,0)};IndexedDBRWTransaction2.prototype.abort=function abort(cb){var _e=null;try{this.tx.abort()}catch(e){_e=convertError$2(e)}finally{cb(_e)}};return IndexedDBRWTransaction2}(IndexedDBROTransaction);var IndexedDBStore=function IndexedDBStore2(cb,storeName){var this$1=this;if(storeName===void 0)storeName="browserfs";this.storeName=storeName;var openReq=indexedDB.open(this.storeName,1);openReq.onupgradeneeded=function(event){var db=event.target.result;if(db.objectStoreNames.contains(this$1.storeName)){db.deleteObjectStore(this$1.storeName)}db.createObjectStore(this$1.storeName)};openReq.onsuccess=function(event){this$1.db=event.target.result;cb(null,this$1)};openReq.onerror=onErrorHandler(cb,ErrorCode.EACCES)};IndexedDBStore.prototype.name=function name(){return IndexedDBFileSystem.Name+" - "+this.storeName};IndexedDBStore.prototype.clear=function clear(cb){try{var tx=this.db.transaction(this.storeName,"readwrite"),objectStore=tx.objectStore(this.storeName),r=objectStore.clear();r.onsuccess=function(event){setTimeout(cb,0)};r.onerror=onErrorHandler(cb)}catch(e){cb(convertError$2(e))}};IndexedDBStore.prototype.beginTransaction=function beginTransaction(type){if(type===void 0)type="readonly";var tx=this.db.transaction(this.storeName,type),objectStore=tx.objectStore(this.storeName);if(type==="readwrite"){return new IndexedDBRWTransaction(tx,objectStore)}else if(type==="readonly"){return new IndexedDBROTransaction(tx,objectStore)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid transaction type.")}};var IndexedDBFileSystem=function(AsyncKeyValueFileSystem$$1){function IndexedDBFileSystem2(cb,storeName,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;AsyncKeyValueFileSystem$$1.call(this);this.store=new IndexedDBStore(function(e){if(e){cb(e)}else{this$1.init(this$1.store,function(e2){cb(e2,this$1)})}},storeName);deprecationMessage(deprecateMsg,IndexedDBFileSystem2.Name,{storeName})}if(AsyncKeyValueFileSystem$$1)IndexedDBFileSystem2.__proto__=AsyncKeyValueFileSystem$$1;IndexedDBFileSystem2.prototype=Object.create(AsyncKeyValueFileSystem$$1&&AsyncKeyValueFileSystem$$1.prototype);IndexedDBFileSystem2.prototype.constructor=IndexedDBFileSystem2;IndexedDBFileSystem2.Create=function Create(opts,cb){new IndexedDBFileSystem2(cb,opts.storeName,false)};IndexedDBFileSystem2.isAvailable=function isAvailable(){try{return typeof indexedDB!=="undefined"&&null!==indexedDB.open("__browserfs_test__")}catch(e){return false}};return IndexedDBFileSystem2}(AsyncKeyValueFileSystem);IndexedDBFileSystem.Name="IndexedDB";IndexedDBFileSystem.Options={storeName:{type:"string",optional:true,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var supportsBinaryString=false;var binaryEncoding;try{global$1.localStorage.setItem("__test__",String.fromCharCode(55296));supportsBinaryString=global$1.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(e){supportsBinaryString=false}binaryEncoding=supportsBinaryString?"binary_string":"binary_string_ie";if(!Buffer2.isEncoding(binaryEncoding)){binaryEncoding="base64"}var LocalStorageStore=function LocalStorageStore2(){};LocalStorageStore.prototype.name=function name(){return LocalStorageFileSystem.Name};LocalStorageStore.prototype.clear=function clear(){global$1.localStorage.clear()};LocalStorageStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};LocalStorageStore.prototype.get=function get(key){try{var data=global$1.localStorage.getItem(key);if(data!==null){return Buffer2.from(data,binaryEncoding)}}catch(e){}return void 0};LocalStorageStore.prototype.put=function put(key,data,overwrite){try{if(!overwrite&&global$1.localStorage.getItem(key)!==null){return false}global$1.localStorage.setItem(key,data.toString(binaryEncoding));return true}catch(e){throw new ApiError(ErrorCode.ENOSPC,"LocalStorage is full.")}};LocalStorageStore.prototype.del=function del(key){try{global$1.localStorage.removeItem(key)}catch(e){throw new ApiError(ErrorCode.EIO,"Unable to delete key "+key+": "+e)}};var LocalStorageFileSystem=function(SyncKeyValueFileSystem$$1){function LocalStorageFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new LocalStorageStore})}if(SyncKeyValueFileSystem$$1)LocalStorageFileSystem2.__proto__=SyncKeyValueFileSystem$$1;LocalStorageFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);LocalStorageFileSystem2.prototype.constructor=LocalStorageFileSystem2;LocalStorageFileSystem2.Create=function Create(options,cb){cb(null,new LocalStorageFileSystem2)};LocalStorageFileSystem2.isAvailable=function isAvailable(){return typeof global$1.localStorage!=="undefined"};return LocalStorageFileSystem2}(SyncKeyValueFileSystem);LocalStorageFileSystem.Name="LocalStorage";LocalStorageFileSystem.Options={};var MountableFileSystem=function(BaseFileSystem$$1){function MountableFileSystem2(){BaseFileSystem$$1.call(this);this.mountList=[];this.mntMap={};this.rootFs=new InMemoryFileSystem}if(BaseFileSystem$$1)MountableFileSystem2.__proto__=BaseFileSystem$$1;MountableFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);MountableFileSystem2.prototype.constructor=MountableFileSystem2;MountableFileSystem2.Create=function Create(opts,cb){var fs4=new MountableFileSystem2;Object.keys(opts).forEach(function(mountPoint){fs4.mount(mountPoint,opts[mountPoint])});cb(null,fs4)};MountableFileSystem2.isAvailable=function isAvailable(){return true};MountableFileSystem2.prototype.mount=function mount(mountPoint,fs4){if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already taken.")}mkdirpSync(mountPoint,511,this.rootFs);this.mntMap[mountPoint]=fs4;this.mountList.push(mountPoint);this.mountList=this.mountList.sort(function(a,b){return b.length-a.length})};MountableFileSystem2.prototype.umount=function umount(mountPoint){var this$1=this;if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(!this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already unmounted.")}delete this.mntMap[mountPoint];this.mountList.splice(this.mountList.indexOf(mountPoint),1);while(mountPoint!=="/"){if(this$1.rootFs.readdirSync(mountPoint).length===0){this$1.rootFs.rmdirSync(mountPoint);mountPoint=path.dirname(mountPoint)}else{break}}};MountableFileSystem2.prototype._getFs=function _getFs(path$$1){var this$1=this;var mountList=this.mountList,len=mountList.length;for(var i2=0;i21?mountPoint.length:0);if(path$$1===""){path$$1="/"}return{fs:this$1.mntMap[mountPoint],path:path$$1}}}return{fs:this.rootFs,path:path$$1}};MountableFileSystem2.prototype.getName=function getName(){return MountableFileSystem2.Name};MountableFileSystem2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};MountableFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};MountableFileSystem2.prototype.supportsLinks=function supportsLinks(){return false};MountableFileSystem2.prototype.supportsProps=function supportsProps(){return false};MountableFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};MountableFileSystem2.prototype.standardizeError=function standardizeError(err,path$$1,realPath){var index=err.message.indexOf(path$$1);if(index!==-1){err.message=err.message.substr(0,index)+realPath+err.message.substr(index+path$$1.length);err.path=realPath}return err};MountableFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){return fs1rv.fs.rename(fs1rv.path,fs2rv.path,function(e){if(e){this$1.standardizeError(this$1.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath)}cb(e)})}return _fsMock.readFile(oldPath,function(err,data){if(err){return cb(err)}_fsMock.writeFile(newPath,data,function(err2){if(err2){return cb(err2)}_fsMock.unlink(oldPath,cb)})})};MountableFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){try{return fs1rv.fs.renameSync(fs1rv.path,fs2rv.path)}catch(e){this.standardizeError(this.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath);throw e}}var data=_fsMock.readFileSync(oldPath);_fsMock.writeFileSync(newPath,data);return _fsMock.unlinkSync(oldPath)};MountableFileSystem2.prototype.readdirSync=function readdirSync(p){var fsInfo=this._getFs(p);var rv=null;if(fsInfo.fs!==this.rootFs){try{rv=this.rootFs.readdirSync(p)}catch(e){}}try{var rv2=fsInfo.fs.readdirSync(fsInfo.path);if(rv===null){return rv2}else{return rv2.concat(rv.filter(function(val){return rv2.indexOf(val)===-1}))}}catch(e){if(rv===null){throw this.standardizeError(e,fsInfo.path,p)}else{return rv}}};MountableFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);fsInfo.fs.readdir(fsInfo.path,function(err,files){if(fsInfo.fs!==this$1.rootFs){try{var rv=this$1.rootFs.readdirSync(p);if(files){files=files.concat(rv.filter(function(val){return files.indexOf(val)===-1}))}else{files=rv}}catch(e){if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}}}else if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}cb(null,files)})};MountableFileSystem2.prototype.rmdirSync=function rmdirSync(p){var fsInfo=this._getFs(p);if(this._containsMountPt(p)){throw ApiError.ENOTEMPTY(p)}else{try{fsInfo.fs.rmdirSync(fsInfo.path)}catch(e){throw this.standardizeError(e,fsInfo.path,p)}}};MountableFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);if(this._containsMountPt(p)){cb(ApiError.ENOTEMPTY(p))}else{fsInfo.fs.rmdir(fsInfo.path,function(err){cb(err?this$1.standardizeError(err,fsInfo.path,p):null)})}};MountableFileSystem2.prototype._containsMountPt=function _containsMountPt(p){var mountPoints=this.mountList,len=mountPoints.length;for(var i2=0;i2=p.length&&pt.slice(0,p.length)===p){return true}}return false};return MountableFileSystem2}(BaseFileSystem);MountableFileSystem.Name="MountableFileSystem";MountableFileSystem.Options={};function defineFcn(name,isSync,numArgs){if(isSync){return function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;try{return rv.fs[name].apply(rv.fs,args)}catch(e){this.standardizeError(e,rv.path,path$$1);throw e}}}else{return function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;if(typeof args[args.length-1]==="function"){var cb=args[args.length-1];args[args.length-1]=function(){var args2=[],len2=arguments.length;while(len2--)args2[len2]=arguments[len2];if(args2.length>0&&args2[0]instanceof ApiError){this$1.standardizeError(args2[0],rv.path,path$$1)}cb.apply(null,args2)}}return rv.fs[name].apply(rv.fs,args)}}}var fsCmdMap=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]];for(var i=0;i0){var fn=timeouts.shift();return fn()}}};if(gScope.addEventListener){gScope.addEventListener("message",handleMessage,true)}else{gScope.attachEvent("onmessage",handleMessage)}}else if(gScope.MessageChannel){var channel=new gScope.MessageChannel;channel.port1.onmessage=function(event){if(timeouts.length>0){return timeouts.shift()()}};bfsSetImmediate=function(fn){timeouts.push(fn);channel.port2.postMessage("")}}else{bfsSetImmediate=function(fn){return setTimeout(fn,0)}}}var setImmediate$3=bfsSetImmediate;var Mutex=function Mutex2(){this._locked=false;this._waiters=[]};Mutex.prototype.lock=function lock(cb){if(this._locked){this._waiters.push(cb);return}this._locked=true;cb()};Mutex.prototype.unlock=function unlock(){if(!this._locked){throw new Error("unlock of a non-locked mutex")}var next=this._waiters.shift();if(next){setImmediate$3(next);return}this._locked=false};Mutex.prototype.tryLock=function tryLock(){if(this._locked){return false}this._locked=true;return true};Mutex.prototype.isLocked=function isLocked(){return this._locked};var LockedFS=function LockedFS2(fs4){this._fs=fs4;this._mu=new Mutex};LockedFS.prototype.getName=function getName(){return"LockedFS<"+this._fs.getName()+">"};LockedFS.prototype.getFSUnlocked=function getFSUnlocked(){return this._fs};LockedFS.prototype.initialize=function initialize3(cb){this._fs.initialize(cb)};LockedFS.prototype.diskSpace=function diskSpace(p,cb){this._fs.diskSpace(p,cb)};LockedFS.prototype.isReadOnly=function isReadOnly(){return this._fs.isReadOnly()};LockedFS.prototype.supportsLinks=function supportsLinks(){return this._fs.supportsLinks()};LockedFS.prototype.supportsProps=function supportsProps(){return this._fs.supportsProps()};LockedFS.prototype.supportsSynch=function supportsSynch(){return this._fs.supportsSynch()};LockedFS.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rename(oldPath,newPath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.renameSync=function renameSync(oldPath,newPath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.renameSync(oldPath,newPath)};LockedFS.prototype.stat=function stat(p,isLstat,cb){var this$1=this;this._mu.lock(function(){this$1._fs.stat(p,isLstat,function(err,stat2){this$1._mu.unlock();cb(err,stat2)})})};LockedFS.prototype.statSync=function statSync(p,isLstat){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.statSync(p,isLstat)};LockedFS.prototype.open=function open(p,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.open(p,flag,mode,function(err,fd){this$1._mu.unlock();cb(err,fd)})})};LockedFS.prototype.openSync=function openSync(p,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.openSync(p,flag,mode)};LockedFS.prototype.unlink=function unlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.unlink(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.unlinkSync=function unlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.unlinkSync(p)};LockedFS.prototype.rmdir=function rmdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rmdir(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.rmdirSync=function rmdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.rmdirSync(p)};LockedFS.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.mkdir(p,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.mkdirSync=function mkdirSync(p,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.mkdirSync(p,mode)};LockedFS.prototype.readdir=function readdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readdir(p,function(err,files){this$1._mu.unlock();cb(err,files)})})};LockedFS.prototype.readdirSync=function readdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readdirSync(p)};LockedFS.prototype.exists=function exists2(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.exists(p,function(exists3){this$1._mu.unlock();cb(exists3)})})};LockedFS.prototype.existsSync=function existsSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.existsSync(p)};LockedFS.prototype.realpath=function realpath(p,cache,cb){var this$1=this;this._mu.lock(function(){this$1._fs.realpath(p,cache,function(err,resolvedPath){this$1._mu.unlock();cb(err,resolvedPath)})})};LockedFS.prototype.realpathSync=function realpathSync(p,cache){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.realpathSync(p,cache)};LockedFS.prototype.truncate=function truncate(p,len,cb){var this$1=this;this._mu.lock(function(){this$1._fs.truncate(p,len,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.truncateSync=function truncateSync(p,len){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.truncateSync(p,len)};LockedFS.prototype.readFile=function readFile2(fname,encoding,flag,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readFile(fname,encoding,flag,function(err,data){this$1._mu.unlock();cb(err,data)})})};LockedFS.prototype.readFileSync=function readFileSync(fname,encoding,flag){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readFileSync(fname,encoding,flag)};LockedFS.prototype.writeFile=function writeFile2(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.writeFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.writeFileSync=function writeFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.writeFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.appendFile=function appendFile3(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.appendFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.appendFileSync=function appendFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.appendFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chmod(p,isLchmod,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chmodSync=function chmodSync(p,isLchmod,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chmodSync(p,isLchmod,mode)};LockedFS.prototype.chown=function chown(p,isLchown,uid,gid,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chown(p,isLchown,uid,gid,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chownSync=function chownSync(p,isLchown,uid,gid){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chownSync(p,isLchown,uid,gid)};LockedFS.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;this._mu.lock(function(){this$1._fs.utimes(p,atime,mtime,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.utimesSync=function utimesSync(p,atime,mtime){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.utimesSync(p,atime,mtime)};LockedFS.prototype.link=function link(srcpath,dstpath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.link(srcpath,dstpath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.linkSync=function linkSync(srcpath,dstpath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.linkSync(srcpath,dstpath)};LockedFS.prototype.symlink=function symlink(srcpath,dstpath,type,cb){var this$1=this;this._mu.lock(function(){this$1._fs.symlink(srcpath,dstpath,type,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.symlinkSync(srcpath,dstpath,type)};LockedFS.prototype.readlink=function readlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readlink(p,function(err,linkString){this$1._mu.unlock();cb(err,linkString)})})};LockedFS.prototype.readlinkSync=function readlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readlinkSync(p)};var deletionLogPath="/.deletedFiles.log";function makeModeWritable(mode){return 146|mode}function getFlag(f){return FileFlag.getFileFlag(f)}var OverlayFile=function(PreloadFile$$1){function OverlayFile2(fs4,path$$1,flag,stats,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stats,data)}if(PreloadFile$$1)OverlayFile2.__proto__=PreloadFile$$1;OverlayFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);OverlayFile2.prototype.constructor=OverlayFile2;OverlayFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){cb(null);return}this._fs._syncAsync(this,function(err){this$1.resetDirty();cb(err)})};OverlayFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};OverlayFile2.prototype.close=function close(cb){this.sync(cb)};OverlayFile2.prototype.closeSync=function closeSync(){this.syncSync()};return OverlayFile2}(PreloadFile);var UnlockedOverlayFS=function(BaseFileSystem$$1){function UnlockedOverlayFS2(writable,readable){BaseFileSystem$$1.call(this);this._isInitialized=false;this._initializeCallbacks=[];this._deletedFiles={};this._deleteLog="";this._deleteLogUpdatePending=false;this._deleteLogUpdateNeeded=false;this._deleteLogError=null;this._writable=writable;this._readable=readable;if(this._writable.isReadOnly()){throw new ApiError(ErrorCode.EINVAL,"Writable file system must be writable.")}}if(BaseFileSystem$$1)UnlockedOverlayFS2.__proto__=BaseFileSystem$$1;UnlockedOverlayFS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);UnlockedOverlayFS2.prototype.constructor=UnlockedOverlayFS2;UnlockedOverlayFS2.isAvailable=function isAvailable(){return true};UnlockedOverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return{readable:this._readable,writable:this._writable}};UnlockedOverlayFS2.prototype._syncAsync=function _syncAsync(file,cb){var this$1=this;this.createParentDirectoriesAsync(file.getPath(),function(err){if(err){return cb(err)}this$1._writable.writeFile(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode,cb)})};UnlockedOverlayFS2.prototype._syncSync=function _syncSync(file){this.createParentDirectories(file.getPath());this._writable.writeFileSync(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode)};UnlockedOverlayFS2.prototype.getName=function getName(){return OverlayFS.Name};UnlockedOverlayFS2.prototype.initialize=function initialize3(cb){var this$1=this;var callbackArray=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbackArray.forEach(function(cb2){return cb2(e)})};if(this._isInitialized){return cb()}callbackArray.push(cb);if(callbackArray.length!==1){return}this._writable.readFile(deletionLogPath,"utf8",getFlag("r"),function(err,data){if(err){if(err.errno!==ErrorCode.ENOENT){return end(err)}}else{this$1._deleteLog=data}this$1._reparseDeletionLog();end()})};UnlockedOverlayFS2.prototype.isReadOnly=function isReadOnly(){return false};UnlockedOverlayFS2.prototype.supportsSynch=function supportsSynch(){return this._readable.supportsSynch()&&this._writable.supportsSynch()};UnlockedOverlayFS2.prototype.supportsLinks=function supportsLinks(){return false};UnlockedOverlayFS2.prototype.supportsProps=function supportsProps(){return this._readable.supportsProps()&&this._writable.supportsProps()};UnlockedOverlayFS2.prototype.getDeletionLog=function getDeletionLog(){return this._deleteLog};UnlockedOverlayFS2.prototype.restoreDeletionLog=function restoreDeletionLog(log){this._deleteLog=log;this._reparseDeletionLog();this.updateLog("")};UnlockedOverlayFS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(oldPath,cb)||this.checkPathAsync(newPath,cb)){return}if(oldPath===deletionLogPath||newPath===deletionLogPath){return cb(ApiError.EPERM("Cannot rename deletion log."))}if(oldPath===newPath){return cb()}this.stat(oldPath,false,function(oldErr,oldStats){if(oldErr){return cb(oldErr)}return this$1.stat(newPath,false,function(newErr,newStats){var self2=this$1;function copyDirContents(files){var file=files.shift();if(!file){return cb()}var oldFile=path.resolve(oldPath,file);var newFile=path.resolve(newPath,file);self2.rename(oldFile,newFile,function(err){if(err){return cb(err)}copyDirContents(files)})}var mode=511;if(oldStats.isDirectory()){if(newErr){if(newErr.errno!==ErrorCode.ENOENT){return cb(newErr)}return this$1._writable.exists(oldPath,function(exists2){if(exists2){return this$1._writable.rename(oldPath,newPath,cb)}this$1._writable.mkdir(newPath,mode,function(mkdirErr){if(mkdirErr){return cb(mkdirErr)}this$1._readable.readdir(oldPath,function(err,files){if(err){return cb()}copyDirContents(files)})})})}mode=newStats.mode;if(!newStats.isDirectory()){return cb(ApiError.ENOTDIR(newPath))}this$1.readdir(newPath,function(readdirErr,files){if(files&&files.length){return cb(ApiError.ENOTEMPTY(newPath))}this$1._readable.readdir(oldPath,function(err,files2){if(err){return cb()}copyDirContents(files2)})})}if(newStats&&newStats.isDirectory()){return cb(ApiError.EISDIR(newPath))}this$1.readFile(oldPath,null,getFlag("r"),function(err,data){if(err){return cb(err)}return this$1.writeFile(newPath,data,null,getFlag("w"),oldStats.mode,function(err2){if(err2){return cb(err2)}return this$1.unlink(oldPath,cb)})})})})};UnlockedOverlayFS2.prototype.renameSync=function renameSync(oldPath,newPath){var this$1=this;this.checkInitialized();this.checkPath(oldPath);this.checkPath(newPath);if(oldPath===deletionLogPath||newPath===deletionLogPath){throw ApiError.EPERM("Cannot rename deletion log.")}var oldStats=this.statSync(oldPath,false);if(oldStats.isDirectory()){if(oldPath===newPath){return}var mode=511;if(this.existsSync(newPath)){var stats=this.statSync(newPath,false);mode=stats.mode;if(stats.isDirectory()){if(this.readdirSync(newPath).length>0){throw ApiError.ENOTEMPTY(newPath)}}else{throw ApiError.ENOTDIR(newPath)}}if(this._writable.existsSync(oldPath)){this._writable.renameSync(oldPath,newPath)}else if(!this._writable.existsSync(newPath)){this._writable.mkdirSync(newPath,mode)}if(this._readable.existsSync(oldPath)){this._readable.readdirSync(oldPath).forEach(function(name){this$1.renameSync(path.resolve(oldPath,name),path.resolve(newPath,name))})}}else{if(this.existsSync(newPath)&&this.statSync(newPath,false).isDirectory()){throw ApiError.EISDIR(newPath)}this.writeFileSync(newPath,this.readFileSync(oldPath,null,getFlag("r")),null,getFlag("w"),oldStats.mode)}if(oldPath!==newPath&&this.existsSync(oldPath)){this.unlinkSync(oldPath)}};UnlockedOverlayFS2.prototype.stat=function stat(p,isLstat,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this._writable.stat(p,isLstat,function(err,stat2){if(err&&err.errno===ErrorCode.ENOENT){if(this$1._deletedFiles[p]){cb(ApiError.ENOENT(p))}this$1._readable.stat(p,isLstat,function(err2,stat3){if(stat3){stat3=stat3.clone();stat3.mode=makeModeWritable(stat3.mode)}cb(err2,stat3)})}else{cb(err,stat2)}})};UnlockedOverlayFS2.prototype.statSync=function statSync(p,isLstat){this.checkInitialized();try{return this._writable.statSync(p,isLstat)}catch(e){if(this._deletedFiles[p]){throw ApiError.ENOENT(p)}var oldStat=this._readable.statSync(p,isLstat).clone();oldStat.mode=makeModeWritable(oldStat.mode);return oldStat}};UnlockedOverlayFS2.prototype.open=function open(p,flag,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.stat(p,false,function(err,stats){if(stats){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}this$1._writable.open(p,flag,mode,cb)});case ActionType.NOP:return this$1._writable.exists(p,function(exists2){if(exists2){this$1._writable.open(p,flag,mode,cb)}else{stats=stats.clone();stats.mode=mode;this$1._readable.readFile(p,null,getFlag("r"),function(readFileErr,data){if(readFileErr){return cb(readFileErr)}if(stats.size===-1){stats.size=data.length}var f=new OverlayFile(this$1,p,flag,stats,data);cb(null,f)})}});default:return cb(ApiError.EEXIST(p))}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}return this$1._writable.open(p,flag,mode,cb)});default:return cb(ApiError.ENOENT(p))}}})};UnlockedOverlayFS2.prototype.openSync=function openSync(p,flag,mode){this.checkInitialized();this.checkPath(p);if(p===deletionLogPath){throw ApiError.EPERM("Cannot open deletion log.")}if(this.existsSync(p)){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);case ActionType.NOP:if(this._writable.existsSync(p)){return this._writable.openSync(p,flag,mode)}else{var buf=this._readable.readFileSync(p,null,getFlag("r"));var stats=this._readable.statSync(p,false).clone();stats.mode=mode;return new OverlayFile(this,p,flag,stats,buf)}default:throw ApiError.EEXIST(p)}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);default:throw ApiError.ENOENT(p)}}};UnlockedOverlayFS2.prototype.unlink=function unlink(p,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){return this$1._writable.unlink(p,function(err){if(err){return cb(err)}this$1.exists(p,function(readableExists){if(readableExists){this$1.deletePath(p)}cb(null)})})}else{this$1.deletePath(p);cb(null)}})})};UnlockedOverlayFS2.prototype.unlinkSync=function unlinkSync(p){this.checkInitialized();this.checkPath(p);if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.unlinkSync(p)}if(this.existsSync(p)){this.deletePath(p)}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.rmdir=function rmdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}var rmdirLower=function(){this$1.readdir(p,function(err,files){if(err){return cb(err)}if(files.length){return cb(ApiError.ENOTEMPTY(p))}this$1.deletePath(p);cb(null)})};this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){this$1._writable.rmdir(p,function(err){if(err){return cb(err)}this$1._readable.exists(p,function(readableExists){if(readableExists){rmdirLower()}else{cb()}})})}else{rmdirLower()}})})};UnlockedOverlayFS2.prototype.rmdirSync=function rmdirSync(p){this.checkInitialized();if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.rmdirSync(p)}if(this.existsSync(p)){if(this.readdirSync(p).length>0){throw ApiError.ENOTEMPTY(p)}else{this.deletePath(p)}}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.exists(p,function(exists2){if(exists2){return cb(ApiError.EEXIST(p))}this$1.createParentDirectoriesAsync(p,function(err){if(err){return cb(err)}this$1._writable.mkdir(p,mode,cb)})})};UnlockedOverlayFS2.prototype.mkdirSync=function mkdirSync(p,mode){this.checkInitialized();if(this.existsSync(p)){throw ApiError.EEXIST(p)}else{this.createParentDirectories(p);this._writable.mkdirSync(p,mode)}};UnlockedOverlayFS2.prototype.readdir=function readdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.stat(p,false,function(err,dirStats){if(err){return cb(err)}if(!dirStats.isDirectory()){return cb(ApiError.ENOTDIR(p))}this$1._writable.readdir(p,function(err2,wFiles){if(err2&&err2.code!=="ENOENT"){return cb(err2)}else if(err2||!wFiles){wFiles=[]}this$1._readable.readdir(p,function(err3,rFiles){if(err3||!rFiles){rFiles=[]}var seenMap={};var filtered=wFiles.concat(rFiles.filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]})).filter(function(fPath){var result=!seenMap[fPath];seenMap[fPath]=true;return result});cb(null,filtered)})})})};UnlockedOverlayFS2.prototype.readdirSync=function readdirSync(p){var this$1=this;this.checkInitialized();var dirStats=this.statSync(p,false);if(!dirStats.isDirectory()){throw ApiError.ENOTDIR(p)}var contents=[];try{contents=contents.concat(this._writable.readdirSync(p))}catch(e){}try{contents=contents.concat(this._readable.readdirSync(p).filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]}))}catch(e){}var seenMap={};return contents.filter(function(fileP){var result=!seenMap[fileP];seenMap[fileP]=true;return result})};UnlockedOverlayFS2.prototype.exists=function exists2(p,cb){var this$1=this;this.checkInitialized();this._writable.exists(p,function(existsWritable){if(existsWritable){return cb(true)}this$1._readable.exists(p,function(existsReadable){cb(existsReadable&&this$1._deletedFiles[p]!==true)})})};UnlockedOverlayFS2.prototype.existsSync=function existsSync(p){this.checkInitialized();return this._writable.existsSync(p)||this._readable.existsSync(p)&&this._deletedFiles[p]!==true};UnlockedOverlayFS2.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chmod(p,isLchmod,mode,cb)}})};UnlockedOverlayFS2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chmodSync(p,isLchmod,mode)})};UnlockedOverlayFS2.prototype.chown=function chown(p,isLchmod,uid,gid,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chown(p,isLchmod,uid,gid,cb)}})};UnlockedOverlayFS2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chownSync(p,isLchown,uid,gid)})};UnlockedOverlayFS2.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.utimes(p,atime,mtime,cb)}})};UnlockedOverlayFS2.prototype.utimesSync=function utimesSync(p,atime,mtime){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.utimesSync(p,atime,mtime)})};UnlockedOverlayFS2.prototype.deletePath=function deletePath(p){this._deletedFiles[p]=true;this.updateLog("d"+p+"\n")};UnlockedOverlayFS2.prototype.updateLog=function updateLog(addition){var this$1=this;this._deleteLog+=addition;if(this._deleteLogUpdatePending){this._deleteLogUpdateNeeded=true}else{this._deleteLogUpdatePending=true;this._writable.writeFile(deletionLogPath,this._deleteLog,"utf8",FileFlag.getFileFlag("w"),420,function(e){this$1._deleteLogUpdatePending=false;if(e){this$1._deleteLogError=e}else if(this$1._deleteLogUpdateNeeded){this$1._deleteLogUpdateNeeded=false;this$1.updateLog("")}})}};UnlockedOverlayFS2.prototype._reparseDeletionLog=function _reparseDeletionLog(){var this$1=this;this._deletedFiles={};this._deleteLog.split("\n").forEach(function(path$$1){this$1._deletedFiles[path$$1.slice(1)]=path$$1.slice(0,1)==="d"})};UnlockedOverlayFS2.prototype.checkInitialized=function checkInitialized(){if(!this._isInitialized){throw new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;throw e}};UnlockedOverlayFS2.prototype.checkInitAsync=function checkInitAsync(cb){if(!this._isInitialized){cb(new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it."));return false}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;cb(e);return false}return true};UnlockedOverlayFS2.prototype.checkPath=function checkPath(p){if(p===deletionLogPath){throw ApiError.EPERM(p)}};UnlockedOverlayFS2.prototype.checkPathAsync=function checkPathAsync(p,cb){if(p===deletionLogPath){cb(ApiError.EPERM(p));return true}return false};UnlockedOverlayFS2.prototype.createParentDirectoriesAsync=function createParentDirectoriesAsync(p,cb){var parent=path.dirname(p);var toCreate=[];var self2=this;this._writable.stat(parent,false,statDone);function statDone(err,stat){if(err){toCreate.push(parent);parent=path.dirname(parent);self2._writable.stat(parent,false,statDone)}else{createParents()}}function createParents(){if(!toCreate.length){return cb()}var dir2=toCreate.pop();self2._readable.stat(dir2,false,function(err,stats){if(!stats){return cb()}self2._writable.mkdir(dir2,stats.mode,function(err2){if(err2){return cb(err2)}createParents()})})}};UnlockedOverlayFS2.prototype.createParentDirectories=function createParentDirectories(p){var this$1=this;var parent=path.dirname(p),toCreate=[];while(!this._writable.existsSync(parent)){toCreate.push(parent);parent=path.dirname(parent)}toCreate=toCreate.reverse();toCreate.forEach(function(p2){this$1._writable.mkdirSync(p2,this$1.statSync(p2,false).mode)})};UnlockedOverlayFS2.prototype.operateOnWritable=function operateOnWritable(p,f){if(this.existsSync(p)){if(!this._writable.existsSync(p)){this.copyToWritable(p)}f()}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.operateOnWritableAsync=function operateOnWritableAsync(p,cb){var this$1=this;this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(existsWritable){if(existsWritable){cb()}else{return this$1.copyToWritableAsync(p,cb)}})})};UnlockedOverlayFS2.prototype.copyToWritable=function copyToWritable(p){var pStats=this.statSync(p,false);if(pStats.isDirectory()){this._writable.mkdirSync(p,pStats.mode)}else{this.writeFileSync(p,this._readable.readFileSync(p,null,getFlag("r")),null,getFlag("w"),this.statSync(p,false).mode)}};UnlockedOverlayFS2.prototype.copyToWritableAsync=function copyToWritableAsync(p,cb){var this$1=this;this.stat(p,false,function(err,pStats){if(err){return cb(err)}if(pStats.isDirectory()){return this$1._writable.mkdir(p,pStats.mode,cb)}this$1._readable.readFile(p,null,getFlag("r"),function(err2,data){if(err2){return cb(err2)}this$1.writeFile(p,data,null,getFlag("w"),pStats.mode,cb)})})};return UnlockedOverlayFS2}(BaseFileSystem);var OverlayFS=function(LockedFS$$1){function OverlayFS2(writable,readable,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;LockedFS$$1.call(this,new UnlockedOverlayFS(writable,readable));deprecationMessage(deprecateMsg,OverlayFS2.Name,{readable:"readable file system",writable:"writable file system"})}if(LockedFS$$1)OverlayFS2.__proto__=LockedFS$$1;OverlayFS2.prototype=Object.create(LockedFS$$1&&LockedFS$$1.prototype);OverlayFS2.prototype.constructor=OverlayFS2;OverlayFS2.Create=function Create(opts,cb){try{var fs4=new OverlayFS2(opts.writable,opts.readable,false);fs4.initialize(function(e){cb(e,fs4)},false)}catch(e){cb(e)}};OverlayFS2.isAvailable=function isAvailable(){return UnlockedOverlayFS.isAvailable()};OverlayFS2.prototype.initialize=function initialize3(cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.")}LockedFS$$1.prototype.initialize.call(this,cb)};OverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()};OverlayFS2.prototype.unwrap=function unwrap(){return LockedFS$$1.prototype.getFSUnlocked.call(this)};return OverlayFS2}(LockedFS);OverlayFS.Name="OverlayFS";OverlayFS.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var SpecialArgType;(function(SpecialArgType2){SpecialArgType2[SpecialArgType2["CB"]=0]="CB";SpecialArgType2[SpecialArgType2["FD"]=1]="FD";SpecialArgType2[SpecialArgType2["API_ERROR"]=2]="API_ERROR";SpecialArgType2[SpecialArgType2["STATS"]=3]="STATS";SpecialArgType2[SpecialArgType2["PROBE"]=4]="PROBE";SpecialArgType2[SpecialArgType2["FILEFLAG"]=5]="FILEFLAG";SpecialArgType2[SpecialArgType2["BUFFER"]=6]="BUFFER";SpecialArgType2[SpecialArgType2["ERROR"]=7]="ERROR"})(SpecialArgType||(SpecialArgType={}));var CallbackArgumentConverter=function CallbackArgumentConverter2(){this._callbacks={};this._nextId=0};CallbackArgumentConverter.prototype.toRemoteArg=function toRemoteArg(cb){var id=this._nextId++;this._callbacks[id]=cb;return{type:SpecialArgType.CB,id}};CallbackArgumentConverter.prototype.toLocalArg=function toLocalArg(id){var cb=this._callbacks[id];delete this._callbacks[id];return cb};var FileDescriptorArgumentConverter=function FileDescriptorArgumentConverter2(){this._fileDescriptors={};this._nextId=0};FileDescriptorArgumentConverter.prototype.toRemoteArg=function toRemoteArg(fd,p,flag,cb){var id=this._nextId++;var data;var stat;this._fileDescriptors[id]=fd;fd.stat(function(err,stats){if(err){cb(err)}else{stat=bufferToTransferrableObject(stats.toBuffer());if(flag.isReadable()){fd.read(Buffer2.alloc(stats.size),0,stats.size,0,function(err2,bytesRead,buff){if(err2){cb(err2)}else{data=bufferToTransferrableObject(buff);cb(null,{type:SpecialArgType.FD,id,data,stat,path:p,flag:flag.getFlagString()})}})}else{cb(null,{type:SpecialArgType.FD,id,data:new ArrayBuffer(0),stat,path:p,flag:flag.getFlagString()})}}})};FileDescriptorArgumentConverter.prototype.applyFdAPIRequest=function applyFdAPIRequest(request,cb){var this$1=this;var fdArg=request.args[0];this._applyFdChanges(fdArg,function(err,fd){if(err){cb(err)}else{fd[request.method](function(e){if(request.method==="close"){delete this$1._fileDescriptors[fdArg.id]}cb(e)})}})};FileDescriptorArgumentConverter.prototype._applyFdChanges=function _applyFdChanges(remoteFd,cb){var fd=this._fileDescriptors[remoteFd.id],data=transferrableObjectToBuffer(remoteFd.data),remoteStats=Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));var flag=FileFlag.getFileFlag(remoteFd.flag);if(flag.isWriteable()){fd.write(data,0,data.length,flag.isAppendable()?fd.getPos():0,function(e){function applyStatChanges(){fd.stat(function(e2,stats){if(e2){cb(e2)}else{if(stats.mode!==remoteStats.mode){fd.chmod(remoteStats.mode,function(e3){cb(e3,fd)})}else{cb(e2,fd)}}})}if(e){cb(e)}else{if(!flag.isAppendable()){fd.truncate(data.length,function(){applyStatChanges()})}else{applyStatChanges()}}})}else{cb(null,fd)}};function apiErrorLocal2Remote(e){return{type:SpecialArgType.API_ERROR,errorData:bufferToTransferrableObject(e.writeToBuffer())}}function apiErrorRemote2Local(e){return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData))}function errorLocal2Remote(e){return{type:SpecialArgType.ERROR,name:e.name,message:e.message,stack:e.stack}}function errorRemote2Local(e){var cnstr=global$1[e.name];if(typeof cnstr!=="function"){cnstr=Error}var err=new cnstr(e.message);err.stack=e.stack;return err}function statsLocal2Remote(stats){return{type:SpecialArgType.STATS,statsData:bufferToTransferrableObject(stats.toBuffer())}}function statsRemote2Local(stats){return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData))}function fileFlagLocal2Remote(flag){return{type:SpecialArgType.FILEFLAG,flagStr:flag.getFlagString()}}function fileFlagRemote2Local(remoteFlag){return FileFlag.getFileFlag(remoteFlag.flagStr)}function bufferToTransferrableObject(buff){return buffer2ArrayBuffer(buff)}function transferrableObjectToBuffer(buff){return arrayBuffer2Buffer(buff)}function bufferLocal2Remote(buff){return{type:SpecialArgType.BUFFER,data:bufferToTransferrableObject(buff)}}function bufferRemote2Local(buffArg){return transferrableObjectToBuffer(buffArg.data)}function isAPIRequest(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}function isAPIResponse(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}var WorkerFile=function(PreloadFile$$1){function WorkerFile2(_fs,_path,_flag,_stat,remoteFdId,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents);this._remoteFdId=remoteFdId}if(PreloadFile$$1)WorkerFile2.__proto__=PreloadFile$$1;WorkerFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);WorkerFile2.prototype.constructor=WorkerFile2;WorkerFile2.prototype.getRemoteFdId=function getRemoteFdId(){return this._remoteFdId};WorkerFile2.prototype.toRemoteArg=function toRemoteArg(){return{type:SpecialArgType.FD,id:this._remoteFdId,data:bufferToTransferrableObject(this.getBuffer()),stat:bufferToTransferrableObject(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}};WorkerFile2.prototype.sync=function sync(cb){this._syncClose("sync",cb)};WorkerFile2.prototype.close=function close(cb){this._syncClose("close",cb)};WorkerFile2.prototype._syncClose=function _syncClose(type,cb){var this$1=this;if(this.isDirty()){this._fs.syncClose(type,this,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};return WorkerFile2}(PreloadFile);var WorkerFS=function(BaseFileSystem$$1){function WorkerFS2(worker,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._callbackConverter=new CallbackArgumentConverter;this._isInitialized=false;this._isReadOnly=false;this._supportLinks=false;this._supportProps=false;this._worker=worker;deprecationMessage(deprecateMsg,WorkerFS2.Name,{worker:"Web Worker instance"});this._worker.addEventListener("message",function(e){var resp=e.data;if(isAPIResponse(resp)){var i2;var args=resp.args;var fixedArgs=new Array(args.length);for(i2=0;i20){countdown=-1;message={browserfsMessage:true,cbId,args:[apiErrorLocal2Remote(err)]};worker.postMessage(message)}}for(i2=0;i20){var inode=void 0;var next=queue.pop();var pwd=next[0];var tree=next[1];var parent=next[2];for(var node in tree){if(tree.hasOwnProperty(node)){var children=tree[node];var name=pwd+"/"+node;if(children){idx._index[name]=inode=new DirInode;queue.push([name,children,inode])}else{inode=new FileInode(new Stats(FileType.FILE,-1,365))}if(parent){parent._ls[node]=inode}}}}return idx};FileIndex.prototype.fileIterator=function fileIterator(cb){var this$1=this;for(var path$$1 in this$1._index){if(this$1._index.hasOwnProperty(path$$1)){var dir2=this$1._index[path$$1];var files=dir2.getListing();for(var i2=0,list2=files;i20&&prefixUrl.charAt(prefixUrl.length-1)!=="/"){prefixUrl=prefixUrl+"/"}this.prefixUrl=prefixUrl;var listing=null;if(typeof listingUrlOrObj==="string"){listing=this._requestFileSync(listingUrlOrObj,"json");if(!listing){throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}}else{listing=listingUrlOrObj}deprecationMessage(deprecateMsg,XmlHttpRequest2.Name,{index:typeof listingUrlOrObj==="string"?listingUrlOrObj:"file index as an object",baseUrl:prefixUrl});this._index=FileIndex.fromListing(listing)}if(BaseFileSystem$$1)XmlHttpRequest2.__proto__=BaseFileSystem$$1;XmlHttpRequest2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);XmlHttpRequest2.prototype.constructor=XmlHttpRequest2;XmlHttpRequest2.Create=function Create(opts,cb){if(opts.index===void 0){opts.index="index.json"}if(typeof opts.index==="string"){XmlHttpRequest2.FromURL(opts.index,cb,opts.baseUrl,false)}else{cb(null,new XmlHttpRequest2(opts.index,opts.baseUrl,false))}};XmlHttpRequest2.isAvailable=function isAvailable(){return typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest!==null};XmlHttpRequest2.FromURL=function FromURL(url,cb,baseUrl,deprecateMsg){if(baseUrl===void 0)baseUrl=url.slice(0,url.lastIndexOf("/")+1);if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: "`+url+'", baseUrl: "'+baseUrl+`" }, cb)' instead.`)}asyncDownloadFile(url,"json",function(e,data){if(e){cb(e)}else{cb(null,new XmlHttpRequest2(data,baseUrl,false))}})};XmlHttpRequest2.prototype.empty=function empty(){this._index.fileIterator(function(file){file.fileData=null})};XmlHttpRequest2.prototype.getName=function getName(){return XmlHttpRequest2.Name};XmlHttpRequest2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};XmlHttpRequest2.prototype.isReadOnly=function isReadOnly(){return true};XmlHttpRequest2.prototype.supportsLinks=function supportsLinks(){return false};XmlHttpRequest2.prototype.supportsProps=function supportsProps(){return false};XmlHttpRequest2.prototype.supportsSynch=function supportsSynch(){return true};XmlHttpRequest2.prototype.preloadFile=function preloadFile(path$$1,buffer$$1){var inode=this._index.getInode(path$$1);if(isFileInode(inode)){if(inode===null){throw ApiError.ENOENT(path$$1)}var stats=inode.getData();stats.size=buffer$$1.length;stats.fileData=buffer$$1}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.stat=function stat(path$$1,isLstat,cb){var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){this._requestFileSizeAsync(path$$1,function(e,size){if(e){return cb(e)}stats.size=size;cb(null,stats.clone())})}else{cb(null,stats.clone())}}else if(isDirInode(inode)){stats=inode.getStats();cb(null,stats)}else{cb(ApiError.FileError(ErrorCode.EINVAL,path$$1))}};XmlHttpRequest2.prototype.statSync=function statSync(path$$1,isLstat){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){stats.size=this._requestFileSizeSync(path$$1)}}else if(isDirInode(inode)){stats=inode.getStats()}else{throw ApiError.FileError(ErrorCode.EINVAL,path$$1)}return stats};XmlHttpRequest2.prototype.open=function open(path$$1,flags,mode,cb){if(flags.isWriteable()){return cb(new ApiError(ErrorCode.EPERM,path$$1))}var self2=this;var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:return cb(ApiError.EEXIST(path$$1));case ActionType.NOP:if(stats.fileData){return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),stats.fileData))}this._requestFileAsync(path$$1,"buffer",function(err,buffer$$1){if(err){return cb(err)}stats.size=buffer$$1.length;stats.fileData=buffer$$1;return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),buffer$$1))});break;default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileMode object."))}}else{return cb(ApiError.EISDIR(path$$1))}};XmlHttpRequest2.prototype.openSync=function openSync(path$$1,flags,mode){if(flags.isWriteable()){throw new ApiError(ErrorCode.EPERM,path$$1)}var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:throw ApiError.EEXIST(path$$1);case ActionType.NOP:if(stats.fileData){return new NoSyncFile(this,path$$1,flags,stats.clone(),stats.fileData)}var buffer$$1=this._requestFileSync(path$$1,"buffer");stats.size=buffer$$1.length;stats.fileData=buffer$$1;return new NoSyncFile(this,path$$1,flags,stats.clone(),buffer$$1);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileMode object.")}}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.readdir=function readdir(path$$1,cb){try{cb(null,this.readdirSync(path$$1))}catch(e){cb(e)}};XmlHttpRequest2.prototype.readdirSync=function readdirSync(path$$1){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}else if(isDirInode(inode)){return inode.getListing()}else{throw ApiError.ENOTDIR(path$$1)}};XmlHttpRequest2.prototype.readFile=function readFile2(fname,encoding,flag,cb){var oldCb=cb;this.open(fname,flag,420,function(err,fd){if(err){return cb(err)}cb=function(err2,arg){fd.close(function(err22){if(!err2){err2=err22}return oldCb(err2,arg)})};var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){cb(err,copyingSlice(fdBuff))}else{tryToString(fdBuff,encoding,cb)}})};XmlHttpRequest2.prototype.readFileSync=function readFileSync(fname,encoding,flag){var fd=this.openSync(fname,flag,420);try{var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){return copyingSlice(fdBuff)}return fdBuff.toString(encoding)}finally{fd.closeSync()}};XmlHttpRequest2.prototype.getXhrPath=function getXhrPath(filePath){if(filePath.charAt(0)==="/"){filePath=filePath.slice(1)}return this.prefixUrl+filePath};XmlHttpRequest2.prototype._requestFileAsync=function _requestFileAsync(p,type,cb){asyncDownloadFile(this.getXhrPath(p),type,cb)};XmlHttpRequest2.prototype._requestFileSync=function _requestFileSync(p,type){return syncDownloadFile(this.getXhrPath(p),type)};XmlHttpRequest2.prototype._requestFileSizeAsync=function _requestFileSizeAsync(path$$1,cb){getFileSizeAsync(this.getXhrPath(path$$1),cb)};XmlHttpRequest2.prototype._requestFileSizeSync=function _requestFileSizeSync(path$$1){return getFileSizeSync(this.getXhrPath(path$$1))};return XmlHttpRequest2}(BaseFileSystem);XmlHttpRequest.Name="XmlHttpRequest";XmlHttpRequest.Options={index:{type:["string","object"],optional:true,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:true,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var ExtendedASCII=function ExtendedASCII2(){};ExtendedASCII.str2byte=function str2byte(str,buf){var length=str.length>buf.length?buf.length:str.length;for(var i2=0;i2127){var charIdx=ExtendedASCII.extendedChars.indexOf(str.charAt(i2));if(charIdx>-1){charCode=charIdx+128}}buf[charCode]=i2}return length};ExtendedASCII.byte2str=function byte2str(buff){var chars=new Array(buff.length);for(var i2=0;i2127){chars[i2]=ExtendedASCII.extendedChars[charCode-128]}else{chars[i2]=String.fromCharCode(charCode)}}return chars.join("")};ExtendedASCII.byteLength=function byteLength(str){return str.length};ExtendedASCII.extendedChars=["\xC7","\xFC","\xE9","\xE2","\xE4","\xE0","\xE5","\xE7","\xEA","\xEB","\xE8","\xEF","\xEE","\xEC","\xC4","\xC5","\xC9","\xE6","\xC6","\xF4","\xF6","\xF2","\xFB","\xF9","\xFF","\xD6","\xDC","\xF8","\xA3","\xD8","\xD7","\u0192","\xE1","\xED","\xF3","\xFA","\xF1","\xD1","\xAA","\xBA","\xBF","\xAE","\xAC","\xBD","\xBC","\xA1","\xAB","\xBB","_","_","_","\xA6","\xA6","\xC1","\xC2","\xC0","\xA9","\xA6","\xA6","+","+","\xA2","\xA5","+","+","-","-","+","-","+","\xE3","\xC3","+","+","-","-","\xA6","-","+","\xA4","\xF0","\xD0","\xCA","\xCB","\xC8","i","\xCD","\xCE","\xCF","+","+","_","_","\xA6","\xCC","_","\xD3","\xDF","\xD4","\xD2","\xF5","\xD5","\xB5","\xFE","\xDE","\xDA","\xDB","\xD9","\xFD","\xDD","\xAF","\xB4","\xAD","\xB1","_","\xBE","\xB6","\xA7","\xF7","\xB8","\xB0","\xA8","\xB7","\xB9","\xB3","\xB2","_"," "];var inflateRaw=__webpack_require__(31).inflateRaw;var decompressionMethods={};var ExternalFileAttributeType;(function(ExternalFileAttributeType2){ExternalFileAttributeType2[ExternalFileAttributeType2["MSDOS"]=0]="MSDOS";ExternalFileAttributeType2[ExternalFileAttributeType2["AMIGA"]=1]="AMIGA";ExternalFileAttributeType2[ExternalFileAttributeType2["OPENVMS"]=2]="OPENVMS";ExternalFileAttributeType2[ExternalFileAttributeType2["UNIX"]=3]="UNIX";ExternalFileAttributeType2[ExternalFileAttributeType2["VM_CMS"]=4]="VM_CMS";ExternalFileAttributeType2[ExternalFileAttributeType2["ATARI_ST"]=5]="ATARI_ST";ExternalFileAttributeType2[ExternalFileAttributeType2["OS2_HPFS"]=6]="OS2_HPFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MAC"]=7]="MAC";ExternalFileAttributeType2[ExternalFileAttributeType2["Z_SYSTEM"]=8]="Z_SYSTEM";ExternalFileAttributeType2[ExternalFileAttributeType2["CP_M"]=9]="CP_M";ExternalFileAttributeType2[ExternalFileAttributeType2["NTFS"]=10]="NTFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MVS"]=11]="MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["VSE"]=12]="VSE";ExternalFileAttributeType2[ExternalFileAttributeType2["ACORN_RISC"]=13]="ACORN_RISC";ExternalFileAttributeType2[ExternalFileAttributeType2["VFAT"]=14]="VFAT";ExternalFileAttributeType2[ExternalFileAttributeType2["ALT_MVS"]=15]="ALT_MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["BEOS"]=16]="BEOS";ExternalFileAttributeType2[ExternalFileAttributeType2["TANDEM"]=17]="TANDEM";ExternalFileAttributeType2[ExternalFileAttributeType2["OS_400"]=18]="OS_400";ExternalFileAttributeType2[ExternalFileAttributeType2["OSX"]=19]="OSX"})(ExternalFileAttributeType||(ExternalFileAttributeType={}));var CompressionMethod;(function(CompressionMethod2){CompressionMethod2[CompressionMethod2["STORED"]=0]="STORED";CompressionMethod2[CompressionMethod2["SHRUNK"]=1]="SHRUNK";CompressionMethod2[CompressionMethod2["REDUCED_1"]=2]="REDUCED_1";CompressionMethod2[CompressionMethod2["REDUCED_2"]=3]="REDUCED_2";CompressionMethod2[CompressionMethod2["REDUCED_3"]=4]="REDUCED_3";CompressionMethod2[CompressionMethod2["REDUCED_4"]=5]="REDUCED_4";CompressionMethod2[CompressionMethod2["IMPLODE"]=6]="IMPLODE";CompressionMethod2[CompressionMethod2["DEFLATE"]=8]="DEFLATE";CompressionMethod2[CompressionMethod2["DEFLATE64"]=9]="DEFLATE64";CompressionMethod2[CompressionMethod2["TERSE_OLD"]=10]="TERSE_OLD";CompressionMethod2[CompressionMethod2["BZIP2"]=12]="BZIP2";CompressionMethod2[CompressionMethod2["LZMA"]=14]="LZMA";CompressionMethod2[CompressionMethod2["TERSE_NEW"]=18]="TERSE_NEW";CompressionMethod2[CompressionMethod2["LZ77"]=19]="LZ77";CompressionMethod2[CompressionMethod2["WAVPACK"]=97]="WAVPACK";CompressionMethod2[CompressionMethod2["PPMD"]=98]="PPMD"})(CompressionMethod||(CompressionMethod={}));function msdos2date(time,date){var day=date&31;var month=(date>>5&15)-1;var year=(date>>9)+1980;var second=time&31;var minute=time>>5&63;var hour=time>>11;return new Date(year,month,day,hour,minute,second)}function safeToString(buff,useUTF8,start,length){if(length===0){return""}else if(useUTF8){return buff.toString("utf8",start,start+length)}else{return ExtendedASCII.byte2str(buff.slice(start,start+length))}}var FileHeader=function FileHeader2(data){this.data=data;if(data.readUInt32LE(0)!==67324752){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))}};FileHeader.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(4)};FileHeader.prototype.flags=function flags(){return this.data.readUInt16LE(6)};FileHeader.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(8)};FileHeader.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(10),this.data.readUInt16LE(12))};FileHeader.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(10)};FileHeader.prototype.crc32=function crc32(){return this.data.readUInt32LE(14)};FileHeader.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(26)};FileHeader.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(28)};FileHeader.prototype.fileName=function fileName(){return safeToString(this.data,this.useUTF8(),30,this.fileNameLength())};FileHeader.prototype.extraField=function extraField(){var start=30+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};FileHeader.prototype.totalSize=function totalSize(){return 30+this.fileNameLength()+this.extraFieldLength()};FileHeader.prototype.useUTF8=function useUTF8(){return(this.flags()&2048)===2048};var FileData=function FileData2(header,record,data){this.header=header;this.record=record;this.data=data};FileData.prototype.decompress=function decompress(){var compressionMethod=this.header.compressionMethod();var fcn=decompressionMethods[compressionMethod];if(fcn){return fcn(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag())}else{var name=CompressionMethod[compressionMethod];if(!name){name="Unknown: "+compressionMethod}throw new ApiError(ErrorCode.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+name)}};FileData.prototype.getHeader=function getHeader(){return this.header};FileData.prototype.getRecord=function getRecord(){return this.record};FileData.prototype.getRawData=function getRawData(){return this.data};var DataDescriptor=function DataDescriptor2(data){this.data=data};DataDescriptor.prototype.crc32=function crc32(){return this.data.readUInt32LE(0)};DataDescriptor.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(4)};DataDescriptor.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(8)};var ArchiveExtraDataRecord=function ArchiveExtraDataRecord2(data){this.data=data;if(this.data.readUInt32LE(0)!==134630224){throw new ApiError(ErrorCode.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))}};ArchiveExtraDataRecord.prototype.length=function length(){return this.data.readUInt32LE(4)};ArchiveExtraDataRecord.prototype.extraFieldData=function extraFieldData(){return this.data.slice(8,8+this.length())};var DigitalSignature=function DigitalSignature2(data){this.data=data;if(this.data.readUInt32LE(0)!==84233040){throw new ApiError(ErrorCode.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))}};DigitalSignature.prototype.size=function size(){return this.data.readUInt16LE(4)};DigitalSignature.prototype.signatureData=function signatureData(){return this.data.slice(6,6+this.size())};var CentralDirectory=function CentralDirectory2(zipData,data){this.zipData=zipData;this.data=data;if(this.data.readUInt32LE(0)!==33639248){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0))}this._filename=this.produceFilename()};CentralDirectory.prototype.versionMadeBy=function versionMadeBy(){return this.data.readUInt16LE(4)};CentralDirectory.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(6)};CentralDirectory.prototype.flag=function flag(){return this.data.readUInt16LE(8)};CentralDirectory.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(10)};CentralDirectory.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(12),this.data.readUInt16LE(14))};CentralDirectory.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(12)};CentralDirectory.prototype.crc32=function crc32(){return this.data.readUInt32LE(16)};CentralDirectory.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(20)};CentralDirectory.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(24)};CentralDirectory.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(28)};CentralDirectory.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(30)};CentralDirectory.prototype.fileCommentLength=function fileCommentLength(){return this.data.readUInt16LE(32)};CentralDirectory.prototype.diskNumberStart=function diskNumberStart(){return this.data.readUInt16LE(34)};CentralDirectory.prototype.internalAttributes=function internalAttributes(){return this.data.readUInt16LE(36)};CentralDirectory.prototype.externalAttributes=function externalAttributes(){return this.data.readUInt32LE(38)};CentralDirectory.prototype.headerRelativeOffset=function headerRelativeOffset(){return this.data.readUInt32LE(42)};CentralDirectory.prototype.produceFilename=function produceFilename(){var fileName=safeToString(this.data,this.useUTF8(),46,this.fileNameLength());return fileName.replace(/\\/g,"/")};CentralDirectory.prototype.fileName=function fileName(){return this._filename};CentralDirectory.prototype.rawFileName=function rawFileName(){return this.data.slice(46,46+this.fileNameLength())};CentralDirectory.prototype.extraField=function extraField(){var start=44+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};CentralDirectory.prototype.fileComment=function fileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return safeToString(this.data,this.useUTF8(),start,this.fileCommentLength())};CentralDirectory.prototype.rawFileComment=function rawFileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(start,start+this.fileCommentLength())};CentralDirectory.prototype.totalSize=function totalSize(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()};CentralDirectory.prototype.isDirectory=function isDirectory(){var fileName=this.fileName();return(this.externalAttributes()&16?true:false)||fileName.charAt(fileName.length-1)==="/"};CentralDirectory.prototype.isFile=function isFile(){return!this.isDirectory()};CentralDirectory.prototype.useUTF8=function useUTF8(){return(this.flag()&2048)===2048};CentralDirectory.prototype.isEncrypted=function isEncrypted(){return(this.flag()&1)===1};CentralDirectory.prototype.getFileData=function getFileData(){var start=this.headerRelativeOffset();var header=new FileHeader(this.zipData.slice(start));return new FileData(header,this,this.zipData.slice(start+header.totalSize()))};CentralDirectory.prototype.getData=function getData(){return this.getFileData().decompress()};CentralDirectory.prototype.getRawData=function getRawData(){return this.getFileData().getRawData()};CentralDirectory.prototype.getStats=function getStats(){return new Stats(FileType.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var EndOfCentralDirectory=function EndOfCentralDirectory2(data){this.data=data;if(this.data.readUInt32LE(0)!==101010256){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))}};EndOfCentralDirectory.prototype.diskNumber=function diskNumber(){return this.data.readUInt16LE(4)};EndOfCentralDirectory.prototype.cdDiskNumber=function cdDiskNumber(){return this.data.readUInt16LE(6)};EndOfCentralDirectory.prototype.cdDiskEntryCount=function cdDiskEntryCount(){return this.data.readUInt16LE(8)};EndOfCentralDirectory.prototype.cdTotalEntryCount=function cdTotalEntryCount(){return this.data.readUInt16LE(10)};EndOfCentralDirectory.prototype.cdSize=function cdSize(){return this.data.readUInt32LE(12)};EndOfCentralDirectory.prototype.cdOffset=function cdOffset(){return this.data.readUInt32LE(16)};EndOfCentralDirectory.prototype.cdZipCommentLength=function cdZipCommentLength(){return this.data.readUInt16LE(20)};EndOfCentralDirectory.prototype.cdZipComment=function cdZipComment(){return safeToString(this.data,true,22,this.cdZipCommentLength())};EndOfCentralDirectory.prototype.rawCdZipComment=function rawCdZipComment(){return this.data.slice(22,22+this.cdZipCommentLength())};var ZipTOC=function ZipTOC2(index,directoryEntries,eocd,data){this.index=index;this.directoryEntries=directoryEntries;this.eocd=eocd;this.data=data};var ZipFS=function(SynchronousFileSystem$$1){function ZipFS2(input,name,deprecateMsg){if(name===void 0)name="";if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this.name=name;this._index=new FileIndex;this._directoryEntries=[];this._eocd=null;deprecationMessage(deprecateMsg,ZipFS2.Name,{zipData:"zip data as a Buffer",name});if(input instanceof ZipTOC){this._index=input.index;this._directoryEntries=input.directoryEntries;this._eocd=input.eocd;this.data=input.data}else{this.data=input;this.populateIndex()}}if(SynchronousFileSystem$$1)ZipFS2.__proto__=SynchronousFileSystem$$1;ZipFS2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);ZipFS2.prototype.constructor=ZipFS2;ZipFS2.Create=function Create(opts,cb){try{ZipFS2.computeIndex(opts.zipData,function(zipTOC){var fs4=new ZipFS2(zipTOC,opts.name,false);cb(null,fs4)},false)}catch(e){cb(e)}};ZipFS2.isAvailable=function isAvailable(){return true};ZipFS2.RegisterDecompressionMethod=function RegisterDecompressionMethod(m,fcn){decompressionMethods[m]=fcn};ZipFS2.computeIndex=function computeIndex(data,cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.")}var index=new FileIndex;var eocd=ZipFS2.getEOCD(data);if(eocd.diskNumber()!==eocd.cdDiskNumber()){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support spanned zip files.")}var cdPtr=eocd.cdOffset();if(cdPtr===4294967295){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support Zip64.")}var cdEnd=cdPtr+eocd.cdSize();ZipFS2.computeIndexResponsive(data,index,cdPtr,cdEnd,cb,[],eocd)};ZipFS2.getEOCD=function getEOCD(data){var startOffset=22;var endOffset=Math.min(startOffset+65535,data.length-1);for(var i2=startOffset;i2-1};DirectoryRecord.prototype.getRockRidgeOffset=function getRockRidgeOffset(){return this._rockRidgeOffset};DirectoryRecord.prototype.rootCheckForRockRidge=function rootCheckForRockRidge(isoData){var dir2=this.getDirectory(isoData);this._rockRidgeOffset=dir2.getDotEntry(isoData)._getRockRidgeOffset(isoData);if(this._rockRidgeOffset>-1){this._fileOrDir=null}};DirectoryRecord.prototype.length=function length(){return this._data[0]};DirectoryRecord.prototype.extendedAttributeRecordLength=function extendedAttributeRecordLength(){return this._data[1]};DirectoryRecord.prototype.lba=function lba(){return this._data.readUInt32LE(2)*2048};DirectoryRecord.prototype.dataLength=function dataLength(){return this._data.readUInt32LE(10)};DirectoryRecord.prototype.recordingDate=function recordingDate(){return getShortFormDate(this._data,18)};DirectoryRecord.prototype.fileFlags=function fileFlags(){return this._data[25]};DirectoryRecord.prototype.fileUnitSize=function fileUnitSize(){return this._data[26]};DirectoryRecord.prototype.interleaveGapSize=function interleaveGapSize(){return this._data[27]};DirectoryRecord.prototype.volumeSequenceNumber=function volumeSequenceNumber(){return this._data.readUInt16LE(28)};DirectoryRecord.prototype.identifier=function identifier(){return this._getString(33,this._data[32])};DirectoryRecord.prototype.fileName=function fileName(isoData){if(this.hasRockRidge()){var fn=this._rockRidgeFilename(isoData);if(fn!==null){return fn}}var ident=this.identifier();if(this.isDirectory(isoData)){return ident}var versionSeparator=ident.indexOf(";");if(versionSeparator===-1){return ident}else if(ident[versionSeparator-1]==="."){return ident.slice(0,versionSeparator-1)}else{return ident.slice(0,versionSeparator)}};DirectoryRecord.prototype.isDirectory=function isDirectory(isoData){var rv=!!(this.fileFlags()&2);if(!rv&&this.hasRockRidge()){rv=this.getSUEntries(isoData).filter(function(e){return e instanceof CLEntry}).length>0}return rv};DirectoryRecord.prototype.isSymlink=function isSymlink(isoData){return this.hasRockRidge()&&this.getSUEntries(isoData).filter(function(e){return e instanceof SLEntry}).length>0};DirectoryRecord.prototype.getSymlinkPath=function getSymlinkPath(isoData){var p="";var entries=this.getSUEntries(isoData);var getStr=this._getGetString();for(var i2=0,list2=entries;i21&&p[p.length-1]==="/"){return p.slice(0,p.length-1)}else{return p}};DirectoryRecord.prototype.getFile=function getFile(isoData){if(this.isDirectory(isoData)){throw new Error("Tried to get a File from a directory.")}if(this._fileOrDir===null){this._fileOrDir=isoData.slice(this.lba(),this.lba()+this.dataLength())}return this._fileOrDir};DirectoryRecord.prototype.getDirectory=function getDirectory(isoData){if(!this.isDirectory(isoData)){throw new Error("Tried to get a Directory from a file.")}if(this._fileOrDir===null){this._fileOrDir=this._constructDirectory(isoData)}return this._fileOrDir};DirectoryRecord.prototype.getSUEntries=function getSUEntries(isoData){if(!this._suEntries){this._constructSUEntries(isoData)}return this._suEntries};DirectoryRecord.prototype._rockRidgeFilename=function _rockRidgeFilename(isoData){var nmEntries=this.getSUEntries(isoData).filter(function(e2){return e2 instanceof NMEntry});if(nmEntries.length===0||nmEntries[0].flags()&(2|4)){return null}var str="";var getString=this._getGetString();for(var i2=0,list2=nmEntries;i20){var spEntry=suEntries[0];if(spEntry instanceof SPEntry&&spEntry.checkBytesPass()){for(var i2=1;i2K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer2.prototype;return buf}function Buffer2(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer2[Symbol.species]===Buffer2){Object.defineProperty(Buffer2,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer2.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer2.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer2.prototype.__proto__=Uint8Array.prototype;Buffer2.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==void 0){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer2.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer2.allocUnsafe=function(size){return allocUnsafe(size)};Buffer2.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer2.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer2.alloc(+length)}Buffer2.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer2.compare=function compare(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer2.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===void 0||start<0){start=0}if(start>this.length){return""}if(end===void 0||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer2.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer2.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer2.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer2.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===void 0){start=0}if(end===void 0){end=target?target.length:0}if(thisStart===void 0){thisStart=0}if(thisEnd===void 0){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir2?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir2)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir2)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer2.from(val,encoding)}if(Buffer2.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir2)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir2){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir2)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir2){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==void 0){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i2){if(indexSize===1){return buf[i2]}else{return buf.readUInt16BE(i2*indexSize)}}var i;if(dir2){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===void 0)encoding="utf8"}else{encoding=length;length=void 0}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===void 0||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer2.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer2.prototype.readUIntLE=function readUIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){checkOffset(offset,byteLength2,this.length)}var val=this[offset+--byteLength2];var mul=1;while(byteLength2>0&&(mul*=256)){val+=this[offset+--byteLength2]*mul}return val};Buffer2.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer2.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer2.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer2.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer2.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer2.prototype.readIntLE=function readIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readIntBE=function readIntBE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var i=byteLength2;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer2.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer2.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer2.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer2.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer2.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer2.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer2.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer2.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var i=byteLength2-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength2};Buffer2.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer2.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer2.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer2.prototype.writeIntLE=function writeIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeIntBE=function writeIntBE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=byteLength2-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer2.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer2.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer2.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer2.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer2.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer2.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer2.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i>>0;end=end===void 0?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}}).call(exports2,__webpack_require__(1))},function(module2,exports2){"use strict";exports2.byteLength=byteLength;exports2.toByteArray=toByteArray;exports2.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len2-2]==="="?2:b64[len2-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i2,j,l,tmp,placeHolders,arr;var len2=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len2*3/4-placeHolders);l=placeHolders>0?len2-4:len2;var L=0;for(i2=0,j=0;i2>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i2=start;i2len22?len22:i2+maxChunkLength))}if(extraBytes===1){tmp=uint8[len2-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len2-2]<<8)+uint8[len2-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},function(module2,exports2){exports2.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports2.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},function(module2,exports2){module2.exports=function(module3){if(!module3.webpackPolyfill){module3.deprecate=function(){};module3.paths=[];module3.children=[];module3.webpackPolyfill=1}return module3}},function(module2,exports2,__webpack_require__){"use strict";var Process=__webpack_require__(7);var process=new Process,processProxy={};function defineKey(key2){if(processProxy[key2]){return}if(typeof process[key2]==="function"){processProxy[key2]=function(){return process[key2].apply(process,arguments)}}else{processProxy[key2]=process[key2]}}for(var key in process){defineKey(key)}processProxy.initializeTTYs=function(){if(process.stdin===null){process.initializeTTYs();processProxy.stdin=process.stdin;processProxy.stdout=process.stdout;processProxy.stderr=process.stderr}};process.nextTick(function(){processProxy.initializeTTYs()});module2.exports=processProxy},function(module2,exports2,__webpack_require__){(function(__dirname){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var events=__webpack_require__(8);var path=null;var Item=function(){function Item2(fun,array){this.fun=fun;this.array=array}Item2.prototype.run=function(){this.fun.apply(null,this.array)};return Item2}();var NextTickQueue=function(){function NextTickQueue2(){this._queue=[];this._draining=false;this._currentQueue=null;this._queueIndex=-1}NextTickQueue2.prototype.push=function(item){var _this=this;if(this._queue.push(item)===1&&!this._draining){setTimeout(function(){return _this._drainQueue()},0)}};NextTickQueue2.prototype._cleanUpNextTick=function(){this._draining=false;if(this._currentQueue&&this._currentQueue.length){this._queue=this._currentQueue.concat(this._queue)}else{this._queueIndex=-1}if(this._queue.length){this._drainQueue()}};NextTickQueue2.prototype._drainQueue=function(){var _this=this;if(this._draining){return}var timeout=setTimeout(function(){return _this._cleanUpNextTick()});this._draining=true;var len=this._queue.length;while(len){this._currentQueue=this._queue;this._queue=[];while(++this._queueIndex0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module2,exports2,__webpack_require__){(function(process){"use strict";var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;function posixSplitPath(filename){var out=splitPathRe.exec(filename);out.shift();return out}var path=function(){function path2(){}path2.normalize=function(p){if(p===""){p="."}var absolute=p.charAt(0)===path2.sep;p=path2._removeDuplicateSeps(p);var components=p.split(path2.sep);var goodComponents=[];for(var idx=0;idx0&&goodComponents[0]!=="..")){goodComponents.pop()}else{goodComponents.push(c)}}if(!absolute&&goodComponents.length<2){switch(goodComponents.length){case 1:if(goodComponents[0]===""){goodComponents.unshift(".")}break;default:goodComponents.push(".")}}p=goodComponents.join(path2.sep);if(absolute&&p.charAt(0)!==path2.sep){p=path2.sep+p}return p};path2.join=function(){var paths=[];for(var _i=0;_i1&&resolved.charAt(resolved.length-1)===path2.sep){return resolved.substr(0,resolved.length-1)}if(resolved.charAt(0)!==path2.sep){if(resolved.charAt(0)==="."&&(resolved.length===1||resolved.charAt(1)===path2.sep)){resolved=resolved.length===1?"":resolved.substr(2)}var cwd=process.cwd();if(resolved!==""){resolved=this.normalize(cwd+(cwd!=="/"?path2.sep:"")+resolved)}else{resolved=cwd}}return resolved};path2.relative=function(from,to){var i;from=path2.resolve(from);to=path2.resolve(to);var fromSegs=from.split(path2.sep);var toSegs=to.split(path2.sep);toSegs.shift();fromSegs.shift();var upCount=0;var downSegs=[];for(i=0;ifromSegs.length){upCount=fromSegs.length}var rv="";for(i=0;i1&&rv.charAt(rv.length-1)===path2.sep){rv=rv.substr(0,rv.length-1)}return rv};path2.dirname=function(p){p=path2._removeDuplicateSeps(p);var absolute=p.charAt(0)===path2.sep;var sections=p.split(path2.sep);if(sections.pop()===""&§ions.length>0){sections.pop()}if(sections.length>1||sections.length===1&&!absolute){return sections.join(path2.sep)}else if(absolute){return path2.sep}else{return"."}};path2.basename=function(p,ext){if(ext===void 0){ext=""}if(p===""){return p}p=path2.normalize(p);var sections=p.split(path2.sep);var lastPart=sections[sections.length-1];if(lastPart===""&§ions.length>1){return sections[sections.length-2]}if(ext.length>0){var lastPartExt=lastPart.substr(lastPart.length-ext.length);if(lastPartExt===ext){return lastPart.substr(0,lastPart.length-ext.length)}}return lastPart};path2.extname=function(p){p=path2.normalize(p);var sections=p.split(path2.sep);p=sections.pop();if(p===""&§ions.length>0){p=sections.pop()}if(p===".."){return""}var i=p.lastIndexOf(".");if(i===-1||i===0){return""}return p.substr(i)};path2.isAbsolute=function(p){return p.length>0&&p.charAt(0)===path2.sep};path2._makeLong=function(p){return p};path2.parse=function(p){var allParts=posixSplitPath(p);return{root:allParts[0],dir:allParts[0]+allParts[1].slice(0,-1),base:allParts[2],ext:allParts[3],name:allParts[2].slice(0,allParts[2].length-allParts[3].length)}};path2.format=function(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof pathObject)}var root=pathObject.root||"";if(typeof root!=="string"){throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof pathObject.root)}var dir2=pathObject.dir?pathObject.dir+path2.sep:"";var base=pathObject.base||"";return dir2+base};path2._removeDuplicateSeps=function(p){p=p.replace(this._replaceRegex,this.sep);return p};path2.sep="/";path2._replaceRegex=new RegExp("//+","g");path2.delimiter=":";path2.posix=path2;path2.win32=path2;return path2}();var _=path;module2.exports=path}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(Buffer2){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var stream=__webpack_require__(11);var TTY=function(_super){__extends(TTY2,_super);function TTY2(){_super.call(this);this.isRaw=false;this.columns=80;this.rows=120;this.isTTY=true;this._bufferedWrites=[];this._waitingForWrites=false}TTY2.prototype.setRawMode=function(mode){if(this.isRaw!==mode){this.isRaw=mode;this.emit("modeChange")}};TTY2.prototype.changeColumns=function(columns){if(columns!==this.columns){this.columns=columns;this.emit("resize")}};TTY2.prototype.changeRows=function(rows){if(rows!==this.rows){this.rows=rows;this.emit("resize")}};TTY2.isatty=function(fd){return fd&&fd instanceof TTY2};TTY2.prototype._write=function(chunk,encoding,cb){var error;try{var data;if(typeof chunk==="string"){data=new Buffer2(chunk,encoding)}else{data=chunk}this._bufferedWrites.push(data);if(this._waitingForWrites){this._read(1024)}}catch(e){error=e}finally{cb(error)}};TTY2.prototype._read=function(size){if(this._bufferedWrites.length===0){this._waitingForWrites=true}else{while(this._bufferedWrites.length>0){this._waitingForWrites=this.push(this._bufferedWrites.shift());if(!this._waitingForWrites){break}}}};return TTY2}(stream.Duplex);module2.exports=TTY}).call(exports2,__webpack_require__(1))},function(module2,exports2,__webpack_require__){module2.exports=Stream;var EE=__webpack_require__(8).EventEmitter;var inherits=__webpack_require__(12);inherits(Stream,EE);Stream.Readable=__webpack_require__(13);Stream.Writable=__webpack_require__(27);Stream.Duplex=__webpack_require__(28);Stream.Transform=__webpack_require__(29);Stream.PassThrough=__webpack_require__(30);Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},function(module2,exports2){if(typeof Object.create==="function"){module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},function(module2,exports2,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(11)}catch(_){}}();exports2=module2.exports=__webpack_require__(14);exports2.Stream=Stream||exports2;exports2.Readable=exports2;exports2.Writable=__webpack_require__(22);exports2.Duplex=__webpack_require__(21);exports2.Transform=__webpack_require__(25);exports2.PassThrough=__webpack_require__(26);if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module2.exports=Stream}}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(process){"use strict";module2.exports=Readable;var processNextTick=__webpack_require__(15);var isArray=__webpack_require__(16);var Duplex;Readable.ReadableState=ReadableState;var EE=__webpack_require__(8).EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var debugUtil=__webpack_require__(19);var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=__webpack_require__(20);var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=__webpack_require__(24).StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||__webpack_require__(21);if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer2.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;iMAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===void 0){enc=void 0;_fill=0}var buf=new Buffer2(size);if(typeof _fill==="string"){var fillBuf=new Buffer2(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer2(size)};exports2.from=function from(value,encodingOrOffset,length){if(typeof Buffer2.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer2.from)){return Buffer2.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer2(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer2(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer2(value.slice(offset,offset+len))}if(Buffer2.isBuffer(value)){var out=new Buffer2(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer2(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer2(value.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")};exports2.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer2.allocUnsafeSlow==="function"){return Buffer2.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(exports2,function(){return this}())},function(module2,exports2,__webpack_require__){(function(Buffer2){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports2.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports2.isBoolean=isBoolean;function isNull(arg){return arg===null}exports2.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports2.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports2.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports2.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports2.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports2.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports2.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports2.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports2.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports2.isError=isError;function isFunction(arg){return typeof arg==="function"}exports2.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports2.isPrimitive=isPrimitive;exports2.isBuffer=Buffer2.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(exports2,__webpack_require__(1))},function(module2,exports2){},function(module2,exports2,__webpack_require__){"use strict";var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);module2.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},function(module2,exports2,__webpack_require__){"use strict";var objectKeys=Object.keys||function(obj){var keys2=[];for(var key in obj){keys2.push(key)}return keys2};module2.exports=Duplex;var processNextTick=__webpack_require__(15);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var Readable=__webpack_require__(14);var Writable=__webpack_require__(22);util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var internalUtil={deprecate:__webpack_require__(23)};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||__webpack_require__(21);if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer2.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer2.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},function(module2,exports2,__webpack_require__){"use strict";module2.exports=Transform;var Duplex=__webpack_require__(21);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==void 0)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg||msg[inflator.err]}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports2.Inflate=Inflate;exports2.inflate=inflate;exports2.inflateRaw=inflateRaw;exports2.ungzip=inflate},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var adler32=__webpack_require__(34);var crc32=__webpack_require__(35);var inflate_fast=__webpack_require__(36);var inflate_table=__webpack_require__(37);var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&©>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module2.exports=adler32},function(module2,exports2){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255]}return crc^-1}module2.exports=crc32},function(module2,exports2){"use strict";var BAD=30;var TYPE=12;module2.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits>>=op;bits-=op}if(bits<15){hold+=input[_in++]<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bitsdmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3;_in-=len;bits-=len<<3;hold&=(1<=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}for(;;){here_bits=len-drop;if(work[sym]end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports2.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports2.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},function(module2,exports2){"use strict";module2.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(module2,exports2){"use strict";module2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(module2,exports2){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module2.exports=ZStream},function(module2,exports2){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module2.exports=GZheader}])})}});var CSV=class{constructor(onOpen=this.onOpen,saveButtonId=null,openButtonId=null){this.onOpen=onOpen;this.notes=[{idx:0,text:"comment"}];if(saveButtonId!==null){document.getElementById(saveButtonId).addEventListener("click",this.saveCSV)}if(openButtonId!==null){document.getElementById(openButtonId).addEventListener("click",this.openCSV)}}processArraysForCSV(data=["1|2|3","3|2|1"],delimiter="|",header="a,b,c",saveNotes=false){let csvDat=header+"\n";let noteIdx=0;data.forEach((line,i)=>{if(data[i]==="string"&&delimiter!==","){csvDat+=line.split(delimiter).join(",")}else{csvData+=line.join(",")}if(saveNotes===true){if(this.notes[noteIdx].idx===i){line+=this.notes[noteIdx].text;noteIdx++}}if(line.indexOf("\n")<0){csvDat+="\n"}});return csvDat}static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){var hiddenElement=document.createElement("a");hiddenElement.href="data:text/csv;charset=utf-8,"+encodeURI(csvDat);hiddenElement.target="_blank";if(name!==""){hiddenElement.download=name}else{hiddenElement.download=Date().toISOString()}hiddenElement.click()}static openCSV(delimiter=",",onOpen=(csvDat,header,path)=>{return csvDat,header,path}){var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;var tempcsvArr=tempcsvData.split("\n");let header=[];var csvDat=[];tempcsvArr.pop();tempcsvArr.forEach((row,i)=>{if(i==0){header=row.split(delimiter)}else{var temp=row.split(delimiter);csvDat.push(temp)}});onOpen(csvDat,header,input.value);input.value=""};reader.readAsText(file)};input.click()}static openCSVRaw(onOpen=(csvDat,path)=>{return csvDat,path}){var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;onOpen(tempcsvData,input.value);input.value=""};reader.readAsText(file)};input.click()}onOpen(csvDat=[],header=[]){console.log("CSV Opened!",header,csvDat)}};var parseCSVData=(data,filename,head,hasend=true,parser=(lines,filename2,head2)=>{let result={filename:filename2};let header=head2;if(typeof head2==="string")header=head2.split(",");result.header=header;for(let i=0;i{let lines=data.split("\n");if(!head)head=lines[0];lines.shift();if(hasend===false)lines.pop();let result=parser(lines,filename,head);return result};function toISOLocal(d){d=new Date(d);var z=n=>("0"+n).slice(-2);var zz=n=>("00"+n).slice(-3);var off=d.getTimezoneOffset();var sign=off<0?"+":"-";off=Math.abs(off);return d.getFullYear()+"-"+z(d.getMonth()+1)+"-"+z(d.getDate())+"T"+z(d.getHours())+":"+z(d.getMinutes())+":"+z(d.getSeconds())+"."+zz(d.getMilliseconds())+"(UTC"+sign+z(off/60|0)+":00)"}var processDataForCSV=(options={})=>{let header="";if(typeof options.data[0]==="object"&&!Array.isArray(options.data[0])){if(options.data[0].x)header="x,";else if(options.data[0].timestamp)header="timestamp,localtime,"}let headeridx=0;let lines={};options.data.forEach((obj,i)=>{if(Array.isArray(obj)){for(let j=0;j{if(exists2)appendFile(options.filename,joined,options.dir);else appendFile(options.filename,header+joined,options.dir)})}return result};var BrowserFS=__toESM(require_browserfs());var fsInited=false;var fs2=BrowserFS.BFSRequire("fs");var BFSBuffer=BrowserFS.BFSRequire("buffer").Buffer;var initFS=async(dirs=["data"],oninit=(exists2=[])=>{},onerror=e=>{},filesystem="IndexedDB")=>{if(fsInited)return true;else{fsInited=true;return new Promise(resolve=>{let oldmfs=fs2.getRootFS();BrowserFS.FileSystem[filesystem].Create({},(e,mountableFileSystem)=>{if(e)throw e;if(!mountableFileSystem){onerror(e);throw new Error(`Error creating BrowserFS`)}BrowserFS.initialize(mountableFileSystem);let promises=[];dirs.forEach(async dir2=>{promises.push(dirExists(fs2,dir2))});Promise.all(promises).then(values=>{oninit(values);fsInited=true;resolve(true)})})})}};var exists=async(path="")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.exists("/"+path,function(exists2){resolve(exists2)})})};var readFile=async(path="data")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.readFile("/"+path,function(e,output){resolve(output)})})};async function readFileChunk(path="data",begin=0,end=5120,onread=data=>{}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);if(path!=""){return new Promise(async resolve=>{fs2.open("/"+path,"r",(e,fd)=>{if(e)throw e;fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er)throw er;if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})}else{console.error("Path name is not defined");return void 0}}var getFilenames=async(directory="data",onload=directory2=>{})=>{if(!fsInited)await initFS([directory]);else await dirExists(fs2,directory);return new Promise(resolve=>{fs2.readdir("/"+directory,(e,dir2)=>{if(e)throw e;if(dir2){onload(dir2);resolve(dir2)}else resolve(void 0)})})};var writeFile=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.writeFile("/"+path,data,err=>{if(err)throw err;onwrite(data);resolve(true)})})};var appendFile2=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.appendFile("/"+path,data,err=>{if(err)throw err;onwrite(data);resolve(true)})})};var deleteFile=async(path="data",ondelete=()=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{if(path!=""){fs2.unlink("/"+path,e=>{if(e)console.error(e);ondelete();resolve(true)})}else{console.error("Path name is not defined");resolve(false)}})};var readFileAsText=async(path="data",end="end",begin=0,onread=(data,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(async resolve=>{let size=await getFileSize(path,dir);if(end==="end"){end=size}else if(typeof end==="number"){if(end>size)end=size}fs2.open("/"+path,"r",(e,fd)=>{if(e)throw e;fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er)throw er;if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})};var listFiles=async(dir2="data",onload=directory=>{})=>{if(!fsInited)await initFS([dir2]);else await dirExists(fs2,dir2);return new Promise(resolve=>{fs2.readdir("/"+dir2,(e,directory)=>{if(e)throw e;if(directory){onload(directory)}resolve(directory)})})};var getFileSize=async(path="data",onread=size=>{console.log(size)})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.stat("/"+path,(e,stats)=>{if(e)throw e;let filesize=stats.size;onread(filesize);resolve(filesize)})})};var getCSVHeader=async(path="data",onopen=(header,filename)=>{console.log(header,filename)})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{fs2.open("/"+path,"r",(e,fd)=>{if(e)throw e;fs2.read(fd,65535,0,"utf-8",(er,output,bytesRead)=>{if(er)throw er;if(bytesRead!==0){let data=output.toString();let lines=data.split("\n");let header=lines[0];fs2.close(fd,()=>{onopen(header,path);resolve(header)})}else resolve(void 0)})})})};var writeToCSVFromDB=async(path="data",fileSizeLimitMb=10)=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return new Promise(resolve=>{if(path!=""){fs2.stat("/"+path,(e,stats)=>{if(e)throw e;let filesize=stats.size;console.log(filesize);fs2.open(path,"r",(e2,fd)=>{if(e2)throw e2;let i=0;let maxFileSize=fileSizeLimitMb*1024*1024;let end=maxFileSize;if(filesize{if(e3)throw e3;if(bytesRead!==0)CSV.saveCSV(output.toString(),path);fs2.close(fd);resolve(true)})}else{const writeChunkToFile=async()=>{if(ifilesize){end=filesize-i}let chunk=0;fs2.read(fd,end,i,"utf-8",(e3,output,bytesRead)=>{if(e3)throw e3;if(bytesRead!==0){CSV.saveCSV(output.toString(),path+"_"+chunk);i+=maxFileSize;chunk++;writeChunkToFile();fs2.close(fd);resolve(true)}})}}}})})}else{console.error("File name is not defined.");resolve(false)}})};async function readCSVChunkFromDB(path="data",start=0,end="end"){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);let head=await getCSVHeader(path);if(head)head=head.split(",");else return void 0;let resultLengths=[];let resultNames=[];let results={};head.forEach(v=>{if(v){resultNames.push(v);resultLengths.push(1)}else resultLengths[resultLengths.length-1]++});let size=await getFileSize(path);if(end==="end")end=size;else if(end>size){start=size-(end-start);end=size}let data=await readFileChunk(path,start,end);let headeridx=0;let lastIdx=0;data.forEach((r,i)=>{let row=r.split(",");while(lastIdx{return new Promise((resolve,reject)=>{if(directories[directory]==="exists"||directories[directory]==="created"){resolve()}else{fs3.exists(`/${directory}`,exists2=>{if(exists2){directories[directory]="exists";console.log(`/${directory} exists!`);resolve()}else if(directories[directory]==="creating"){console.log(directory+" is still being created.");resolve()}else{console.log(`creating /${directory}`,fs3);directories[directory]="creating";fs3.mkdir(`/${directory}`,1,err=>{if(err){throw err}directories[directory]="created";setTimeout(resolve,500)})}})}})};var BFSRoutes={initFS,dirExists,exists,readFile,readFileChunk,getFilenames,writeFile,appendFile:appendFile2,deleteFile,readFileAsText,getFileSize,getCSVHeader,listFiles};var CSV_REFERENCE={};function lerp(v0,v1,t){return(1-t)*v0+t*v1}function interpolerp(v0,v1,fit,floor=true){if(fit<=2)return[v0,v1];let a=1/fit;let result=new Array(fit);result[0]=v0;for(let i=1;i<=fit;i++){result[i]=lerp(v0,v1,a*i);if(floor)result[i]=Math.floor(result[i])}return result}var appendCSV=async(newData,filename,header,toFixed=5)=>{if(!filename){let keys=Object.keys(CSV_REFERENCE);if(keys.length>0)filename=keys[keys.length-1];else filename=`csv${new Date().toISOString()}`}let csv=CSV_REFERENCE[filename];if(!csv){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);CSV_REFERENCE[filename]={header:header?header:["timestamp","localized",...keys],lastX:void 0,buffer:"",buffered:0,bufferSize:0,xIncrement:void 0};csv=CSV_REFERENCE[filename];header=csv.header}if(!csv.header||csv.header?.length===0){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);csv.header=header?header:["timestamp","localized",...keys]}else if(header)csv.header=header;let maxLen=1;for(const key in newData){if(csv.header.indexOf(key)>-1&&newData[key]?.length>maxLen){maxLen=newData[key]?.length}}let x;if(csv.xIncrement){if(!csv.lastX){if(typeof newData[csv.header[0]]!=="undefined"){x=newData[csv.header[0]]}else if(csv.header[0].toLowerCase().includes("time")||csv.header[0].toLowerCase().includes("unix"))x=Date.now()}else{if(newData[csv.header[2]]){if(Array.isArray(newData[csv.header[2]]))x=csv.lastX+csv.xIncrement*newData[csv.header[2]].length;else x=csv.lastX+csv.xIncrement}else if(newData[csv.header[0]]){if(Array.isArray(newData[csv.header[0]]))x=csv.lastX+csv.xIncrement*newData[csv.header[0]].length;else x=csv.lastX+csv.xIncrement}else x=csv.lastX+csv.xIncrement}}else x=newData[csv.header[0]];if(typeof csv.lastX==="undefined")csv.lastX=Array.isArray(x)?x[0]:x;if(typeof x==="undefined"){if(csv.header[0].includes("time")){let now=Date.now();if(maxLen===1)x=Date.now();else{x=interpolerp(csv.lastX,now,maxLen);x.shift()}}else{let newX=csv.lastX+1;if(maxLen>1){x=new Array(maxLen).fill("");x[maxLen-1]=newX}else x=newX}}else if(maxLen>1&&x?.length!==maxLen){if(!Array.isArray(x)||x.length===1){x=interpolerp(csv.lastX,x,maxLen);x.shift()}else{x=interpolerp(x[0],x[x.length-1],maxLen);x.shift()}}let toAppend=[];if(Array.isArray(x)){let curIdcs={};for(let i=0;icurIdcs[csv.header[j]]){curIdcs[csv.header[j]]++;toAppend[i][j]=d[curIdcs[csv.header[j]]]}else{toAppend[i][j]=""}}}}else{if(i===x.length-1){toAppend[i][j]=d}else{toAppend[i][j]=""}}if(typeof toAppend[i][j]==="number"&&Math.floor(toAppend[i][j])!==toAppend[i][j])toAppend[i][j]=toAppend[i][j].toFixed(toFixed)}}}else{toAppend.push([]);for(let j=0;j{csvProcessed+=arr.join(",")+"\n";if(csv.bufferSize)csv.buffered++});csv.lastX=toAppend[toAppend.length-1][0];if(csv.bufferSize){csv.buffer+=csvProcessed;if(csv.buffered>csv.bufferSize){let r=new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csv.buffer,written=>{res(written)})}else{appendFile2(filename,csv.buffer,written=>{res(written)})}})});await r;csv.buffer="";csv.buffered=0;return r}else return Promise.resolve(true)}else{return new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csvProcessed,written=>{res(written)})}else{appendFile2(filename,csvProcessed,written=>{res(written)})}})})}};var updateCSVHeader=(header,filename)=>{if(CSV_REFERENCE[filename]){CSV_REFERENCE[filename].header=header}};var createCSV=(filename,header,bufferSize=0,xIncrement)=>{if(header?.indexOf("timestamp")>1){header.splice(header.indexOf("timestamp"),1);header.unshift("timestamp")}if((header?.[0].toLowerCase().includes("time")||header?.[0].toLowerCase().includes("unix"))&&header[1]!=="localized"){header.splice(1,0,"localized")}CSV_REFERENCE[filename]={header,lastX:header[1]==="localized"?Date.now():0,bufferSize,buffer:"",buffered:0,xIncrement};return new Promise((res,rej)=>{writeFile(filename,CSV_REFERENCE[filename].header?CSV_REFERENCE[filename].header.join(",")+"\n":"",written=>{res(written)}).catch(rej)})};var visualizeDirectory=(dir2,parentNode=document.body)=>{return new Promise(async(res,rej)=>{if(parentNode.querySelector("#bfs"+dir2))parentNode.querySelector("#bfs"+dir2)?.remove();parentNode.insertAdjacentHTML("beforeend",`
`);let div=parentNode.querySelector("#bfs"+dir2);await listFiles(dir2).then(directory=>{if(directory.length===0)div.innerHTML="No Files!";else directory.forEach(listing=>{div?.insertAdjacentHTML("beforeend",`
+ Data: + ${listing} + + ${listing.indexOf(".")>-1?``:""} +
`);if(document.getElementById(`delete${listing}`)){document.getElementById(`delete${listing}`).onclick=()=>{deleteFile(dir2+"/"+listing,()=>{visualizeDirectory(dir2,parentNode)})}}if(document.getElementById(`download${listing}`)){document.getElementById(`download${listing}`).onclick=()=>{writeToCSVFromDB(dir2+"/"+listing,10)}}});res(directory)}).catch(rej)})};var csvRoutes={appendCSV,updateCSVHeader,createCSV,visualizeDirectory,openCSV:CSV.openCSV,saveCSV:CSV.saveCSV,openCSVRaw:CSV.openCSVRaw,parseCSVData,getCSVHeader,writeToCSVFromDB,readCSVChunkFromDB,toISOLocal};})(); +/*! +* The buffer module from node.js, for the browser. +* +* @author Feross Aboukhadijeh +* @license MIT +*/ diff --git a/extras/dist/loaders/Loaders.d.ts b/extras/dist/loaders/Loaders.d.ts new file mode 100644 index 00000000..74eb85d5 --- /dev/null +++ b/extras/dist/loaders/Loaders.d.ts @@ -0,0 +1,67 @@ +import { GraphNode, Graph, GraphNodeProperties } from "../Graph"; +/** + * setting nodeA.__node.backward:true propagates operator results to parent + */ +export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** + * + * Specify a timer loop, will stop when node is popped or nodeA.__node.isLooping is set false + * nodeA.__node.loop = 100 will loop the operator every 100 milliseconds + * + * Or + * nodeA.__node.delay will delay the operator by specified millisecond number and resolve the result as a promise + * nodeA.__node.frame will use requestAnimationFrame to call the function and resolve the result as a promise + * + * Use in combination with: + * nodeA.__node.repeat will repeat the operator the specified number of times + * nodeA.__node.recursive will do the same as repeat but will pass in the previous operator call's results + * + * + */ +export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Animations + * + * nodeA.__node.animate = true | () => void, to run the operator or a specified animation function on loop + * + */ +export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Branching operations + * + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * + * nodeA.__listeners['nodeB.x'] = { + * callback:(result)=>void, + * branch:{if:Function|any, then:Function|any|GraphNode} + * } + * + */ +export declare const branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Trigger listeners oncreate with specific arguments + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } + * + */ +export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Trigger listeners oncreate with specific arguments + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } + * + */ +export declare const bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } + * + */ +export declare const transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +export declare const substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; +export declare const loaders: { + backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; +}; diff --git a/dist/src/loaders/index.d.ts b/extras/dist/loaders/index.d.ts similarity index 84% rename from dist/src/loaders/index.d.ts rename to extras/dist/loaders/index.d.ts index 229b9ec7..6e6983f2 100644 --- a/dist/src/loaders/index.d.ts +++ b/extras/dist/loaders/index.d.ts @@ -1,4 +1,4 @@ -import { GraphNode, Graph, GraphNodeProperties } from "../core/Graph"; +import { GraphNode, Graph, GraphNodeProperties } from "../Graph"; /** * setting nodeA.__node.backward:true propagates operator results to parent */ @@ -31,15 +31,11 @@ export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: G export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; /** Branching operations * - * //runs a function or node if the if-conditions are satisfied, which can be a function that returns a true or false - * nodeA.__branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} * * nodeA.__listeners['nodeB.x'] = { * callback:(result)=>void, - * branch:{ - * if:Function|any, //if a function using the result evaluates to true or if the value equals the if value - * then:Function|any|GraphNode //call a function, return a different result, or call a node - * } + * branch:{if:Function|any, then:Function|any|GraphNode} * } * */ @@ -50,7 +46,7 @@ export declare const branching: (node: GraphNode, parent: GraphNode | Graph, gra * */ export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; -/** Bind listeners to a specific object instead of the node that owns it +/** Trigger listeners oncreate with specific arguments * * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } * diff --git a/extras/dist/services/EventHandler.d.ts b/extras/dist/services/EventHandler.d.ts new file mode 100644 index 00000000..b6f54f38 --- /dev/null +++ b/extras/dist/services/EventHandler.d.ts @@ -0,0 +1,17 @@ +export declare class EventHandler { + pushToState: {}; + data: {}; + triggers: {}; + constructor(data?: { + [key: string]: any; + }); + setState: (updateObj: { + [key: string]: any; + }) => {}; + setValue: (key: any, value: any) => void; + subscribeTrigger: (key: string, onchange: (res: any) => void) => number; + unsubscribeTrigger: (key: string, sub?: number) => boolean; + subscribeTriggerOnce: (key: string, onchange: (res: any) => void) => void; + getTrigger: (key: any, sub: any) => any; + onRemoved: any; +} diff --git a/src/extras/dist/src/services/Service.d.ts b/extras/dist/services/Service.d.ts similarity index 74% rename from src/extras/dist/src/services/Service.d.ts rename to extras/dist/services/Service.d.ts index a5558998..f9db7452 100644 --- a/src/extras/dist/src/services/Service.d.ts +++ b/extras/dist/services/Service.d.ts @@ -1,27 +1,21 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export type ServiceMessage = { +import { Graph, GraphNode, GraphOptions } from "../Graph"; +export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export declare type ServiceMessage = { route?: string; args?: any; method?: string; node?: string | GraphNode; [key: string]: any; }; -export type ServiceOptions = GraphOptions & { +export declare type ServiceOptions = GraphOptions & { services?: { [key: string]: Service | Function | { [key: string]: any; }; }; - restrict?: { - [key: string]: boolean; - }; }; export declare class Service extends Graph { name: string; - restrict?: { - [key: string]: boolean; - }; constructor(options?: ServiceOptions); addServices: (services: { [key: string]: Function | Graph | Service | { @@ -33,7 +27,7 @@ export declare class Service extends Graph { handleGraphNodeCall(route: string | GraphNode, args: any): any; transmit: (...args: any[]) => any | void; receive: (...args: any[]) => any | void; - pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; + pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => any; terminate: (...args: any) => void; isTypedArray: typeof isTypedArray; @@ -41,8 +35,6 @@ export declare class Service extends Graph { spliceTypedArray: typeof spliceTypedArray; ping: () => string; echo: (...args: any) => any; - log: (...args: any) => boolean; - error: (...args: any) => boolean; } export declare function isTypedArray(x: any): boolean; export declare const recursivelyAssign: (target: any, obj: any) => any; diff --git a/src/extras/dist/src/services/ecs/ECS.service.d.ts b/extras/dist/services/ecs/ECS.service.d.ts similarity index 92% rename from src/extras/dist/src/services/ecs/ECS.service.d.ts rename to extras/dist/services/ecs/ECS.service.d.ts index cb3252b8..aefca013 100644 --- a/src/extras/dist/src/services/ecs/ECS.service.d.ts +++ b/extras/dist/services/ecs/ECS.service.d.ts @@ -1,11 +1,11 @@ -import { GraphNode, GraphNodeProperties } from '../../core/Graph'; +import { GraphNode, GraphNodeProperties } from '../../Graph'; import { Service, ServiceOptions } from '../Service'; -export type EntityProps = { +export declare type EntityProps = { components: { [key: string]: any; }; } & (GraphNodeProperties | GraphNode); -export type SystemProps = (GraphNodeProperties & { +export declare type SystemProps = (GraphNodeProperties & { __operator: (entities: { [key: string]: Entity; }) => any; @@ -16,13 +16,13 @@ export type SystemProps = (GraphNodeProperties & { }; setupEntity: (entity: Entity) => Entity; }) | GraphNode; -export type Entity = { +export declare type Entity = { components: { [key: string]: any; }; [key: string]: any; } & GraphNode; -export type System = { +export declare type System = { __operator: (entities: { [key: string]: Entity; }) => any; @@ -40,7 +40,7 @@ export type System = { }; entityKeys: string[]; } & GraphNode; -export type ECSOptions = { +export declare type ECSOptions = { entities: { [key: string]: EntityProps; }; diff --git a/src/extras/dist/services/router/Router.d.ts b/extras/dist/services/router/Router.d.ts similarity index 73% rename from src/extras/dist/services/router/Router.d.ts rename to extras/dist/services/router/Router.d.ts index 3d6e0348..67171855 100644 --- a/src/extras/dist/services/router/Router.d.ts +++ b/extras/dist/services/router/Router.d.ts @@ -1,6 +1,6 @@ -import { Graph, GraphNode } from "../../core/Graph"; +import { Graph, GraphNode } from "../../Graph"; import { Service, ServiceOptions } from "../Service"; -export type User = { +export declare type User = { _id: string; send: (...args: any[]) => any; request: (...args: any[]) => Promise | Promise[] | undefined; @@ -8,19 +8,11 @@ export type User = { run: (...args: any[]) => Promise | Promise[] | undefined; subscribe: (...args: any[]) => Promise | Promise[] | undefined; unsubscribe: (...args: any[]) => Promise | Promise[] | undefined; - sendAll?: (...args: any[]) => any; - requestAll?: (...args: any[]) => Promise | undefined; - postAll?: (...args: any[]) => void; - runAll?: (...args: any[]) => Promise | undefined; - subscribeAll?: (...args: any[]) => Promise | undefined; - unsubscribeAll?: (...args: any[]) => Promise | undefined; terminate: (...args: any[]) => boolean; - onmessage?: (...args: any[]) => void; - onerror?: (...args: any[]) => void; - onclose?: ((user: User) => void) | ((...args: any[]) => void); + onclose?: (user: User) => void; [key: string]: any; }; -export type ConnectionProps = { +export declare type ConnectionProps = { connection: GraphNode | Graph | { [key: string]: any; } | string; @@ -28,7 +20,7 @@ export type ConnectionProps = { source?: string; onclose?: (connection: ConnectionInfo, ...args: any[]) => void; }; -export type ConnectionInfo = { +export declare type ConnectionInfo = { connection: GraphNode | Graph | { [key: string]: any; }; @@ -41,12 +33,12 @@ export type ConnectionInfo = { request?: (message: any, method?: any, ...a: any[]) => Promise | Promise[]; post?: (route: any, args?: any, method?: string, ...a: any[]) => void; run?: (route: any, args?: any, method?: string, ...a: any[]) => Promise | Promise[]; - subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | undefined; + subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | Promise[] | undefined; unsubscribe?: (route: any, sub: number, ...arrayBuffer: any[]) => Promise | Promise[]; terminate: (...a: any[]) => boolean; onclose?: (connection: ConnectionInfo, ...args: any[]) => void; }; -export type RouterOptions = { +export declare type RouterOptions = { graph?: { [key: string]: Service | Graph | any | { service: Service | Graph | any; @@ -64,7 +56,6 @@ export type RouterOptions = { }; }; }; - timeout?: number; order?: string[]; [key: string]: any; } & ServiceOptions; @@ -91,7 +82,6 @@ export declare class Router extends Service { users: { [key: string]: User; }; - userTimeout: number; order: string[]; constructor(options?: RouterOptions); addUser: (info: { @@ -113,11 +103,11 @@ export declare class Router extends Service { _id: string; [key: string]: any; }, terminate?: boolean): boolean; - getConnection: (sourceId: string, hasMethod?: string, connectionId?: string) => User | ConnectionInfo | undefined; - getConnections: (sourceId: string, hasMethod?: string, props?: {}) => {}; - runConnection: (userId: string, method: 'run' | 'post' | 'subscribe' | 'unsubscribe' | 'terminate' | 'send' | 'request' | 'runAll' | 'postAll' | 'subscribeAll' | 'unsubscribeAll' | 'sendAll' | 'requestAll', args: any[], connectionId?: string) => Promise; - subscribeThroughConnection: (route: string, remoteRelay: string | ConnectionInfo, remoteEndpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; - addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string, autoRemove?: boolean) => ConnectionInfo; + getConnection: (sourceId: string, hasMethod?: string) => ConnectionInfo | undefined; + getConnections: (sourceId: string, hasMethod?: string, props?: {}) => { + [key: string]: ConnectionInfo; + }; + addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string) => ConnectionInfo; removeConnection: (connection: string | ConnectionInfo | { [key: string]: any; _id: string; @@ -128,12 +118,9 @@ export declare class Router extends Service { [key: string]: any; }, source?: string, ...args: any[]) => Promise; terminate: (connection: string | ConnectionInfo) => boolean; + subscribeThroughConnection: (route: string, relay: string | ConnectionInfo, endpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; routeConnections: (route: string, transmitter: string | ConnectionInfo, receiver: string | ConnectionInfo, ...args: any[]) => Promise; setUserData: (user: string | User, data: string | { [key: string]: any; }) => boolean; } -export declare function connectionHasId(connection: { - _id?: string; - [key: string]: any; -}, timeout?: number): Promise; diff --git a/extras/dist/services/unsafe/Unsafe.service.d.ts b/extras/dist/services/unsafe/Unsafe.service.d.ts new file mode 100644 index 00000000..fecbf4b8 --- /dev/null +++ b/extras/dist/services/unsafe/Unsafe.service.d.ts @@ -0,0 +1,25 @@ +export declare const unsafeRoutes: { + setRoute: (fn: string | (() => any), fnName?: string) => boolean; + setNode: (fn: string | (() => any), fnName?: string) => boolean; + setMethod: (route: string, fn: string | (() => any), fnName?: string) => boolean; + assignRoute: (route: string, source: { + [key: string]: any; + }) => void; + transferClass: (classObj: any, className?: string) => false | { + route: string; + args: any[]; + }; + receiveClass: (stringified: string, className?: string) => boolean; + setGlobal: (key: string, value: any) => boolean; + assignGlobalObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setValue: (key: string, value: any) => boolean; + assignObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setGlobalFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToGlobalObject: (globalObjectName: string, fn: any, fnName: any) => boolean; + setFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToObject: (objectName: string, fn: any, fnName: any) => boolean; +}; diff --git a/src/extras/dist/services/utils.d.ts b/extras/dist/services/utils.d.ts similarity index 50% rename from src/extras/dist/services/utils.d.ts rename to extras/dist/services/utils.d.ts index 9efee154..38516f95 100644 --- a/src/extras/dist/services/utils.d.ts +++ b/extras/dist/services/utils.d.ts @@ -1,12 +1,6 @@ -export declare let recursivelyStringifyFunctions: (obj: { - [key: string]: any; -}) => {}; -export declare function getFnParamNames(fn: any): any; -export declare let getFunctionHead: (methodString: any) => any; export declare function parseFunctionFromText(method?: string): any; export declare function reconstructObject(json?: string | { [x: string]: any; }): any; export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyWithFunctionsAndCircularRefs: (obj: any, space?: any) => string; export declare const stringifyFast: (obj: any, space?: any) => string; diff --git a/extras/dist/services/worker/ProxyListener.d.ts b/extras/dist/services/worker/ProxyListener.d.ts new file mode 100644 index 00000000..dc6e2c02 --- /dev/null +++ b/extras/dist/services/worker/ProxyListener.d.ts @@ -0,0 +1,66 @@ +declare function wheelEventHandler(event: any, sendFn: any): void; +declare function preventDefaultHandler(event: any): void; +declare function touchEventHandler(event: any, sendFn: any): void; +declare function filteredKeydownEventHandler(event: any, sendFn: any): void; +export declare const eventHandlers: { + contextmenu: typeof preventDefaultHandler; + mousedown: (event: any, sendFn: any) => void; + mousemove: (event: any, sendFn: any) => void; + mouseup: (event: any, sendFn: any) => void; + pointerdown: (event: any, sendFn: any) => void; + pointermove: (event: any, sendFn: any) => void; + pointerup: (event: any, sendFn: any) => void; + touchstart: typeof touchEventHandler; + touchmove: typeof touchEventHandler; + touchend: typeof touchEventHandler; + wheel: typeof wheelEventHandler; + keydown: typeof filteredKeydownEventHandler; +}; +export declare function initProxyElement(element: any, worker: any, id: any): any; +export declare class EventDispatcher { + __listeners: any; + addEventListener(type: any, listener: any): void; + hasEventListener(type: any, listener: any): boolean; + removeEventListener(type: any, listener: any): void; + dispatchEvent(event: any, target: any): void; +} +export declare class ElementProxyReceiver extends EventDispatcher { + __listeners: any; + proxied: any; + style: any; + width: any; + left: any; + right: any; + top: any; + height: any; + constructor(); + get clientWidth(): any; + get clientHeight(): any; + setPointerCapture: () => void; + releasePointerCapture: () => void; + getBoundingClientRect: () => { + left: any; + top: any; + width: any; + height: any; + right: any; + bottom: any; + }; + handleEvent: (data: any) => void; + focus(): void; +} +export declare class ProxyManager { + targets: any; + constructor(); + makeProxy: (id: any, addTo?: any) => void; + getProxy: (id: any) => any; + handleEvent: (data: any, id: any) => boolean; +} +declare function makeProxy(id: any, elm?: any): any; +declare function handleProxyEvent(data: any, id: any): any; +export declare const proxyElementWorkerRoutes: { + initProxyElement: typeof initProxyElement; + makeProxy: typeof makeProxy; + handleProxyEvent: typeof handleProxyEvent; +}; +export {}; diff --git a/extras/dist/services/worker/Subprocess.d.ts b/extras/dist/services/worker/Subprocess.d.ts new file mode 100644 index 00000000..9963fd85 --- /dev/null +++ b/extras/dist/services/worker/Subprocess.d.ts @@ -0,0 +1,127 @@ +import { WorkerInfo, WorkerService } from './Worker.service'; +export declare type Subprocess = (context: SubprocessContext, data: { + [key: string]: any; +} | any) => { + [key: string]: any; +} | undefined; +export declare type SubprocessContextProps = { + ondata: Subprocess; + oncreate?: (context: SubprocessContext) => void; + structs?: { + [key: string]: any; + }; + [key: string]: any; +}; +export declare type SubprocessContext = { + ondata: Subprocess; + oncreate?: (context: SubprocessContext) => void; + run?: (data: { + [key: string]: any; + } | any) => any; + [key: string]: any; +}; +export declare type SubprocessWorkerProps = { + subprocess: string | { + name: string; + structs: {}; + oncreate: string | ((ctx: SubprocessContext) => void); + ondata: string | ((context: any, data: { + [key: string]: any; + } | any) => { + [key: string]: any; + } | undefined); + props?: { + [key: string]: any; + }; + }; + subscribeRoute: string; + source?: WorkerInfo; + route: string; + init?: string; + initArgs?: any[]; + otherArgs?: any[]; + callback?: string | ((data: any) => any); + pipeTo?: { + worker?: WorkerInfo; + portId?: string; + route: string; + otherArgs?: any[]; + init?: string; + initArgs?: any[]; + }; + worker?: WorkerInfo; + url?: any; + stopped?: boolean; +}; +export declare type SubprocessWorkerInfo = { + sub: number; + blocking?: boolean; + stop: () => void; + start: () => void; + terminate: () => void; + setArgs: (args: any[] | { + [key: string]: any; + }) => void; +} & SubprocessWorkerProps; +export declare const algorithms: { + [key: string]: SubprocessContextProps; +}; +export declare const loadAlgorithms: (settings: { + [key: string]: SubprocessContextProps; +}) => { + [key: string]: SubprocessContextProps; +} & { + [key: string]: SubprocessContextProps; +}; +export declare function createSubprocess(options: SubprocessContextProps, inputs?: { + [key: string]: any; +}): SubprocessContext; +export declare const subprocessRoutes: { + loadAlgorithms: (settings: { + [key: string]: SubprocessContextProps; + }) => { + [key: string]: SubprocessContextProps; + } & { + [key: string]: SubprocessContextProps; + }; + initSubprocesses: (subprocesses: { + [key: string]: SubprocessWorkerProps; + }, service?: WorkerService) => Promise<{ + [key: string]: SubprocessWorkerInfo; + }>; + addSubprocessTemplate: (name: string, structs: {}, oncreate: string | ((ctx: SubprocessContext) => void), ondata: string | ((context: any, data: any) => { + [key: string]: any; + }), props?: { + [key: string]: any; + }) => boolean; + updateSubprocess: (structs: {}, _id?: string) => void; + createSubprocess: (options: SubprocessContextProps | string, inputs?: { + [key: string]: any; + }) => any; + runSubprocess: (data: { + [key: string]: any; + }, _id?: string) => any; + setRoute: (fn: string | (() => any), fnName?: string) => boolean; + setNode: (fn: string | (() => any), fnName?: string) => boolean; + setMethod: (route: string, fn: string | (() => any), fnName?: string) => boolean; + assignRoute: (route: string, source: { + [key: string]: any; + }) => void; + transferClass: (classObj: any, className?: string) => false | { + route: string; + args: any[]; + }; + receiveClass: (stringified: string, className?: string) => boolean; + setGlobal: (key: string, value: any) => boolean; + assignGlobalObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setValue: (key: string, value: any) => boolean; + assignObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setGlobalFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToGlobalObject: (globalObjectName: string, fn: any, fnName: any) => boolean; + setFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToObject: (objectName: string, fn: any, fnName: any) => boolean; +}; diff --git a/dist/src/services/worker/canvas.worker.d.ts b/extras/dist/services/worker/Worker.d.ts similarity index 100% rename from dist/src/services/worker/canvas.worker.d.ts rename to extras/dist/services/worker/Worker.d.ts diff --git a/dist/src/services/worker/Worker.service.d.ts b/extras/dist/services/worker/Worker.service.d.ts similarity index 68% rename from dist/src/services/worker/Worker.service.d.ts rename to extras/dist/services/worker/Worker.service.d.ts index 9539bb89..fe064cf3 100644 --- a/dist/src/services/worker/Worker.service.d.ts +++ b/extras/dist/services/worker/Worker.service.d.ts @@ -1,9 +1,10 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; import Worker from 'web-worker'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export type WorkerRoute = { +import { GraphNode, GraphNodeProperties } from "../../Graph"; +export declare type WorkerRoute = { worker?: WorkerInfo; workerUrl?: string | URL | Blob; + workerId?: string; transferFunctions?: { [key: string]: Function; }; @@ -19,7 +20,7 @@ export type WorkerRoute = { initArgs?: any[]; initTransfer?: any[]; } & GraphNodeProperties & WorkerProps; -export type WorkerProps = { +export declare type WorkerProps = { worker?: WorkerInfo; workerUrl?: string | URL | Blob; url?: URL | string | Blob; @@ -29,13 +30,13 @@ export type WorkerProps = { onerror?: (ev: any) => void; onclose?: (worker: Worker | MessagePort) => void; }; -export type WorkerInfo = { +export declare type WorkerInfo = { worker: Worker | MessagePort; send: (message: any, transfer?: any) => void; - request: (message: any, method?: string, transfer?: any) => Promise; - post: (route: any, args?: any, method?: string, transfer?: any) => void; - run: (route: any, args?: any, method?: string, transfer?: any) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; + request: (message: any, transfer?: any, method?: string) => Promise; + post: (route: any, args?: any, transfer?: any) => void; + run: (route: any, args?: any, transfer?: any, method?: string) => Promise; + subscribe: (route: any, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; unsubscribe: (route: any, sub: number) => Promise; start: (route?: any, portId?: string, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; stop: (route?: string, portId?: string) => Promise; @@ -49,7 +50,7 @@ export type WorkerInfo = { }; }; terminate: () => boolean; - postMessage: (message: any, transfer?: any[]) => void; + postMessage: (message: any, transfer: any[]) => void; graph: WorkerService; _id: string; } & WorkerProps & WorkerRoute; @@ -61,7 +62,7 @@ export declare class WorkerService extends Service { threadRot: number; connections: any; constructor(options?: ServiceOptions); - loadWorkerRoute: (node: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; + loadWorkerRoute: (rt: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; workerloader: any; addDefaultMessageListener: () => void; postMessage: (message: any, target: string, transfer?: Transferable[]) => void; @@ -72,24 +73,18 @@ export declare class WorkerService extends Service { onmessage?: (ev: any) => void; onerror?: (ev: any) => void; }) => WorkerInfo; - open: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - close: () => void; toObjectURL: (scriptTemplate: string) => string; getTransferable(message: any): any; transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: StructuredSerializeOptions) => any; - terminate: (worker: Worker | MessagePort | string | WorkerInfo) => boolean; + terminate: (worker: Worker | MessagePort | string) => boolean; establishMessageChannel: (worker: Worker | string | MessagePort | WorkerInfo, worker2?: Worker | string | MessagePort | WorkerInfo) => string | false; request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; - runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number, getTransferable?: boolean) => any; - subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => number; - subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; + runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number) => any; + subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, blocking?: boolean, key?: string, subInput?: boolean) => any; + subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), blocking?: boolean, key?: string, subInput?: boolean) => Promise; triggerSubscription: (route: string, workerId: string, result: any) => Promise; - pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, args?: any[], key?: any, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; + pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, blocking?: boolean) => Promise; unpipeWorkers: (sourceRoute: string, sourceWorker: WorkerInfo | string, sub?: number) => Promise; + transferFunction(worker: WorkerInfo, fn: Function, fnName?: string): Promise; + transferClass(worker: WorkerInfo, cls: Function, className?: string): Promise; } diff --git a/extras/dist/services/worker/WorkerCanvas.d.ts b/extras/dist/services/worker/WorkerCanvas.d.ts new file mode 100644 index 00000000..45d0d374 --- /dev/null +++ b/extras/dist/services/worker/WorkerCanvas.d.ts @@ -0,0 +1,88 @@ +import { initProxyElement } from './ProxyListener'; +export declare type WorkerCanvasTransferProps = { + canvas: HTMLCanvasElement; + context?: string; + _id?: string; + draw?: string | ((self: any, canvas: any, context: any) => void); + update?: string | ((self: any, canvas: any, context: any, input: any) => void); + init?: string | ((self: any, canvas: any, context: any) => void); + clear?: string | ((self: any, canvas: any, context: any) => void); + transfer?: any[]; + animating?: boolean; + [key: string]: any; +}; +export declare type CanvasProps = { + canvas: any; + context?: string | CanvasRenderingContext2D | WebGL2RenderingContext | WebGLRenderingContext; + _id?: string; + width?: number; + height?: number; + draw?: string | ((self: any, canvas: any, context: any) => void); + update?: string | ((self: any, canvas: any, context: any, input: any) => void); + init?: string | ((self: any, canvas: any, context: any) => void); + clear?: string | ((self: any, canvas: any, context: any) => void); + animating?: boolean; + [key: string]: any; +}; +export declare type CanvasControls = { + _id: string; + draw: (props?: any) => void; + update: (props: { + [key: string]: any; + }) => void; + clear: () => void; + init: () => void; + stop: () => void; + start: () => void; + set: (newDrawProps: CanvasProps) => void; +}; +export declare type WorkerCanvasControls = { + worker: Worker | MessagePort; + terminate: () => void; +} & CanvasControls; +export declare type WorkerCanvas = { + graph: any; + canvas: any; + context?: CanvasRenderingContext2D | WebGL2RenderingContext | WebGLRenderingContext; + _id: string; + draw?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); + update?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context'], input: any) => void); + init?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); + clear?: ((self: WorkerCanvas, canvas: WorkerCanvas['canvas'], context: WorkerCanvas['context']) => void); + animating: boolean; + [key: string]: any; +}; +export declare function Renderer(options: CanvasProps & { + worker?: Worker | string | Blob | MessagePort; + route?: string; +}): string | CanvasControls; +export declare function transferCanvas(worker: Worker | MessagePort, options: WorkerCanvasTransferProps, route?: string): WorkerCanvasControls; +export declare function setDraw(settings: CanvasProps, _id?: string): string; +export declare function setupCanvas(options: CanvasProps): string | CanvasControls; +export declare function drawFrame(props?: { + [key: string]: any; +}, _id?: string): string; +export declare function clearCanvas(_id?: string): string; +export declare function initCanvas(_id?: string): string; +export declare function updateCanvas(input?: any, _id?: string): string; +export declare function setProps(props?: { + [key: string]: any; +}, _id?: string): string; +export declare function startAnim(_id?: string, draw?: string | ((this: any, canvas: any, context: any) => void)): string; +export declare function stopAnim(_id?: string): string; +export declare const workerCanvasRoutes: { + Renderer: typeof Renderer; + transferCanvas: typeof transferCanvas; + setupCanvas: typeof setupCanvas; + setDraw: typeof setDraw; + drawFrame: typeof drawFrame; + clearCanvas: typeof clearCanvas; + initCanvas: typeof initCanvas; + updateCanvas: typeof updateCanvas; + setProps: typeof setProps; + startAnim: typeof startAnim; + stopAnim: typeof stopAnim; + initProxyElement: typeof initProxyElement; + makeProxy: (id: any, elm?: any) => any; + handleProxyEvent: (data: any, id: any) => any; +}; diff --git a/src/extras/dist/storage/BFSUtils.d.ts b/extras/dist/storage/BFSUtils.d.ts similarity index 85% rename from src/extras/dist/storage/BFSUtils.d.ts rename to extras/dist/storage/BFSUtils.d.ts index be89548b..3bc84449 100644 --- a/src/extras/dist/storage/BFSUtils.d.ts +++ b/extras/dist/storage/BFSUtils.d.ts @@ -1,8 +1,7 @@ export function readFileChunk(path?: string, begin?: number, end?: number, onread?: (data: any) => void): Promise; -export function processCSVChunksFromDB(path?: string, onData?: (csvdata: any, start: any, end: any, size: any) => void, maxChunkSize?: number, start?: number, end?: string, options?: {}): Promise; -export function readCSVChunkFromDB(path?: string, start?: number, end?: string, options?: {}): Promise<{}>; +export function readCSVChunkFromDB(path?: string, start?: number, end?: string): Promise<{}>; export let fsInited: boolean; -export const fs: import("browserfs/dist/node/core/FS.js").FSModule; +export const fs: import("browserfs/dist/node/core/FS").FSModule; export function initFS(dirs?: string[], oninit?: (exists?: any[]) => void, onerror?: (e: any) => void, filesystem?: string): Promise; export function exists(path?: string): Promise; export function readFile(path?: string): Promise; diff --git a/src/extras/dist/storage/BFS_CSV.d.ts b/extras/dist/storage/BFS_CSV.d.ts similarity index 62% rename from src/extras/dist/storage/BFS_CSV.d.ts rename to extras/dist/storage/BFS_CSV.d.ts index d18aaee3..63d93e48 100644 --- a/src/extras/dist/storage/BFS_CSV.d.ts +++ b/extras/dist/storage/BFS_CSV.d.ts @@ -1,27 +1,17 @@ -import { processCSVChunksFromDB, readCSVChunkFromDB } from './BFSUtils'; +import { readCSVChunkFromDB } from './BFSUtils'; import { CSV, toISOLocal } from './csv'; export declare const appendCSV: (newData: { [key: string]: number | number[]; -}, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; -}) => Promise; +}, filename: string, header?: string[], toFixed?: number) => Promise; export declare const updateCSVHeader: (header: any[], filename: string) => void; -export declare const createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; +export declare const createCSV: (filename: string, header: string[], bufferSize?: number, xIncrement?: number) => Promise; export declare const visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; export declare const csvRoutes: { appendCSV: (newData: { [key: string]: number | number[]; - }, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; - }) => Promise; + }, filename: string, header?: string[], toFixed?: number) => Promise; updateCSVHeader: (header: any[], filename: string) => void; - createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; + createCSV: (filename: string, header: string[], bufferSize?: number, xIncrement?: number) => Promise; visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; openCSV: typeof CSV.openCSV; saveCSV: typeof CSV.saveCSV; @@ -34,6 +24,5 @@ export declare const csvRoutes: { getCSVHeader: (path?: string, onopen?: (header: any, filename: any) => void) => Promise; writeToCSVFromDB: (path?: string, fileSizeLimitMb?: number) => Promise; readCSVChunkFromDB: typeof readCSVChunkFromDB; - processCSVChunksFromDB: typeof processCSVChunksFromDB; toISOLocal: typeof toISOLocal; }; diff --git a/src/extras/dist/src/storage/csv.d.ts b/extras/dist/storage/csv.d.ts similarity index 88% rename from src/extras/dist/src/storage/csv.d.ts rename to extras/dist/storage/csv.d.ts index 030f67f5..08e7d7ae 100644 --- a/src/extras/dist/src/storage/csv.d.ts +++ b/extras/dist/storage/csv.d.ts @@ -1,11 +1,14 @@ export function toISOLocal(d: any): string; export class CSV { static saveCSV(csvDat?: string, name?: string): void; - static openCSV(delimiter?: string, onOpen?: (csvDat: any, header: any, path: any) => any): Promise; - static openCSVRaw(onOpen?: (csvDat: any, path: any) => any): Promise; + static openCSV(delimiter?: string, onOpen?: (csvDat: any, header: any, path: any) => any): void; + static openCSVRaw(onOpen?: (csvDat: any, path: any) => any): void; constructor(onOpen?: (csvDat?: any[], header?: any[]) => void, saveButtonId?: any, openButtonId?: any); onOpen(csvDat?: any[], header?: any[]): void; - notes: any[]; + notes: { + idx: number; + text: string; + }[]; processArraysForCSV(data?: string[], delimiter?: string, header?: string, saveNotes?: boolean): string; } export function parseCSVData(data: any, filename: any, head: any, hasend?: boolean, parser?: (lines: any, filename: any, head: any) => { diff --git a/src/extras/ecs/ECS.systems.ts b/extras/ecs/ECS.systems.ts similarity index 98% rename from src/extras/ecs/ECS.systems.ts rename to extras/ecs/ECS.systems.ts index db53156e..5e82756c 100644 --- a/src/extras/ecs/ECS.systems.ts +++ b/extras/ecs/ECS.systems.ts @@ -1,4 +1,4 @@ -import { GraphNode } from "../../core/Graph"; +import { GraphNode } from "../../Graph"; import { Entity } from "../../services/ecs/ECS.service"; export const Systems = { @@ -106,7 +106,7 @@ export const Systems = { } return false }, - sphereCollisionCheck:( //simplest collisions + sphereCollisionCheck:( body1:{ position:{x:number,y:number,z:number}, collisionRadius:number, @@ -125,7 +125,7 @@ export const Systems = { return (dist as number) < (body1.collisionRadius + body2.collisionRadius); }, - boxCollisionCheck:( //also simple but corners are a problem + boxCollisionCheck:( body1:{ position:{x:number,y:number,z:number}, collisionRadius:number, @@ -311,8 +311,8 @@ export const Systems = { } }, dot:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ let dot = 0; for(const key in v1) { @@ -331,8 +331,8 @@ export const Systems = { }; }, vecadd:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1+v2 let result = Object.assign({},v1); for(const key in result) { @@ -341,8 +341,8 @@ export const Systems = { return result; }, vecsub:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1-v2, e.g. a point is v2 - v1 let result = Object.assign({},v1); for(const key in result) { @@ -351,8 +351,8 @@ export const Systems = { return result; }, vecmul:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1*v2 let result = Object.assign({},v1); for(const key in result) { @@ -361,8 +361,8 @@ export const Systems = { return result; }, vecdiv:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ //v1/v2 let result = Object.assign({},v1); for(const key in result) { @@ -371,7 +371,7 @@ export const Systems = { return result; }, vecscale:( - v1:{[key:string]:number}, + v1:any, scalar:number )=>{ //v1*v2 let result = Object.assign({},v1); @@ -381,8 +381,8 @@ export const Systems = { return result; }, distance:( - v1:{[key:string]:number}, - v2:{[key:string]:number} + v1:any, + v2:any )=>{ let distance = 0; for(const key in v1) { @@ -391,7 +391,7 @@ export const Systems = { return Math.sqrt(distance); }, magnitude:( - v:{[key:string]:number} + v:any ) => { let magnitude = 0; for(const key in v) { @@ -400,11 +400,11 @@ export const Systems = { return Math.sqrt(magnitude); }, normalize:( - v:{[key:string]:number} + v:any ) => { let magnitude = Systems.collision.magnitude(v); let _mag = magnitude ? 1/magnitude : 0; - let vn = {}; + let vn = Object.assign({},v); for(const key in v) { vn[key] = v[key]*_mag; } diff --git a/src/extras/gpu/GPU.service.ts b/extras/gpu/GPU.service.ts similarity index 91% rename from src/extras/gpu/GPU.service.ts rename to extras/gpu/GPU.service.ts index 431da7f4..b16b8aad 100644 --- a/src/extras/gpu/GPU.service.ts +++ b/extras/gpu/GPU.service.ts @@ -14,7 +14,7 @@ export class GPUService extends Service { constructor(options?:any) { super(options) - this.load(this); + this.setTree(this); } @@ -26,15 +26,8 @@ export class GPUService extends Service { if(typeof fn === 'string') fn = parseFunctionFromText(fn); if(typeof fn === 'function') this.gpu.addKernel(name,fn as any,options); } - combineKernels=(name:string,fs:(string|Function)[], ckrnl?:()=>void)=>{ - for(let i = 0; i < fs.length; i++) { - if(typeof fs[i] === 'string') fs[i] = parseFunctionFromText(fs[i] as string); - } - if(typeof ckrnl === 'string') ckrnl = parseFunctionFromText(ckrnl); - this.gpu.combineKernels(name, fs, ckrnl); - } callKernel=(name:string,...args:any[])=>{ - this.gpu.callKernel(name,args); + this.gpu.callKernel(name,...args); } dft=(signalBuffer: number[], nSeconds: any, scalar?: number)=>{ if (scalar == undefined) scalar = 1; diff --git a/src/extras/index.gpu.services.ts b/extras/index.gpu.services.ts similarity index 100% rename from src/extras/index.gpu.services.ts rename to extras/index.gpu.services.ts diff --git a/src/extras/index.services.ts b/extras/index.services.ts similarity index 69% rename from src/extras/index.services.ts rename to extras/index.services.ts index 25e64c89..ae7cf55f 100644 --- a/src/extras/index.services.ts +++ b/extras/index.services.ts @@ -4,14 +4,13 @@ export * from './struct/Struct.frontend' export * from './struct/Struct.backend' -export * from './struct/genTimestamps' export * from './ecs/ECS.systems' export * from './webgl-plot/webglplot.routes' -//import gsworker from '../services/worker/Worker' //compiles the worker in the dist +import gsworker from '../services/worker/Worker' //compiles the worker in the dist export { algorithms } from './algorithms/index'; //modified algorithms object with presets -//export { gsworker } //available as a dataurl \ No newline at end of file +export { gsworker } //available as a dataurl \ No newline at end of file diff --git a/src/extras/index.storage.services.ts b/extras/index.storage.services.ts similarity index 100% rename from src/extras/index.storage.services.ts rename to extras/index.storage.services.ts diff --git a/src/extras/package-lock.json b/extras/package-lock.json similarity index 69% rename from src/extras/package-lock.json rename to extras/package-lock.json index a36fd11d..64441928 100644 --- a/src/extras/package-lock.json +++ b/extras/package-lock.json @@ -1,19 +1,20 @@ { "name": "graphscript-services", - "version": "0.3.1", + "version": "0.2.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "graphscript-services", - "version": "0.3.1", - "license": "LGPL-3.0-or-later", + "version": "0.2.1", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", - "browserfs": "~1.4.3", - "gpujsutils": "~1.0.15", - "web-worker": "~1.2.0", - "webgl-plot-utils": "~0.4.2" + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "web-worker": "^1.2.0", + "webgl-plot-utils": "~0.3.13" }, "devDependencies": { "@types/node": "~18.7.15" @@ -22,7 +23,7 @@ "../../../../AppData/Roaming/npm/node_modules/tinybuild": { "version": "0.3.181", "extraneous": true, - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "chokidar": "~3.5.3", "esbuild": "~0.14.49", @@ -50,9 +51,9 @@ } }, "node_modules/brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" }, "node_modules/browserfs": { "version": "1.4.3", @@ -69,10 +70,15 @@ "node": ">= 0.10" } }, + "node_modules/bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, "node_modules/gpujsutils": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.15.tgz", - "integrity": "sha512-V6AevSRCmAPm7+Y8Wl+aqP1Q4+6iJQbFDImsdQkX082ZWgBvN/ALK8uY8bhHqceWUzgsW6aVDZG/pdrDaPKHlA==" + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" }, "node_modules/lodash": { "version": "4.17.21", @@ -90,16 +96,16 @@ "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" }, "node_modules/webgl-plot": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.1.tgz", - "integrity": "sha512-CSLgEj+Xerd+SZoBpIWMiHk/AhoPb8ZokqmTGPaGOra0++9e5LsiAWIuUWGunOHjllvKAhSKPg7yG4+kiHifew==" + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" }, "node_modules/webgl-plot-utils": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.4.2.tgz", - "integrity": "sha512-mS4vI7O7lPNZLvd3iLIpaYAsD+kr//zvfTvGsOYRTJ4JZ/b6/ybxMELFDbtw0j1w3UWInU872ogUEnniTpGDzQ==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz", + "integrity": "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==", "dependencies": { - "webgl-plot": "~0.7.1" + "webgl-plot": "~0.7.0" } } }, @@ -119,9 +125,9 @@ } }, "brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" + "version": "0.0.25", + "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz", + "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" }, "browserfs": { "version": "1.4.3", @@ -132,10 +138,15 @@ "pako": "^1.0.4" } }, + "bson-objectid": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", + "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + }, "gpujsutils": { - "version": "1.0.15", - "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.15.tgz", - "integrity": "sha512-V6AevSRCmAPm7+Y8Wl+aqP1Q4+6iJQbFDImsdQkX082ZWgBvN/ALK8uY8bhHqceWUzgsW6aVDZG/pdrDaPKHlA==" + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz", + "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" }, "lodash": { "version": "4.17.21", @@ -153,16 +164,16 @@ "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" }, "webgl-plot": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.1.tgz", - "integrity": "sha512-CSLgEj+Xerd+SZoBpIWMiHk/AhoPb8ZokqmTGPaGOra0++9e5LsiAWIuUWGunOHjllvKAhSKPg7yG4+kiHifew==" + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" }, "webgl-plot-utils": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.4.2.tgz", - "integrity": "sha512-mS4vI7O7lPNZLvd3iLIpaYAsD+kr//zvfTvGsOYRTJ4JZ/b6/ybxMELFDbtw0j1w3UWInU872ogUEnniTpGDzQ==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz", + "integrity": "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==", "requires": { - "webgl-plot": "~0.7.1" + "webgl-plot": "~0.7.0" } } } diff --git a/src/extras/package.json b/extras/package.json similarity index 80% rename from src/extras/package.json rename to extras/package.json index 8b72994b..bfd2540c 100644 --- a/src/extras/package.json +++ b/extras/package.json @@ -1,10 +1,10 @@ { "name": "graphscript-services", - "version": "0.3.2", + "version": "0.2.23", "description": "Extra services for graphscript.", "main": "dist/index.services.js", "module": "dist/index.services.esm.js", - "types": "dist/src/extras/index.services.d.ts", + "types": "dist/extras/index.services.d.ts", "scripts": { "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", "build": "tinybuild build", @@ -21,13 +21,14 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", - "browserfs": "~1.4.3", - "gpujsutils": "~1.0.15", - "web-worker": "~1.3.0", - "webgl-plot-utils": "~0.4.2" + "brainsatplay-math": "~0.0.25", + "browserfs": "^1.4.3", + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "web-worker": "^1.2.0", + "webgl-plot-utils": "~0.3.13" }, "nodemonConfig": { "env": { diff --git a/src/extras/storage/BFSUtils.js b/extras/storage/BFSUtils.js similarity index 66% rename from src/extras/storage/BFSUtils.js rename to extras/storage/BFSUtils.js index 2281dddd..b6337e41 100644 --- a/src/extras/storage/BFSUtils.js +++ b/extras/storage/BFSUtils.js @@ -1,6 +1,6 @@ import {CSV} from './csv.js' -export let fsInited = false; +export let fsInited = false import * as BrowserFS from 'browserfs' export const fs = BrowserFS.BFSRequire('fs'); const BFSBuffer = BrowserFS.BFSRequire('buffer').Buffer; @@ -10,7 +10,6 @@ const BFSBuffer = BrowserFS.BFSRequire('buffer').Buffer; //Generic reimplementation of reading/writing buffered objects from/to CSVs and IndexedDB -let initPromise; // ----------------------------- Generic Functions for BrowserFS ----------------------------- export const initFS = async ( dirs = ['data'], @@ -18,26 +17,16 @@ export const initFS = async ( onerror=(e)=>{}, filesystem='IndexedDB' //default is IndexedDB //https://github.com/jvilk/BrowserFS see all ) => { - if (fsInited) { - if(initPromise) { - await initPromise; - } - return true; - } + if (fsInited) return true else { fsInited = true; - initPromise = new Promise ((resolve, reject) => { - //let oldmfs = fs.getRootFS(); + return new Promise (resolve => { + let oldmfs = fs.getRootFS(); BrowserFS.FileSystem[filesystem].Create({}, (e, mountableFileSystem) => { - if (e) { - reject(e); - return - } + if (e) throw e; if (!mountableFileSystem) { onerror(e); - - reject( new Error(`Error creating BrowserFS`) ); - return + throw new Error(`Error creating BrowserFS`); } BrowserFS.initialize(mountableFileSystem); //fs now usable with imports after this //console.log(mountableFileSystem,filesystem); @@ -50,11 +39,11 @@ export const initFS = async ( Promise.all(promises).then((values) => { oninit(values); + fsInited = true resolve(true) - }); - }); - }); - return await initPromise; + }) + }) + }) } } @@ -62,7 +51,7 @@ export const exists = async (path='') => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(resolve => { + return new Promise(resolve => { fs.exists('/'+path, function (exists) { resolve(exists); }); @@ -74,7 +63,7 @@ export const readFile = async (path='data') => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(resolve => { + return new Promise(resolve => { fs.readFile('/'+path, function(e, output) { resolve(output) }); @@ -88,18 +77,12 @@ export async function readFileChunk (path='data', begin = 0, end = 5120, onread= else await dirExists(fs,path.split('/')[0]); if (path != ''){ - return await new Promise(async (resolve, reject) => { + return new Promise(async resolve => { fs.open('/'+path, 'r', (e, fd) => { - if (e) { - reject(e); - return - } + if (e) throw e; fs.read(fd, end, begin, 'utf-8', (er, output, bytesRead) => { - if (er) { - reject(er); - return - } + if (er) throw er; if (bytesRead !== 0) { let data = output.toString(); //Now parse the data back into the buffers. @@ -122,12 +105,9 @@ export const getFilenames = async (directory = 'data', onload=(directory)=>{}) = if(!fsInited) await initFS([directory]); else await dirExists(fs,directory); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.readdir('/'+directory, (e, dir) => { - if (e){ - reject(e); - return - } + if (e) throw e; if (dir) { //console.log("files", dir); onload(dir); @@ -142,12 +122,9 @@ export const writeFile = async (path, data, onwrite=(data)=>{}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.writeFile('/'+path, data, (err) => { - if (err) { - reject(err); - return - } + if (err) throw err; onwrite(data); resolve(true); }); @@ -158,12 +135,9 @@ export const appendFile = async (path, data, onwrite=(data)=>{}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.appendFile('/'+path, data, (err) => { - if (err) { - reject(err); - return - } + if (err) throw err; onwrite(data); resolve(true); }); @@ -174,7 +148,7 @@ export const deleteFile = async (path='data', ondelete=()=>{}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(resolve => { + return new Promise(resolve => { if (path != ''){ fs.unlink('/'+path, (e) => { if (e) console.error(e); @@ -199,9 +173,9 @@ export const readFileAsText = async ( if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise(async (resolve, reject) => { + return new Promise(async resolve => { - let size = await getFileSize(path); + let size = await getFileSize(path,dir) if(end === 'end') { end = size; @@ -210,15 +184,9 @@ export const readFileAsText = async ( } fs.open('/'+path, 'r', (e, fd) => { - if (e) { - reject(e); - return - } + if (e) throw e; fs.read(fd, end, begin, 'utf-8', (er, output, bytesRead) => { - if (er) { - reject(er); - return - } + if (er) throw er; if (bytesRead !== 0) { let data = output.toString(); //Now parse the data back into the buffers. @@ -241,12 +209,9 @@ export const listFiles = async (dir='data', onload=(directory)=>{}) => { if(!fsInited) await initFS([dir]); else await dirExists(fs,dir); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.readdir('/'+dir, (e, directory) => { - if (e) { - reject(e); - return - } + if (e) throw e; if (directory) { onload(directory); // if(fs_html_id){ @@ -277,17 +242,13 @@ export const listFiles = async (dir='data', onload=(directory)=>{}) => { -export const getFileSize = async (path='data',onread=(size)=>{}) => { - +export const getFileSize = async (path='data',onread=(size)=>{console.log(size);}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.stat('/'+path,(e,stats) => { - if(e) { - reject(e) - return - } + if(e) throw e; let filesize = stats.size; onread(filesize); resolve(filesize); @@ -296,22 +257,16 @@ export const getFileSize = async (path='data',onread=(size)=>{}) => { } -export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) => { +export const getCSVHeader = async (path='data', onopen=(header, filename)=>{console.log(header,filename);}) => { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { fs.open('/'+path,'r',(e,fd) => { - if(e) { - reject(e) - return - } + if(e) throw e; fs.read(fd,65535,0,'utf-8',(er,output,bytesRead) => { //could be a really long header for all we know - if (er) { - reject(er) - return; - } + if (er) throw er; if(bytesRead !== 0) { let data = output.toString(); let lines = data.split('\n'); @@ -332,30 +287,22 @@ export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) = if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - return await new Promise((resolve, reject) => { + return new Promise(resolve => { if (path != ''){ fs.stat('/' + path, (e, stats) => { - if (e) { - reject(e); - return - } + if (e) throw e; let filesize = stats.size; + console.log(filesize) fs.open(path, 'r', (e, fd) => { - if (e) { - reject(e); - return - } + if (e) throw e; let i = 0; let maxFileSize = fileSizeLimitMb * 1024 * 1024; let end = maxFileSize; if (filesize < maxFileSize) { end = filesize; fs.read(fd, end, 0, 'utf-8', (e, output, bytesRead) => { - if (e) { - reject(e); - return - } - if (bytesRead !== 0) CSV.saveCSV(output.toString(), path.split('/')[1]); + if (e) throw e; + if (bytesRead !== 0) CSV.saveCSV(output.toString(), path); fs.close(fd); resolve(true); }); @@ -366,12 +313,9 @@ export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) = if (i + end > filesize) { end = filesize - i; } let chunk = 0; fs.read(fd, end, i, 'utf-8', (e, output, bytesRead) => { - if (e) { - reject(e); - return - } + if (e) throw e; if (bytesRead !== 0) { - CSV.saveCSV(output.toString(), path.split('/')[1] + "_" + chunk); + CSV.saveCSV(output.toString(), path + "_" + chunk); i += maxFileSize; chunk++; writeChunkToFile(); @@ -393,42 +337,12 @@ export const getCSVHeader = async (path='data', onopen=(header, filename)=>{}) = }); } -//iterate asynchronously over a file (or a specific range of a file) and run a function on the data -export async function processCSVChunksFromDB(path='data', onData=(csvdata,start,end,size)=>{}, maxChunkSize=10000, start=0, end='end', options={}) { - - let size = await getFileSize(path); - - let partition = start; - - return await new Promise((res,rej) => { - let processPartition = () => { - let endChunk = partition+maxChunkSize; - if(endChunk > size) { - endChunk = size; - } - readCSVChunkFromDB(path,partition,endChunk,options).then(async (result) => { - await onData(result,partition,endChunk,size); - //console.log(partition,endChunk,size); - partition = endChunk; - if(partition !== size) { - processPartition(); - } else { - res(true); - } - }).catch(rej); - - } - - processPartition(); - }); -} //returns an object with the headers and correctly sized outputs (e.g. single values or arrays pushed in columns) -export async function readCSVChunkFromDB(path='data', start=0, end='end', options={}) { +export async function readCSVChunkFromDB(path='data', start=0, end='end') { if(!fsInited) await initFS([path.split('/')[0]]); else await dirExists(fs,path.split('/')[0]); - const transpose = options.transpose || false; let head = await getCSVHeader(path); @@ -437,7 +351,7 @@ export async function readCSVChunkFromDB(path='data', start=0, end='end', option let resultLengths = []; let resultNames = []; - let results = (transpose) ? [] : {} + let results = {}; head.forEach((v) => { if(v) { @@ -454,62 +368,53 @@ export async function readCSVChunkFromDB(path='data', start=0, end='end', option end = size; } + let data = await readFileChunk(path,start,end); - let data = (await readFileChunk(path,start,end))?.split('\n').slice(1, -1) // exclude header and last pseudoline - - let preprocess = (value) => { - try { value = JSON.parse(value) } catch {} - return value; - } - - if(data) data.forEach((r,i) => { + let headeridx = 0; + let lastIdx = 0; + data.forEach((r,i) => { let row = r.split(','); - if (transpose) { - const entry = {} - if(options.json) row.forEach((v, idx) => {if(options.json) entry[resultNames[idx]] = preprocess(v); else entry[resultNames[idx]] = v;}) - results.push(entry) - } else { - row.forEach((v,i) => { - const header = resultNames[i] - if (!results[header]) results[header] = []; - if(options.json) results[header].push(preprocess(v)) - else results[header].push(v); - }) - } + while(lastIdx < row.length-1) { + let l = resultLengths[headeridx]; + if(l === 1) { + results[resultNames[headeridx]].push(row[lastIdx]); + lastIdx++; + } + else { + results[resultNames[headeridx]].push(row[lastIdx].slice(lastIdx,l)); + lastIdx+=l; + } + } }); - return results; + } + let directories = {}; export const dirExists = async (fs, directory) => { - if(!fsInited) await initFS([directory]); - return await new Promise((resolve, reject) => { - if(!directory) reject(false); + return new Promise((resolve, reject) => { if (directories[directory] === 'exists' || directories[directory] === 'created'){ resolve() } else { - if(directory[0] === '/') directory = directory.substring(1); - if(!directory) reject(false); fs.exists(`/${directory}`, (exists) => { if (exists) { directories[directory] = 'exists' - //console.log(`/${directory} exists!`) + console.log(`/${directory} exists!`) resolve(); } else if (directories[directory] === 'creating'){ - //console.log(directory + ' is still being created.') + console.log(directory + ' is still being created.') resolve(); } else { - //console.log('creating ' + `/${directory}`, fs); + console.log('creating ' + `/${directory}`, fs); directories[directory] = 'creating'; fs.mkdir(`/${directory}`, 1, (err) => { if (err) { - reject(err); - return + throw err; } directories[directory] = 'created' setTimeout(resolve, 500) @@ -521,19 +426,19 @@ export const dirExists = async (fs, directory) => { }); } -//redundant declaration prevents minification of names for the routes + export const BFSRoutes = { - initFS:initFS, - dirExists:dirExists, - exists:exists, - readFile:readFile, - readFileChunk:readFileChunk, - getFilenames:getFilenames, - writeFile:writeFile, - appendFile:appendFile, - deleteFile:deleteFile, - readFileAsText:readFileAsText, - getFileSize:getFileSize, - getCSVHeader:getCSVHeader, - listFiles:listFiles + initFS, + dirExists, + exists, + readFile, + readFileChunk, + getFilenames, + writeFile, + appendFile, + deleteFile, + readFileAsText, + getFileSize, + getCSVHeader, + listFiles }; \ No newline at end of file diff --git a/src/extras/storage/BFS_CSV.ts b/extras/storage/BFS_CSV.ts similarity index 77% rename from src/extras/storage/BFS_CSV.ts rename to extras/storage/BFS_CSV.ts index 29df8331..63c01657 100644 --- a/src/extras/storage/BFS_CSV.ts +++ b/extras/storage/BFS_CSV.ts @@ -1,4 +1,4 @@ -import { appendFile, deleteFile, exists, getCSVHeader, listFiles, processCSVChunksFromDB, readCSVChunkFromDB, writeFile, writeToCSVFromDB } from './BFSUtils'; +import { appendFile, deleteFile, exists, getCSVHeader, listFiles, readCSVChunkFromDB, writeFile, writeToCSVFromDB } from './BFSUtils'; import { CSV, parseCSVData, toISOLocal } from './csv'; //We have object formats coming in like {x,y,z}, tied to devices with USB data or BLE data with specifiers @@ -11,7 +11,6 @@ const CSV_REFERENCE:{ lastX:number, //latest line, unjoined buffer:string, //appended strings waiting to be written to browserfs buffered:number, - toFixed:number, bufferSize:number|undefined, xIncrement?:number|undefined } @@ -39,16 +38,9 @@ export const appendCSV = async ( newData:{[key:string]:number|number[]}, //assume uniformly sized data is passed in, so pass separate timestamp intervals separately filename:string, header?:string[], - options?: { - json?:boolean, - toFixed?:number, - bufferSize?:number, - xIncrement?:number - } + toFixed:number=5 ) => { - //console.log(newData); - //console.log('append',filename); if(!filename) { let keys = Object.keys(CSV_REFERENCE); @@ -66,15 +58,11 @@ export const appendCSV = async ( lastX:undefined as any, buffer:'', buffered:0, //buffer numbers to be appended? - bufferSize:options?.bufferSize ? options.bufferSize : 0, - toFixed:options?.toFixed ? options.toFixed : 0, - xIncrement:options?.xIncrement ? options.xIncrement : 0 + bufferSize:0, + xIncrement:undefined }; csv = CSV_REFERENCE[filename]; - - const existingHeader = await getCSVHeader(filename).catch(() => null); - const isDifferent = (!existingHeader || existingHeader !== csv.header.join(',')) - if (isDifferent) header = csv.header; // Only push header if it's different + header = csv.header; } if (!csv.header || csv.header?.length === 0) { let keys = Array.from(Object.keys(newData)); if (keys.indexOf('timestamp') > -1) keys.splice(keys.indexOf('timestamp'), 1); @@ -85,10 +73,12 @@ export const appendCSV = async ( let maxLen = 1; //max length of new arrays being appended, if any for(const key in newData) { - const value = newData[key] - if(csv.header.indexOf(key) > -1 && value && Array.isArray(value) && value?.length > maxLen) maxLen = value?.length; + if(csv.header.indexOf(key) > -1 && (newData[key] as any)?.length > maxLen) { + maxLen = (newData[key] as any)?.length; + } } + let x; if(csv.xIncrement) { @@ -111,9 +101,8 @@ export const appendCSV = async ( } } - else if(newData[csv.header[0]]) x = newData[csv.header[0]]; //first csv value treated as x for reference for growing the csv, mainly to generate timestamps if being used but not defined - else x = Date.now(); - + else x = newData[csv.header[0]]; //first csv value treated as x for reference for growing the csv, mainly to generate timestamps if being used but not defined + if(typeof csv.lastX === 'undefined') csv.lastX = Array.isArray(x) ? x[0] : x; if(typeof x === 'undefined') { if(csv.header[0].includes('time')) { @@ -133,10 +122,10 @@ export const appendCSV = async ( } } else if (maxLen > 1 && (x as any)?.length !== maxLen) { if(!Array.isArray(x) || x.length === 1) { - x = interpolerp(csv.lastX,x,maxLen,true); //we are gonna upsample x to the maximum size array that's been passed in + x = interpolerp(csv.lastX,x,maxLen); //we are gonna upsample x to the maximum size array that's been passed in x.shift(); } else { - x = interpolerp(x[0],x[x.length-1],maxLen,true); //upsample using new timestamps + x = interpolerp(x[0],x[x.length-1],maxLen); //upsample using new timestamps x.shift(); } } @@ -184,8 +173,7 @@ export const appendCSV = async ( } if(typeof toAppend[i][j] === 'number' && Math.floor(toAppend[i][j]) !== toAppend[i][j]) - toAppend[i][j] = toAppend[i][j].toFixed(CSV_REFERENCE[filename].toFixed) - + toAppend[i][j] = toAppend[i][j].toFixed(toFixed) } } } else { @@ -203,8 +191,7 @@ export const appendCSV = async ( if(typeof toAppend[0][j] === 'number' && Math.floor(toAppend[0][j]) !== toAppend[0][j]) - toAppend[0][j] = toAppend[0][j].toFixed(CSV_REFERENCE[filename].toFixed); - + toAppend[0][j] = toAppend[0][j].toFixed(toFixed) } } @@ -214,15 +201,13 @@ export const appendCSV = async ( if(header) csvProcessed += header.join(',') + '\n'; //append new headers when they show up toAppend.forEach((arr) => { - csvProcessed += ((options?.json) ? arr.map(v => JSON.stringify(v)) : arr).join(',') + '\n'; - // csvProcessed += arr.join(',') + '\n'; + csvProcessed += arr.join(',') + '\n'; if(csv.bufferSize) csv.buffered++; }); csv.lastX = toAppend[toAppend.length-1][0]; //reference the last array written as the latest data for if we don't pass timestamps //okay we are ready to append arrays to the file - if(csv.bufferSize) { csv.buffer += csvProcessed; if(csv.buffered > csv.bufferSize) { @@ -255,10 +240,10 @@ export const appendCSV = async ( return r; } - else return await Promise.resolve(true); + else return Promise.resolve(true); } else { - return await new Promise((res,rej) => { + return new Promise((res,rej) => { exists(filename).then((fileExists) => { if(!fileExists) { writeFile( @@ -278,7 +263,7 @@ export const appendCSV = async ( ); } }); - }) as any as Promise + }) as Promise } //e.g. generalize this for other data types } @@ -293,42 +278,35 @@ export const updateCSVHeader = (header:any[],filename:string) => { export const createCSV = ( filename:string, header:string[], - toFixed:number=5, //limit decimals (saves a ton of memory), set to 0 for integers bufferSize:number=0, //accumulate a certain number of lines before writing to BFS? (necessary for > 100 updates/sec fyi) xIncrement?:number //fixed time increment for newlines? ) => { - if(!CSV_REFERENCE[filename]) { - if(header?.indexOf('timestamp') > 1) {header.splice(header.indexOf('timestamp'),1); header.unshift('timestamp')} - if((header?.[0].toLowerCase().includes('time') || header?.[0].toLowerCase().includes('unix')) && header[1] !== 'localized') { - header.splice(1,0,'localized') //toISOLocal - } - - CSV_REFERENCE[filename] = { - header, - lastX:header[1] === 'localized' ? Date.now() : 0, - bufferSize, - buffer:'', - buffered:0, - toFixed, - xIncrement - }; - - //overwrite existing files - return new Promise((res,rej) => { - exists(filename).then((doesExist) => { - if(!doesExist) { //try not to overwrite - writeFile( - filename, - CSV_REFERENCE[filename].header? CSV_REFERENCE[filename].header.join(',')+'\n' : '', - (written:boolean) => { - res(written); - } - ).catch(rej); - } - }); - }); + if(header?.indexOf('timestamp') > 1) {header.splice(header.indexOf('timestamp'),1); header.unshift('timestamp')} + if((header?.[0].toLowerCase().includes('time') || header?.[0].toLowerCase().includes('unix')) && header[1] !== 'localized') { + header.splice(1,0,'localized') //toISOLocal } + + CSV_REFERENCE[filename] = { + header, + lastX:header[1] === 'localized' ? Date.now() : 0, + bufferSize, + buffer:'', + buffered:0, + xIncrement + }; + + //overwrite existing files + return new Promise((res,rej) => { + writeFile( + filename, + CSV_REFERENCE[filename].header? CSV_REFERENCE[filename].header.join(',')+'\n' : '', + (written:boolean) => { + res(written); + } + ).catch(rej); + }); + } @@ -373,17 +351,16 @@ export const visualizeDirectory = (dir:string, parentNode=document.body) => { } export const csvRoutes = { - appendCSV:appendCSV, - updateCSVHeader:updateCSVHeader, - createCSV:createCSV, - visualizeDirectory:visualizeDirectory, + appendCSV, + updateCSVHeader, + createCSV, + visualizeDirectory, openCSV:CSV.openCSV, saveCSV:CSV.saveCSV, openCSVRaw:CSV.openCSVRaw, - parseCSVData:parseCSVData, - getCSVHeader:getCSVHeader, - writeToCSVFromDB:writeToCSVFromDB, - readCSVChunkFromDB:readCSVChunkFromDB, - processCSVChunksFromDB:processCSVChunksFromDB, - toISOLocal:toISOLocal + parseCSVData, + getCSVHeader, + writeToCSVFromDB, + readCSVChunkFromDB, + toISOLocal } \ No newline at end of file diff --git a/src/extras/storage/csv.js b/extras/storage/csv.js similarity index 63% rename from src/extras/storage/csv.js rename to extras/storage/csv.js index 35fcdeb8..bdc3f2ad 100644 --- a/src/extras/storage/csv.js +++ b/extras/storage/csv.js @@ -4,7 +4,7 @@ export class CSV { //data=["1|2","11|22"], or data=[[1,2,"xyz"],[2,3,"abc"],etc] constructor(onOpen=this.onOpen, saveButtonId=null, openButtonId=null) { this.onOpen = onOpen; - this.notes = []; //order comments by data index {idx:0,text:"comment"} + this.notes = [{idx:0,text:"comment"}]; //order comments by data index if(saveButtonId !== null) { document.getElementById(saveButtonId).addEventListener('click', this.saveCSV); @@ -33,80 +33,65 @@ export class CSV { //data=["1|2","11|22"], or data=[[1,2,"xyz"],[2,3,"abc"],etc] } //Converts an array of strings (e.g. raw data stream text) or an array of arrays representing lines of data into CSVs - static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n", name=new Date().toISOString()){ + static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){ var hiddenElement = document.createElement('a'); hiddenElement.href = "data:text/csv;charset=utf-8," + encodeURI(csvDat); hiddenElement.target = "_blank"; if (name !== "") { - //if(!name.includes('.csv')) name +='.csv'; hiddenElement.download = name; } else{ - hiddenElement.download = new Date().toISOString() + '.csv'; + hiddenElement.download = Date().toISOString(); } hiddenElement.click(); } static openCSV(delimiter = ",", onOpen = (csvDat, header, path)=>{return csvDat, header, path;}) { - return new Promise((res,rej) => { - var input = document.createElement('input'); - input.accept = '.csv'; - input.type = 'file'; - - input.onchange = (e) => { - var file = e.target.files[0]; - var reader = new FileReader(); - reader.onload = (event) => { - var tempcsvData = event.target.result; - var tempcsvArr = tempcsvData.split("\n"); - let header = []; - var csvDat = []; - tempcsvArr.pop(); - tempcsvArr.forEach((row,i) => { - if(i==0){ header = row.split(delimiter); } - else{ - var temp = row.split(delimiter); - csvDat.push(temp); - } - }); - onOpen(csvDat,header,input.value); - input.value = ''; - res({ - data:csvDat, - header:header, - filename:input.value - }); - } - reader.readAsText(file); + var input = document.createElement('input'); + input.accept = '.csv'; + input.type = 'file'; + + input.onchange = (e) => { + var file = e.target.files[0]; + var reader = new FileReader(); + reader.onload = (event) => { + var tempcsvData = event.target.result; + var tempcsvArr = tempcsvData.split("\n"); + let header = []; + var csvDat = []; + tempcsvArr.pop(); + tempcsvArr.forEach((row,i) => { + if(i==0){ header = row.split(delimiter); } + else{ + var temp = row.split(delimiter); + csvDat.push(temp); + } + }); + onOpen(csvDat,header,input.value); + input.value = ''; } - input.click(); - }); - + reader.readAsText(file); + } + input.click(); } //Dump CSV data without parsing it. static openCSVRaw(onOpen = (csvDat, path)=>{return csvDat, path;}) { - return new Promise((res,rej) => { - var input = document.createElement('input'); - input.accept = '.csv'; - input.type = 'file'; - - input.onchange = (e) => { - var file = e.target.files[0]; - var reader = new FileReader(); - reader.onload = (event) => { - var tempcsvData = event.target.result; - onOpen(tempcsvData, input.value); - input.value = ''; - res({ - data:tempcsvData, - filename: input.value - }) - } - reader.readAsText(file); + var input = document.createElement('input'); + input.accept = '.csv'; + input.type = 'file'; + + input.onchange = (e) => { + var file = e.target.files[0]; + var reader = new FileReader(); + reader.onload = (event) => { + var tempcsvData = event.target.result; + onOpen(tempcsvData, input.value); + input.value = ''; } - input.click(); - }) + reader.readAsText(file); + } + input.click(); } onOpen(csvDat=[],header=[]) { // Customize this function in your init script, access data with ex. console.log(serialMonitor.csvDat), where var serialMonitor = new chromeSerial(defaultUI=false) @@ -116,7 +101,7 @@ export class CSV { //data=["1|2","11|22"], or data=[[1,2,"xyz"],[2,3,"abc"],etc] -//e.g. let csv = CSV.openCSVRaw((data,head,path) => { +//e.g. let csv = CSV.openCSV(',',(data,head,path) => { // let name = path.split('/').pop(); // result = parseCSVData(data,name,head); // console.log(result); @@ -145,9 +130,9 @@ export const parseCSVData = ( for(let j = 0; j < line.length; j++){ - if(!result[header[j]]) result[header[j]] = []; - - result[header[j]].push(line[j]); + if(!result[header[j]]) result[header[j]] + + result[header[j]] = line[j]; } } @@ -156,11 +141,7 @@ export const parseCSVData = ( } ) => { - let lines; - if(data.includes('\r')) - lines = data.split('\r\n'); - else lines = data.split('\n'); - + let lines = data.split('\n'); if(!head) head = lines[0]; lines.shift(); @@ -218,27 +199,27 @@ export function toISOLocal(d) { */ //spits out an array of CSV rows in string format with endlines added export const processDataForCSV = (options={}) => { - if(!options.data) return undefined; - if(!Array.isArray(options.data)) options.data = [options.data]; - if(options.data && !options.header) options.header = Object.keys(options.data[0]); - let head = [...options.header]; - if(head.indexOf('timestamp') > -1) { - head.splice(head.indexOf('timestamp') + 1, 0, 'localized'); - } - - let header = head.join(','); + let header = ''; + if(typeof options.data[0] === 'object' && !Array.isArray(options.data[0])){ + if(options.data[0].x) header = 'x,'; + else if (options.data[0].timestamp) header = 'timestamp,localtime,'; + } + let headeridx = 0; - let lines = []; - let foreach = (obj, i) => { + let lines = {}; //associative array (e.g. timestamp = row) + options.data.forEach((obj, i) => { if(Array.isArray(obj)) { //unstructured data just gets pushed into a column for(let j = 0; j < obj.length; j++) { if(!lines[j]) lines[j] = ''; + if(Array.isArray(obj[j])) { + if(j === 0) header[headeridx] += options.header[headeridx]+new Array(obj[j].length-1).fill('').join(','); //add empty spaces lines[j] += obj[j].join(',') + ','; headeridx+=obj[j].length; } else { + if(j === 0) header[headeridx] += options.header[headeridx]+','; lines[j] += obj[j] + ','; headeridx++; } @@ -250,34 +231,42 @@ export const processDataForCSV = (options={}) => { } else if (obj.timestamp) { x = obj.timestamp; } - let keys = options.header; for(let j = 0; j < x.length; j++) { - if(!lines[j]) lines[j] = x[j] + ','; + + if(!lines[x[j]]) lines[x[j]] = x[j] + ','; if(obj.timestamp) { - keys.splice(keys.indexOf('timestamp'), 1); - lines[j] += toISOLocal(obj.timestamp[j]) + ','; //add local timezone data - } else if (obj.x) { - keys.splice(keys.indexOf('x')); - } - let lastIndex = keys.length - 1; - for(let k = 0; k < keys.length; k++) { - const key = keys[k]; - if(Array.isArray(obj[key][j])) { - lines[j] += obj[key][j].join(',') + (k === lastIndex ? '' : ','); - } - else { - lines[j] += obj[key][j] + (k === lastIndex ? '' : ','); + lines[x[j]] += toISOLocal(obj.timestamp[j]) + ','; //add local timezone data + } + + for(const prop in obj) { + if(prop !== 'x') { + if(!lines[x[j]]) lines[x[j]] = ''; + + if(Array.isArray(obj[prop][j])) { + if(j === 0) header[headeridx] += options.header[headeridx]+Array(obj[prop][j].length-1).fill('').join(','); //add empty spaces + lines[x[j]] += obj[prop][j].join(',') + ','; + headeridx+=obj[prop][j].length; + } + else { + if(j === 0) header[headeridx] += options.header[headeridx]+','; + lines[x[j]] += obj[prop][j] + ','; + headeridx++; + } } } } } - } - - options.data.forEach(foreach); + }); + header.splice(header.length-1,1); //remove last comma header += '\n'; - let joined = lines.join('\n'); + let joined = ''; + + for(const prop in lines) { + lines[prop].splice(lines[prop].length-1,1); //splice off the trailing comma + joined += lines[prop] + '\n'; //add a newline + } let result = {filename:options.filename,header:header,body:joined}; diff --git a/src/extras/struct/Struct.backend.ts b/extras/struct/Struct.backend.ts similarity index 66% rename from src/extras/struct/Struct.backend.ts rename to extras/struct/Struct.backend.ts index 5d0fc613..aceb0db0 100644 --- a/src/extras/struct/Struct.backend.ts +++ b/extras/struct/Struct.backend.ts @@ -1,28 +1,21 @@ -import { ObjectId } from "./datastructures/bson.cjs" +import ObjectID from "bson-objectid" import { AuthorizationStruct, CommentStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; -import { genTimestampFromString, TimeSpecifier } from './genTimestamps' import { Service } from "../../services/Service"; import { User } from '../../services/router/Router'; -import { DS } from "./datastructures/index.js"; - -//todo: -//edit notification system to register to a single object for all notification associated for a single user, saves some space -//template a finer-grained permission system -//instructions - const randomId = (prefix?) => ((prefix) ? `${prefix}_` : '') + Math.floor(1000000000000000*Math.random()) -export const toObjectId = (str) => { - return (typeof str === 'string' && str.length === 24) ? new ObjectId(str) : str //wraps a string with an ObjectId if it isn't +export const toObjectID = (str) => { + return (typeof str === 'string' && str.length === 24) ? ObjectID(str) : str //wraps a string with an objectid if it isn't } -export const getStringId = (mongoid:string|ObjectId) => { - if(typeof mongoid === 'object') return mongoid.toString() //parse strig from mongo ObjectId +export const getStringId = (mongoid:string|ObjectID) => { + if(typeof mongoid === 'object') return mongoid.toString() //parse strig from mongo objectid else return mongoid; } type CollectionsType = { + users?: CollectionType [x:string]: CollectionType } @@ -59,100 +52,77 @@ export class StructBackend extends Service { debug:boolean=false; db: any; // mongodb instance (mongoose) - users:{[key:string]:User} = {}; - collections: CollectionsType = {}; - mode: 'local' | 'mongo' | string = 'local'; - - useAuths: boolean = true; //check if the user querying has the correct permissions - useAccessTokens: boolean = false; //extra security - useRefreshTokens: boolean = false; //fallback - - accessTokens:Map = new Map(); - refreshTokens:Map = new Map(); + users:{[key:string]:User} = {} + collections: CollectionsType = {} + mode: 'local' | 'mongodb' | string + useAuths: boolean = true //check if the user querying has the correct permissions constructor( options?:any, dboptions?:{ users?:{[key:string]:User}, - mode?:'local' | 'mongo' | string, + mode?:'local' | 'mongodb' | string, db?:any, //mongodb instance (mongoose) - collections?:CollectionsType, - useAuths?:boolean, - debug?:boolean, - useAccessTokens?:boolean, - useRefreshTokens?:boolean + collections?:CollectionsType } ) { super(options); - this.load(this); - - if(dboptions) { - this.initDB(dboptions); - } - - } - - initDB = (dboptions) => { - this.db = dboptions.db; + this.setTree(this); if(dboptions?.users) this.users = dboptions.users; //set the reference so this keeps concurrent with the user router - if(dboptions.mode) this.mode = dboptions.mode; + if(dboptions?.db) this.mode = (this.db) ? ((dboptions.mode) ? dboptions.mode : 'local') : 'local' if(dboptions?.collections) this.collections = dboptions.collections; - if(dboptions.debug) this.debug = dboptions.debug; - if(dboptions.useAccessTokens) this.useAccessTokens = dboptions.useAccessTokens; - if(dboptions.useRefreshTokens) this.useRefreshTokens = dboptions.useRefreshTokens; - if('useAuths' in dboptions) this.useAuths = dboptions.useAuths; - defaultCollections.forEach(k => { if (!this.collections[k]) { this.collections[k] = (this.db) ? {instance: this.db.collection(k)} : {} this.collections[k].reference = {} } - }); + }) + + } //------------------------------------ //routes to be loaded - query = async (requestingUserId:string,collection?:any,queryObj?:any,findOne?:boolean,skip?:number, token?:string) => { + query = async (requestingUserId:string,collection?:any,queryObj?:any,findOne?:boolean,skip?:number) => { let user = this.users[requestingUserId]; if(!user) return false; if(this.mode.indexOf('mongo') > -1) { - return await this.queryMongo(user,collection,queryObj,findOne,skip,token) + return await this.queryMongo(user,collection,queryObj,findOne,skip) } else { let res = this.getLocalData(user,collection); if(res && !Array.isArray(res)) { let passed = !this.useAuths; if(!res?.ownerId) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,res,'READ',token); - if(passed) return res; + else if(this.useAuths) passed = await this.checkAuthorization(user,res); } if(typeof skip === 'number' && Array.isArray(res)) if(res.length > skip) res.splice(0,skip); let data:any[] = []; if(res) await Promise.all(res.map(async(s) => { let struct = this.getLocalData(getStringId(s._id)); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); })); return data; } } - getUser = async (requestingUserId:string, lookupId:string, basicInfo?:boolean, token?:string) => { + getUser = async (requestingUserId:string, lookupId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data:any; if(this.mode.indexOf('mongo') > -1) { - data = await this.getMongoUser(user, lookupId, undefined, basicInfo, token); + data = await this.getMongoUser(user,lookupId); } else { let struct = this.getLocalData('profile',{_id:lookupId}); - if(!struct) data = {user:undefined}; + if(!struct) data = {user:{}}; else { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) { let groups = this.getLocalData('group',{ownerId:lookupId}); let auths = this.getLocalData('authorization',{ownerId:lookupId}); @@ -164,62 +134,36 @@ export class StructBackend extends Service { return data; } - setUser = async (requestingUserId:string, struct:Partial, token:string) => { + setUser = async (requestingUserId:string, struct:Partial) => { let user = this.users[requestingUserId]; if(!user) return false; let data:any; - - if(struct.accessToken) { - this.accessTokens.set(requestingUserId, token); - } - if(struct.refreshToken) { - this.refreshTokens.set(requestingUserId, struct.refreshToken); - } - - //don't save these to mongodb - delete struct.accessToken; - delete struct.refreshToken; - - //delete on user object too, just to be sure its only on the structbackend object - delete user.accessToken; - delete user.refreshToken; - if(this.mode.indexOf('mongo') > -1) { - data = await this.setMongoUser(user,struct,token); + data = await this.setMongoUser(user,struct); } else { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct, 'WRITE', token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct, 'WRITE'); if(passed) this.setLocalData(struct); return true; - } - if(this.debug) console.log('setUser user:',user,'input:',struct,'output',data); - return data; + } + if(this.debug) console.log('setUser user:',user,'input:',struct,'output',data) + return data; } - getUsersByIds = async (requestingUserId:string, userIds:string[], basicInfo?:boolean) => { + getUsersByIds = async (requestingUserId:string, userIds:string[]) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoUsersByIds(user, userIds, basicInfo); + data = await this.getMongoUsersByIds(user,userIds); } else { data = []; if(Array.isArray(userIds)) { let struct = this.getLocalData('profile',{_id:userIds}); - if(struct) { - if(basicInfo) data.push({ - _id:struct._id, - username:struct.username, - firstName:struct.firstName, - lastName:struct.lastName, - fullName:struct.fullName, - pictureUrl:struct.pictureUrl - }) - else data.push(struct); - } + if(struct) data.push(struct); } } if(this.debug) console.log('getUserByIds: user:',user,'input:',userIds,'output',data) @@ -246,20 +190,20 @@ export class StructBackend extends Service { return data; } - deleteUser = async (requestingUserId:string, userId:string, deleteData?:boolean, token?:string) => { + deleteUser = async (requestingUserId:string, userId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoUser(user,userId,deleteData,token); + data = await this.deleteMongoUser(user,userId); } else { data = false; let struct = this.getLocalData(userId); if(struct) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(passed) data = this.deleteLocalData(struct); } } @@ -267,26 +211,25 @@ export class StructBackend extends Service { return data; } - setData = async (requestingUserId:string, structs:any[], notify?:boolean, token?:string) => { + setData = async (requestingUserId:string, structs:any[], notify?:boolean) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.setMongoData(user,structs,notify,token); //input array of structs - + data = await this.setMongoData(user,structs,notify); //input array of structs } else { let non_notes:any[] = []; data = []; await Promise.all(structs.map(async(structId) => { let struct = this.getLocalData(structId); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE'); if(passed) { if(!this.collections[struct.structType]) { - this.collections[struct.structType] = {} + this.collections[struct.structType] = (this.db) ? {instance: this.db.collection(struct.structType)} : {} this.collections[struct.structType].reference = {} } this.setLocalData(struct); @@ -302,13 +245,13 @@ export class StructBackend extends Service { return data; } - getData = async (requestingUserId:string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number, token?:string) => { + getData = async (requestingUserId:string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoData(user, collection, ownerId, dict, limit, skip, token); + data = await this.getMongoData(user, collection, ownerId, dict, limit, skip); } else { data = []; let structs; @@ -318,8 +261,8 @@ export class StructBackend extends Service { if(structs) await Promise.all(structs.map(async(s) => { let struct = this.getLocalData(getStringId(s._id)); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); })); } @@ -327,13 +270,13 @@ export class StructBackend extends Service { return data; } - getDataByIds = async (requestingUserId:string, structIds:string[], ownerId?:string, collection?:string, token?:string) => { + getDataByIds = async (requestingUserId:string, structIds:string[], ownerId?:string, collection?:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoDataByIds(user, structIds, ownerId, collection, token); + data = await this.getMongoDataByIds(user, structIds, ownerId, collection); } else { data = []; let structs; @@ -342,8 +285,8 @@ export class StructBackend extends Service { if(structs)await Promise.all(structs.map(async(s) => { let struct = this.getLocalData(getStringId(s._id)); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); })); } @@ -351,12 +294,13 @@ export class StructBackend extends Service { return data; } - getAllData = async (requestingUserId:string, ownerId:string, excludedCollections?:string[], timeRange?:[number|TimeSpecifier,number|TimeSpecifier], token?:string) => { + getAllData = async (requestingUserId:string, ownerId:string, excludedCollections?:string[]) => { let user = this.users[requestingUserId]; if(!user) return false; + let data; if(this.mode.includes('mongo')) { - data = await this.getAllUserMongoData(user,ownerId,excludedCollections, timeRange, token); + data = await this.getAllUserMongoData(user,ownerId,excludedCollections); } else { let result = this.getLocalData(undefined,{ownerId:ownerId}); data = []; @@ -364,15 +308,15 @@ export class StructBackend extends Service { if(excludedCollections) { if(excludedCollections.indexOf(struct.structType) < 0) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); } } else { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct); if(passed) data.push(struct); } })); @@ -381,20 +325,20 @@ export class StructBackend extends Service { return data; } - deleteData = async (requestingUserId:string, structIds:string[], token?:string) => { + deleteData = async (requestingUserId:string, structIds:string[]) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoData(user,structIds,token); + data = await this.deleteMongoData(user,structIds); } else { data = false; await Promise.all(structIds.map(async (structId) => { let struct = this.getLocalData(structId); let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(passed) this.deleteLocalData(struct); data = true; })); @@ -423,7 +367,7 @@ export class StructBackend extends Service { } else { result.forEach((struct)=>{ - if(Object.keys(struct.users).includes(getStringId(user._id as string|ObjectId))) data.push(struct); + if(Object.keys(struct.users).includes(getStringId(user._id as string|ObjectID))) data.push(struct); }); } } @@ -432,19 +376,19 @@ export class StructBackend extends Service { return data; } - deleteGroup = async (requestingUserId:string, groupId:string, token?:string) => { + deleteGroup = async (requestingUserId:string, groupId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoGroup(user,groupId,token); + data = await this.deleteMongoGroup(user,groupId); } else { let struct = this.getLocalData('group',groupId); let passed = !this.useAuths; if(struct) { - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); } if(passed) { data = true; @@ -454,13 +398,13 @@ export class StructBackend extends Service { return data; } - getAuthorizations = async (requestingUserId:string, ownerId?: string, authId?: string, token?:string) => { + getAuthorizations = async (requestingUserId:string, ownerId?: string, authId?: string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.getMongoAuthorizations(user,ownerId,authId, token); + data = await this.getMongoAuthorizations(user,ownerId,authId); } else { if(authId) { let result = this.getLocalData('authorization',{_id:authId}); @@ -473,21 +417,21 @@ export class StructBackend extends Service { return data; } - deleteAuthorization = async (requestingUserId:string, authId:string, token?:string) => { + deleteAuthorization = async (requestingUserId:string, authId:string) => { let user = this.users[requestingUserId]; if(!user) return false; let data; if(this.mode.includes('mongo')) { - data = await this.deleteMongoAuthorization(user,authId,token); + data = await this.deleteMongoAuthorization(user,authId); } else { data = true; let struct = this.getLocalData('authorization',{_id:authId}); if(struct) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(passed) data = this.deleteLocalData(struct); } } @@ -498,14 +442,8 @@ export class StructBackend extends Service { //------------------------------------ //internalish stuff - - getToken = (user:Partial) => { - return this.useAccessTokens ? this.accessTokens.get(user._id) - : - this.useRefreshTokens ? this.refreshTokens.get(user._id) : undefined - } - notificationStruct = (parentStruct:any= {}) => { + notificationStruct(parentStruct:any= {}) { let structType = 'notification'; let struct = { structType:structType, @@ -515,18 +453,15 @@ export class StructBackend extends Service { alert:false, //can throw an alert if there is an alert flag on the struct ownerId: '', parentUserId: '', - parent: { - structType:parentStruct?.structType, - _id:getStringId(parentStruct?._id) - }, //where it belongs + parent: {structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}, //where it belongs }; return struct; } //when passing structs to be set, check them for if notifications need to be created - //TODO: need to make this more flexible in the cases you DON'T want an update. I.e. a notification filter struct. - checkToNotify = async (user:Partial,structs:any[]=[], mode=this.mode) => { + //TODO: need to make this more flexible in the cases you DON'T want an update + async checkToNotify(user:Partial,structs:any[]=[], mode=this.mode) { //console.log('CHECK TO NOTIFY', structs) if(structs.length === 0) return false; if(typeof user === 'string') { @@ -542,9 +477,9 @@ export class StructBackend extends Service { let newNotifications :any[] = []; structs.forEach(async (struct)=>{ if(struct?._id) { - if (struct.ownerId && user?._id !== struct.ownerId) { //a struct you own being updated by another user + if (user?._id !== struct.ownerId) { //a struct you own being updated by another user let newNotification = this.notificationStruct(struct); - newNotification._id = 'notification_'+getStringId(struct._id)+'_'+struct.ownerId; //overwrites notifications for the same parent + newNotification._id = 'notification_'+getStringId(struct._id); //overwrites notifications for the same parent newNotification.ownerId = struct.ownerId; newNotification.note = struct.structType; //redundant now newNotification.parentUserId = struct.ownerId; @@ -557,7 +492,7 @@ export class StructBackend extends Service { Object.keys(struct.users).forEach((usr)=>{ if(usr !== user._id as string) { let newNotification = this.notificationStruct(struct); - newNotification._id = 'notification_'+getStringId(struct._id)+'_'+usr; //overwrites notifications for the same parent + newNotification._id = 'notification_'+getStringId(struct._id); //overwrites notifications for the same parent newNotification.ownerId = usr; newNotification.note = struct.structType; if(struct.alert) newNotification.alert = struct.alert; @@ -571,9 +506,8 @@ export class StructBackend extends Service { let auths :any[] = []; if(mode.includes('mongo')) { let s = this.collections.authorization.instance.find({ $or:[{authorizedId: user._id as string},{authorizerId: user._id as string}] }); - let arr = await s.toArray(); - if(arr.length > 0) { - arr.forEach(d => auths.push(d)); + if(await s.count() > 0) { + await s.forEach(d => auths.push(d)); } } else { auths = this.getLocalData('authorization',{authorizedId:user._id as string}); @@ -585,7 +519,7 @@ export class StructBackend extends Service { if(auth.status === 'OKAY' && auth.authorizations['peer']) { let newNotification = this.notificationStruct(struct); newNotification.ownerId = auth.authorizedId; - newNotification._id = 'notification_'+getStringId(struct._id)+'_'+auth.authorizedId; //overwrites notifications for the same parent + newNotification._id = 'notification_'+getStringId(struct._id); //overwrites notifications for the same parent newNotification.note = struct.structType; newNotification.parentUserId = struct.ownerId; if(struct.alert) newNotification.alert = struct.alert; @@ -603,14 +537,13 @@ export class StructBackend extends Service { //console.log('NEW NOTIFICATIONS', newNotifications) if(newNotifications.length > 0) { if(mode.includes('mongo')){ - //console.log('new notes', newNotifications); - await this.setMongoData(user, newNotifications, true, this.getToken(user)); //set the DB, let the user get them + await this.setMongoData(user, newNotifications); //set the DB, let the user get them } else { this.setLocalData(newNotifications); } // console.log(usersToNotify); for(const uid in usersToNotify) { - this.users[uid]?.sendAll({route:'structNotification',args:true}); //notify on all available connections for a user (e.g. phone + laptop) + this.users[uid].send({route:'structNotification',args:true}); } return true; @@ -618,50 +551,50 @@ export class StructBackend extends Service { } //general mongodb query - queryMongo = async (user:Partial,collection:string, queryObj:any={}, findOne:boolean=false, skip:number=0, token?:string) => { + async queryMongo(user:Partial,collection:string, queryObj:any={}, findOne:boolean=false, skip:number=0) { if(!collection && !queryObj) return undefined; else if(findOne){ - let res = await this.db.collection(collection).findOne(queryObj); + let res = this.db.collection(collection).findOne(queryObj); if(!res) return undefined; let passed = !this.useAuths; if(!res?.ownerId) { //return anyway if not matching our struct format passed = true; } else if((getStringId(user._id as string) !== res.ownerId || (getStringId(user._id as string) === res.ownerId && (user.userRoles as any)?.admincontrol))) { - if(this.useAuths) passed = await this.checkAuthorization(user,res,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,res); } if(passed) return res; else return undefined; } else { - let res = this.db.collection(collection).find(queryObj).sort({ $natural: -1 }).skip(skip); + let res = await this.db.collection(collection).find(queryObj).sort({ $natural: -1 }).skip(skip); let structs :any[] = []; - let arr = await res.toArray(); - if(arr.length > 0) { + if(await res.count() > 0) { let passed = !this.useAuths; let checkedAuth = ''; - for(const s of arr){ + await res.forEach(async (s) => { if(!s?.ownerId) { //return anyway if not matching our struct format passed = true; } else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed) structs.push(s); - } + }) } return structs; } } //structs can be Struct objects or they can be an array with a secondary option e.g. [Struct,{$push:{x:[1,2,3]}}] - setMongoData = async (user:Partial,structs:any[] = [], notify=true, token?:string) => { + async setMongoData(user:Partial,structs:any[] = [], notify=true) { - //console.log(user,structs); + //console.log(structs,user); let firstwrite = false; + //console.log(structs); if(structs.length > 0) { let passed = !this.useAuths; let checkedAuth = ''; @@ -671,37 +604,33 @@ export class StructBackend extends Service { secondary = struct[1]; struct = struct[0]; } - - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; //if no owner, it's public + if(!struct?.ownerId) passed = true; //if no owner, it's public else if((getStringId(user._id as string) !== struct.ownerId || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== struct.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); checkedAuth = struct.ownerId; } if(passed) { if(struct.structType) { if(!this.collections[struct.structType]) { - this.collections[struct.structType] = {} + this.collections[struct.structType] = (this.db) ? {instance: this.db.collection(struct.structType)} : {} this.collections[struct.structType].reference = {} } let copy = JSON.parse(JSON.stringify(struct)); if(copy._id) delete copy._id; //if(copy._id && copy.structType !== 'profile' && copy.structType !== 'notification') - //else copy._id = toObjectId(struct._id); + //else copy._id = toObjectID(struct._id); //if(struct.structType === 'notification') console.log(struct); if (struct._id) { if(getStringId(struct._id).includes('defaultId')) { - await this.db.collection(struct.structType ? struct.structType : 'data').insertOne(copy); + await this.db.collection(struct.structType).insertOne(copy); firstwrite = true; } - else if (struct.structType === 'notification') - await this.db.collection(struct.structType ? struct.structType : 'data').updateOne( - {_id:struct._id}, {$set: copy, ...secondary}, {upsert: true, unique: false} - ); - else await this.db.collection(struct.structType ? struct.structType : 'data').updateOne({_id: toObjectId(struct._id)}, {$set: copy, ...secondary}, {upsert: true}); + else if (struct.structType === 'notification') await this.db.collection(struct.structType).updateOne({parent: struct.parent, _id:struct._id}, {$set: copy, ...secondary}, {upsert: true, unique: false}); + else await this.db.collection(struct.structType).updateOne({_id: toObjectID(struct._id)}, {$set: copy, ...secondary}, {upsert: true}); } else if(struct.structType) { - this.db.collection(struct.structType ? struct.structType : 'data').insertOne(copy); + this.db.collection(struct.structType).insertOne(copy); } } } @@ -739,7 +668,7 @@ export class StructBackend extends Service { let pulledReply; await Promise.all(['discussion','chatroom','comment'].map(async (name) => { - let found = await this.db.collection(name).findOne({_id:toObjectId(replyToId)}); + let found = await this.db.collection(name).findOne({_id:toObjectID(replyToId)}); if(found) pulledReply = found; })); //console.log(pulledReply) @@ -777,7 +706,7 @@ export class StructBackend extends Service { await Promise.all(toUpdate.map(async(s)=>{ let copy = JSON.parse(JSON.stringify(s)); delete copy._id; - await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set: copy},{upsert: false}); + await this.db.collection(s.structType).updateOne({_id:toObjectID(s._id)},{$set: copy},{upsert: false}); })); // console.log('pulled comment',pulledComment) @@ -799,7 +728,6 @@ export class StructBackend extends Service { })); //console.log('toReturn: ',toReturn) if(notify) this.checkToNotify(user,toReturn); - //console.log(toReturn); return toReturn; } else { @@ -814,38 +742,29 @@ export class StructBackend extends Service { else return false; } - setMongoUser = async (user:Partial,struct:Partial, token?:string) => { + async setMongoUser(user:Partial,struct:Partial) { if(struct._id) { //this has a second id that matches the token id - const _id = toObjectId(struct._id); - let usersearch = {_id}; + const _id = toObjectID(struct._id); + let usersearch = (_id !== struct._id) ? { _id } : {id: struct.id}; let userexists = await this.collections.profile.instance.findOne(usersearch); if(userexists) { - if( - getStringId(user._id as string) !== struct.ownerId || - (getStringId(user._id as string) === struct.ownerId && - (user.userRoles as any)?.admincontrol) - ) { + if(getStringId(user._id as string) !== struct.ownerId || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) - passed = true; - else if(this.useAuths) - passed = await this.checkAuthorization(user,struct,'WRITE',token); - if(!passed) - return false; + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); + if(!passed) return false; } } let copy = JSON.parse(JSON.stringify(struct)); - copy._id = _id; if(this.debug) console.log('RETURNS PROFILE', struct) // Only Set _id if Appropriate - await this.collections.profile.instance.updateOne( - usersearch, {$set: copy}, {upsert: true}); + await this.collections.profile.instance.updateOne(usersearch, {$set: copy}, {upsert: true}); user = await this.collections.profile.instance.findOne(usersearch); this.checkToNotify(user, [struct]); @@ -853,23 +772,20 @@ export class StructBackend extends Service { } else return false; } - setGroup = async (user:Partial,struct:any, mode=this.mode, token?:string) => { + async setGroup(user:Partial,struct:any, mode=this.mode) { if(struct?._id) { - - let uid = getStringId(user._id as string); - let exists:any = undefined; if(mode.includes('mongo')) { exists = await this.collections.group.instance.findOne({name:struct.name}); } else { exists = this.getLocalData('group',{_id:getStringId(struct._id)}); } - if(exists && (exists.ownerId !== struct.ownerId || struct.admins.indexOf(uid) < 0) ) return false; //BOUNCE + if(exists && (exists.ownerId !== struct.ownerId || struct.admins.indexOf(getStringId(user._id as string)) < 0) ) return false; //BOUNCE - if(uid !== struct.ownerId) { + if(getStringId(user._id as string) !== struct.ownerId) { let passed = !this.useAuths; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE',token); + if(!struct?.ownerId) passed = true; + else if(this.useAuths) passed = await this.checkAuthorization(user,struct,'WRITE'); if(!passed) return false; } @@ -883,11 +799,10 @@ export class StructBackend extends Service { let ids = {}; if(mode.includes('mongo')) { let cursor = this.collections.profile.instance.find({ $or: allusers }); //encryption references - let arr = cursor.toArray(); - if(arr.length > 0) { - arr.forEach((user) => { - users[uid] = user; - ids[uid] = true; + if( await cursor.count() > 0) { + await cursor.forEach((user) => { + users[getStringId(user._id as string)] = user; + ids[getStringId(user._id as string)] = true; }); } } else { @@ -928,12 +843,12 @@ export class StructBackend extends Service { //console.log(struct) if(mode.includes('mongo')){ if(getStringId(struct._id).includes('defaultId')) { - await this.db.collection(struct.structType ? struct.structType : 'data').insertOne(copy); + await this.db.collection(struct.structType).insertOne(copy); delete struct._id; - struct = await this.db.collection(struct.structType ? struct.structType : 'data').findOne(struct); + struct = await this.db.collection(struct.structType).findOne(struct); struct._id = getStringId(struct._id); } - else await this.collections.group.instance.updateOne({ _id: toObjectId(struct._id) }, {$set: copy}, {upsert: true}); + else await this.collections.group.instance.updateOne({ _id: toObjectID(struct._id) }, {$set: copy}, {upsert: true}); } else { this.setLocalData(struct); } @@ -944,174 +859,56 @@ export class StructBackend extends Service { } else return false; } - getMongoUser = ( - user:Partial, - info='', - requireAuth=true, - basicInfo=false, - token?:string - ):Promise<{}|{user:ProfileStruct,authorizations:AuthorizationStruct[], groups:GroupStruct[]|{user:ProfileStruct}}> => { + // + async getMongoUser(user:Partial,info='', bypassAuth=false):Promise<{}|{user:ProfileStruct,authorizations:AuthorizationStruct[], groups:GroupStruct[]|{user:ProfileStruct}}> { return new Promise(async resolve => { const query:any[] = [{email: info},{id: info},{username:info}] - //console.log('creating query with', info); - try {query.push({_id: toObjectId(info)})} catch (e) {console.log('error creating ObjectId with ', info);} + try {query.push({_id: toObjectID(info)})} catch (e) {} let u = await this.collections.profile.instance.findOne({$or: query}); //encryption references - if(!u || u == null) resolve(undefined); + if(!u || u == null) resolve({}); else { - u._id = getStringId(u._id); + u._id = getStringId(u._id) if (!u.ownerId) u.ownerId = u._id - if(basicInfo) { - - if(this.useAccessTokens || this.useRefreshTokens) { - if(this.getToken(user) !== token) //not authorized without a current token - resolve( undefined as any); - } - - let stripped = { - username:u.username, - firstName:u.firstName, - lastName:u.lastName, - fullName:u.fullName, - pictureUrl:u.pictureUrl, - _id:u._id - } - - u = stripped; - - resolve({user:u}); - } else if (requireAuth){ + if (u && bypassAuth === false){ if(getStringId(user._id as string) !== u._id || (getStringId(user._id as string) === u._id && (user.userRoles as any)?.admincontrol)) { // TODO: Ensure that passed users will always have the same ObjectId (not necessarily id...) let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,u,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,u); if(!passed) resolve(undefined as any); } // console.log(u); let authorizations :any[] = []; let auths = this.collections.authorization.instance.find({ownerId:u._id}); - let aarr = await auths.toArray(); - if(auths.toArray().length > 0) { - aarr.forEach(d => authorizations.push(d)); + if((await auths.count() > 0)) { + await auths.forEach(d => authorizations.push(d)); } let gs = this.collections.group.instance.find({users:{$all:[u._id]}}); - let arr = await gs.toArray(); let groups :any[] = []; - if((arr.length > 0)) { - arr.forEach(d => groups.push(d)); + if((await gs.count() > 0)) { + await gs.forEach(d => groups.push(d)); } resolve({user:u, authorizations, groups}); - } else { - if(this.useAccessTokens || this.useRefreshTokens) { - if(this.getToken(user) !== token) //not authorized without a current token - resolve( undefined as any); - } - resolve({user:u}); - } - } - }); - } - - //safely query basic identifying information - queryUsers = ( - user:Partial, - info='', - limit=0, - skip=0, - requireAuth=false, - token?:string - ):Promise<{}|{user:ProfileStruct,authorizations:AuthorizationStruct[], groups:GroupStruct[]|{user:ProfileStruct}}> => { - if(typeof user === 'string') user = this.users[user]; - if(!user) return; - return new Promise(async resolve => { - let q = { $regex: `^${info}`, $options: 'i'}; - const query:any[] = [{email: q},{username:q},{firstName:q},{lastName:q},{name:q}] - - let arr; - - if(this.mode.includes('mongo')) { - let users = this.collections.profile.instance.find({$or: query}, {projection:shallowqueryDummy}).skip(skip); //encryption references - if(limit > 0) users.limit(limit); - await users; - - arr = await users.toArray(); - } else { - arr = [] as any; - for(let i = 0; i < query.length; i++) { - let dat = this.getLocalData('profile',query[i]); - if(Array.isArray(dat)) { - dat.forEach((u) => { - arr.push({ - firstName:u.firstName, - lastName:u.lastName, - fullName:u.fullName, - username:u.username, - pictureUrl:u.pictureUrl - }); - }) - } - else if(dat) arr.push({ - firstName:dat.firstName, - lastName:dat.lastName, - fullName:dat.fullName, - username:dat.username, - pictureUrl:dat.pictureUrl - }); - } - } - - if(requireAuth) { - let result = []; - let strid = getStringId(user._id as string); - for(let i = 0; i < arr.length; i++) { - let u = arr[i]; - u._id = getStringId(u._id); //converts to string - if(strid !== u._id || (strid === u._id && (user.userRoles as any)?.admincontrol)) { - let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,u,'READ',token); - if(passed) result.push(u); - } - } - arr = result; - } else if(this.useAccessTokens || this.useRefreshTokens) { - let tk = this.getToken(user); - if(!tk || tk !== token) //not authorized without a current token - { resolve(false); return; } + } else resolve({user:u}); } - - resolve(arr); - }); } - - getMongoUsersByIds = async (user:Partial, userIds:any[]=[], basicInfo?:boolean) => { + //safely returns the profile id, username, and email and other basic info based on the user role set applied + async getMongoUsersByIds(user:Partial,userIds:any[]=[]) { let usrs :any[] = []; userIds.forEach((u) => { - try {usrs.push({_id:toObjectId(u)});} catch {} + try {usrs.push({_id:toObjectID(u)});} catch {} }); - let found :any[] = []; if (usrs.length > 0){ let users = this.collections.profile.instance.find({$or:usrs}); - let arr = await users.toArray(); - //console.log(arr); - if(arr.length > 0) { - arr.forEach((u) => { - if(basicInfo) { - found.push({ - username:u.username, - firstName:u.firstName, - lastName:u.lastName, - fullName:u.fullName, - pictureUrl:u.pictureUrl, - _id:u._id - }) - } - else found.push(u); + if(await users.count() > 0) { + await users.forEach((u) => { + found.push(u); }); } } @@ -1119,28 +916,26 @@ export class StructBackend extends Service { return found as ProfileStruct[]; } - getMongoUsersByRole = async (user:Partial,role:string) => { + //safely returns the profile id, username, and email and other basic info based on the user role set applied + async getMongoUsersByRole(user:Partial,role:string) { let users = this.collections.profile.instance.find({ userRoles:{$all: {[role]:true}} }); let found :any[] = []; - let arr = await users.toArray(); - if(arr.length > 0) { - arr.forEach((u) => { + if(await users.count() > 0) { + await users.forEach((u) => { found.push(u); }); } return found as ProfileStruct[]; } - getMongoDataByIds = async (user:Partial, structIds:string[], ownerId:string|undefined, collection:string|undefined, token?:string) => { - - let uid = getStringId(user._id as string); + async getMongoDataByIds(user:Partial, structIds:string[], ownerId:string|undefined, collection:string|undefined) { if(structIds.length > 0) { let query :any[] = []; structIds.forEach( (_id)=>{ - let q = {_id:toObjectId(_id)}; + let q = {_id:toObjectID(_id)}; if(ownerId) (q as any).ownerId = ownerId; query.push(q); }) @@ -1148,32 +943,30 @@ export class StructBackend extends Service { if(!collection) { await Promise.all(Object.keys(this.collections).map(async (name) => { let cursor = await this.db.collection(name).find({$or:query}); - let arr = await cursor.toArray(); - if(arr.length > 0) { + + if(await cursor.count() > 0) { let passed = true; let checkedAuth = ''; - for(let i = 0; i < arr.length; i++) { - let s = arr[i]; + await cursor.forEach(async (s) => { if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed) found.push(s); - } + }) } })); } else { let cursor = await this.db.collection(collection).find({$or:query}); - let arr = await cursor.toArray(); - if(arr.length > 0) { + if(await cursor.count() > 0) { let passed = true; let checkedAuth = ''; - arr.forEach(async (s) => { + await cursor.forEach(async (s) => { if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed) found.push(s); @@ -1186,89 +979,65 @@ export class StructBackend extends Service { } //get all data for an associated user, can add a search string - getMongoData = async (user:Partial, collection:string|undefined, ownerId:string|undefined, dict:any|undefined={}, limit=0, skip=0, token?:string) => { + async getMongoData(user:Partial, collection:string|undefined, ownerId:string|undefined, dict:any|undefined={}, limit=0, skip=0) { if (!ownerId) ownerId = dict?.ownerId // TODO: Ensure that replacing ownerId, key, value with dict was successful if(!dict) dict = {}; - if (dict._id) dict._id = toObjectId(dict._id) - - let uid = getStringId(user._id as string); + if (dict._id) dict._id = toObjectID(dict._id) let structs :any[] = []; let passed = true; let checkedAuth = ''; - - let cursor; - if(!collection && !ownerId && !dict) return []; else if(!collection && ownerId && Object.keys(dict).length === 0) return await this.getAllUserMongoData(user,ownerId); else if((!dict || Object.keys(dict).length === 0) && ownerId && collection) { - cursor = this.db.collection(collection).find({ownerId}).sort({ $natural: -1 }).skip(skip); - } else if (collection && Object.keys(dict).length > 0) { - if(ownerId) dict.ownerId = ownerId; - cursor = await this.db.collection(collection).find(dict).sort({ $natural: -1 }).skip(skip); - } - - if(cursor) { + let cursor = this.db.collection(collection).find({ownerId}).sort({ $natural: -1 }).skip(skip); if(limit > 0) cursor.limit(limit); - let arr = await cursor.toArray(); - if(arr.length > 0) { - for(let i = 0; i < arr.length; i++) { - let s = arr[i]; + if(await cursor.count() > 0) { + await cursor.forEach(async (s) => { if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); + else if((getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,s); checkedAuth = s.ownerId; } if(passed === true) structs.push(s); - } + }); } - } else if (!collection && Object.keys(dict).length > 0 && !ownerId) { //need to search all collections in this case + } else if (Object.keys(dict).length > 0 && ownerId) { + let found = await this.db.collection(collection).findOne({ownerId:ownerId,...dict}); + if(found) structs.push(found); + } else if (Object.keys(dict).length > 0 && !ownerId) { //need to search all collections in this case await Promise.all(Object.keys(this.collections).map(async (name) => { - cursor = await this.db.collection(name).find(dict).sort({ $natural: -1 }).skip(skip);; - if(cursor) { - if(limit > 0) cursor.limit(limit); - let arr = await cursor.toArray(); - if(arr.length > 0) { - for(let i = 0; i < arr.length; i++) { - let s = arr[i]; - if(!s?.ownerId) passed = true; - else if((uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== s.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,s,'READ',token); - checkedAuth = s.ownerId; - } - if(passed === true) structs.push(s); - } + let found = await this.db.collection(name).findOne(dict); + if(found) { + if(!found?.ownerId) passed = true; + else if((getStringId(user._id as string) !== found.ownerId || (getStringId(user._id as string) === found.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== found.ownerId) { + if(this.useAuths) passed = await this.checkAuthorization(user,found); + checkedAuth = found.ownerId; } + structs.push(found); + return } })); } - //console.log('\n\n\n getData passed:',passed, '\n\n\n res:', JSON.stringify(structs), '\n\nargs', collection, ownerId, JSON.stringify(dict)); - if(!passed) return []; //need to make this better + if(!passed) return []; return structs; } - getAllUserMongoData = async (user:Partial, ownerId, excluded:any[]=[], timeRange?:[number|TimeSpecifier,number|TimeSpecifier], token?:string) => { + async getAllUserMongoData(user:Partial,ownerId,excluded:any[]=[]) { let structs :any[] = []; let passed = true; let checkedId = ''; await Promise.all(Object.keys(this.collections).map(async (name,j) => { if(passed && excluded.indexOf(name) < 0) { - let query = {ownerId:ownerId} as any; - if(timeRange) { - if(typeof timeRange[0] === 'string') timeRange[0] = genTimestampFromString(timeRange[0]); - if(typeof timeRange[1] === 'string') timeRange[1] = genTimestampFromString(timeRange[1]); - query.timestamp = {$gt:timeRange[0],$lt:timeRange[1]}; - } - let cursor = this.db.collection(name).find(query); - let arr = await cursor.toArray(); - let count = arr.length; + let cursor = this.db.collection(name).find({ownerId:ownerId}); + let count = await cursor.count(); for(let k = 0; k < count; k++) { - let struct = arr[k]; + let struct = await cursor.next(); if(!ownerId) passed = true; else if((getStringId(user._id as string) !== ownerId || (getStringId(user._id as string) === ownerId && (user.userRoles as any)?.admincontrol)) && checkedId !== ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,struct); //console.log(passed) checkedId = ownerId; } @@ -1286,19 +1055,19 @@ export class StructBackend extends Service { } //passing in structrefs to define the collection (structType) and id - getMongoDataByRefs = async (user:Partial,structRefs:any[]=[], token?:string) => { + async getMongoDataByRefs(user:Partial,structRefs:any[]=[]) { let structs :any[] = []; //structRef = {structType, id} if(structs.length > 0) { let checkedAuth = ''; structRefs.forEach(async (ref)=>{ if(ref.structType && getStringId(ref._id)) { - let struct = await this.db.collection(ref.structType).findOne({_id: toObjectId(ref._id)}); + let struct = await this.db.collection(ref.structType).findOne({_id: toObjectID(ref._id)}); if(struct) { let passed = true; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; + if(!struct?.ownerId) passed = true; else if((getStringId(user._id as string) !== struct.ownerId || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) && checkedAuth !== struct.ownerId) { - if(this.useAuths) passed = await this.checkAuthorization(user,struct,'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,struct); checkedAuth = struct.ownerId; } if(passed === true) { @@ -1311,62 +1080,60 @@ export class StructBackend extends Service { return structs; } - getMongoAuthorizations = async (user:Partial,ownerId=getStringId(user._id as string), authId='', token?:string) => { + async getMongoAuthorizations(user:Partial,ownerId=getStringId(user._id as string), authId='') { let auths :any[] = []; //console.log(user); if(authId.length === 0 ) { let cursor = this.collections.authorization.instance.find({ownerId:ownerId}); - let arr = await cursor.toArray(); - if(arr.length > 0) { - arr.forEach((a) => { + if(await cursor.count > 0) { + await cursor.forEach((a) => { auths.push(a) }); } } - else auths.push(await this.collections.authorization.instance.findOne({_id: toObjectId(authId), ownerId:ownerId})); + else auths.push(await this.collections.authorization.instance.findOne({_id: toObjectID(authId), ownerId:ownerId})); if(!auths[0]?.ownerId) true; else if(getStringId(user._id as string) !== auths[0]?.ownerId) { let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,auths[0],'READ',token); + if(this.useAuths) passed = await this.checkAuthorization(user,auths[0]); if(!passed) return undefined; } return auths as AuthorizationStruct[]; } - getMongoGroups = async (user:Partial, userId=getStringId(user._id as string), groupId='') => { + async getMongoGroups(user:Partial, userId=getStringId(user._id as string), groupId='') { let groups :any[] = []; if(groupId.length === 0 ) { let cursor = this.collections.group.instance.find({users:{$all:[userId]}}); - let arr = await cursor.toArray(); - if(arr.length > 0) { - arr.forEach((a) => { + if(await cursor.count > 0) { + await cursor.forEach((a) => { groups.push(a) }); } } else { - try {groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId), users:{$all:[userId]}}));} catch {} + try {groups.push(await this.collections.group.instance.findOne({_id:toObjectID(groupId), users:{$all:[userId]}}));} catch {} } return groups as GroupStruct[]; } //general delete function - deleteMongoData = async (user:Partial,structRefs:any[]=[], token?:string) => { + async deleteMongoData(user:Partial,structRefs:any[]=[]) { // let ids :any[] = []; let structs :any[] = []; await Promise.all(structRefs.map(async (ref) => { try { - let _id = toObjectId(ref._id) + let _id = toObjectID(ref._id) let struct = await this.db.collection(ref.structType).findOne({_id}); if(struct) { structs.push(struct); let notifications = await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}}); - let count = notifications.toArray().length; + let count = await notifications.count(); for(let i = 0; i < count; i++) { let note = await notifications.next(); if(note) structs.push(note); //remove any associated notifications with a piece of data @@ -1379,23 +1146,22 @@ export class StructBackend extends Service { let checkedOwner = ''; await Promise.all(structs.map(async (struct,i)=>{ let passed = true; - if(!struct?.ownerId || struct.ownerId === user._id) passed = true; + if(!struct?.ownerId) passed = true; else if((struct.ownerId !== getStringId(user._id as string) || (getStringId(user._id as string) === struct.ownerId && (user.userRoles as any)?.admincontrol)) && struct.ownerId !== checkedOwner) { checkedOwner = struct.ownerId; - if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user, struct,'WRITE'); } if(passed) { //console.log(passed); - await this.db.collection(struct.structType ? struct.structType : 'data').deleteOne({_id:toObjectId(struct._id)}); + await this.db.collection(struct.structType).deleteOne({_id:toObjectID(struct._id)}); //delete any associated notifications, too if(struct.users) { Object.keys(struct.users).forEach((uid)=> { - if(uid !== getStringId(user._id as string) && uid !== struct.ownerId && this.users[uid]) - this.users[uid]?.sendAll({route:'structDeleted',args:{_id:getStringId(struct._id),structType:struct.structType}}) + if(uid !== getStringId(user._id as string) && uid !== struct.ownerId && this.users[uid]) this.users[uid].send({route:'structDeleted',args:getStringId(struct._id)}) }); } if(struct.ownerId !== user._id as string && this.users[struct.ownerId]) { - this.users[struct.ownerId]?.sendAll({route:'structDeleted',args:{_id:getStringId(struct._id),structType:struct.structType}}) + this.users[struct.ownerId].send({route:'structDeleted',args:getStringId(struct._id)}) } } })); @@ -1404,83 +1170,63 @@ export class StructBackend extends Service { } //specific delete functions (the above works for everything) - deleteMongoUser = async (user:Partial, userId, deleteData?:boolean, token?:string) => { + async deleteMongoUser(user:Partial,userId) { if(getStringId(user._id as string) !== userId || (getStringId(user._id as string) === userId && (user.userRoles as any)?.admincontrol)) { let u = await this.collections.profile.instance.findOne({ id: userId }); let passed = !this.useAuths; if(!u?.ownerId) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,u,'WRITE',token); + else if(this.useAuths) passed = await this.checkAuthorization(user,u,'WRITE'); if(!passed) return false; } await this.collections.profile.instance.deleteOne({ id: userId }); - if(deleteData) { - for(const key in this.collections) { - this.collections[key].instance.deleteMany({ ownerId: userId }); - this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}}); - } - } - - if(getStringId(user._id as string) !== userId && this.users[userId]) this.users[userId]?.sendAll({route:'structDeleted',args:{_id:userId,structType:'profile'}}); + if(getStringId(user._id as string) !== userId && this.users[userId]) this.users[userId].send({route:'structDeleted',args:userId}); //now delete their authorizations and data too (optional?) return true; } - deleteMongoGroup = async (user:Partial,groupId, token?:string) => { - let s = await this.collections.group.instance.findOne({ _id: toObjectId(groupId) }); + async deleteMongoGroup(user:Partial,groupId) { + let s = await this.collections.group.instance.findOne({ _id: toObjectID(groupId) }); if(s) { if(!s?.ownerId) true; else if(getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol) ) { let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE'); if(!passed) return false; } if(s.users) { - Object.keys(s.users).forEach((u) => { - this.users[u]?.sendAll({route:'structDeleted',args:{_id:getStringId(s._id), structType:s.structType}}); - }); + Object.keys(s.users).forEach((u) => { this.users[s.authorizerId].send({route:'structDeleted',args:getStringId(s._id)}); }); } - await this.collections.group.instance.deleteOne({ _id:toObjectId(groupId) }); + await this.collections.group.instance.deleteOne({ _id:toObjectID(groupId) }); return true; } else return false; } - deleteMongoAuthorization = async (user:Partial, authId, token?:string) => { - let s = await this.collections.authorization.instance.findOne({ _id: toObjectId(authId) }); - let uid = getStringId(user._id as string); + async deleteMongoAuthorization(user:Partial,authId) { + let s = await this.collections.authorization.instance.findOne({ _id: toObjectID(authId) }); if(s) { - if(uid !== s.ownerId || (uid === s.ownerId && (user.userRoles as any)?.admincontrol)) { + if(getStringId(user._id as string) !== s.ownerId || (getStringId(user._id as string) === s.ownerId && (user.userRoles as any)?.admincontrol)) { let passed = !this.useAuths; if(!s?.ownerId) passed = true; - else if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE',token); + else if(this.useAuths) passed = await this.checkAuthorization(user,s,'WRITE'); if(!passed) return false; } - if(s.associatedAuthId) { //belonging to the other user + if(s.associatedAuthId) { if(this.debug) console.log(s); - - await this.collections.authorization.instance.deleteOne({ _id: toObjectId(s.associatedAuthId) }); //remove the other auth too - - if(s.authorizerId !== uid) this.users[s.authorizerId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s.associatedAuthId), structType:s.structType}}); - else if (s.authorizedId !== uid) this.users[s.authorizedId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s.associatedAuthId), structType:s.structType}}); + await this.collections.authorization.instance.deleteOne({ _id: toObjectID(s.associatedAuthId) }); //remove the other auth too + if(s.authorizerId && s.authorizerId !== getStringId(user._id as string)) this.users[s.authorizerId].send({route:'structDeleted',args:getStringId(s._id)}); + else if (s.authorizedId && s.authorizedId !== getStringId(user._id as string)) this.users[s.authorizerId].send({route:'structDeleted',args:getStringId(s._id)}); } - await this.collections.authorization.instance.deleteOne({ _id: toObjectId(authId) }); - - if(s.authorizerId === uid) this.users[s.authorizerId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s._id), structType:s.structType}}); - else if (s.authorizedId === uid) this.users[s.authorizedId]?.sendAll({route:'structDeleted',args:{_id:getStringId(s._id), structType:s.structType}}); - + await this.collections.authorization.instance.deleteOne({ _id: toObjectID(authId) }); return true; } else return false; } - setAuthorization = async ( - user:Partial, - authStruct, - token?:string - ) => { + async setAuthorization(user:Partial, authStruct, mode=this.mode) { //check against authorization db to allow or deny client/professional requests. //i.e. we need to preauthorize people to use stuff and allow each other to view sensitive data to cover our asses @@ -1501,15 +1247,12 @@ export class StructBackend extends Service { */ let u1, u2; - - let mmode = this.mode.includes('mongo'); - - if(mmode) { - u1 = (await this.getMongoUser(user, authStruct.authorizedId, false) as any).user; //can authorize via email, id, or username - u2 = (await this.getMongoUser(user, authStruct.authorizerId, false) as any).user; + if(mode.includes('mongo')) { + u1 = (await this.getMongoUser(user, authStruct.authorizedId, true) as any).user; //can authorize via email, id, or username + u2 = (await this.getMongoUser(user, authStruct.authorizerId, true) as any).user; } else { - u1 = this.getLocalData('profile',{'_id':authStruct.authorizedId})?.[0]; - u2 = this.getLocalData('profile',{'_id':authStruct.authorizerId})?.[0]; + u1 = this.getLocalData('profile',{'_id':authStruct.authorizedId})[0]; + u2 = this.getLocalData('profile',{'_id':authStruct.authorizerId})[0]; } //console.log(u1,u2) @@ -1520,43 +1263,31 @@ export class StructBackend extends Service { if(authStruct.authorizerId !== getStringId(u2._id)) authStruct.authorizerId = getStringId(u2._id); if(!authStruct.authorizedName) { - if(u1.name) authStruct.authorizedName = u1.name; - else if(u1.username) authStruct.authorizedName = u1.username; + if(u1.username) authStruct.authorizedName = u1.username; else if (u1.email) authStruct.authorizedName = u1.email; } if(!authStruct.authorizerName) { - if(u1.name) authStruct.authorizedName = u1.name; - else if(u2.username) authStruct.authorizerName = u2.username; + if(u2.username) authStruct.authorizerName = u2.username; else if (u2.email) authStruct.authorizerName = u2.email; } //console.log(authStruct); if(!authStruct?.ownerId) true; - else if( - (getStringId(user._id as string) !== authStruct.ownerId || ( - getStringId(user._id as string) === authStruct.ownerId && - (user.userRoles as any)?.admincontrol) - ) && - ( - getStringId(user._id as string) !== authStruct.authorizedId && - getStringId(user._id as string) !== authStruct.authorizerId - ) - ) { + else if((getStringId(user._id as string) !== authStruct.ownerId || (getStringId(user._id as string) === authStruct.ownerId && (user.userRoles as any)?.admincontrol)) && (getStringId(user._id as string) !== authStruct.authorizedId && getStringId(user._id as string) !== authStruct.authorizerId)) { let passed = !this.useAuths; - if(this.useAuths) passed = await this.checkAuthorization(user,authStruct,'WRITE',token); + if(this.useAuths) passed = await this.checkAuthorization(user,authStruct,'WRITE'); if(!passed) return false; } let auths :any[] = []; - if(mmode){ - let s = await this.collections.authorization.instance.find( + if(mode.includes('mongo')){ + let s = this.collections.authorization.instance.find( { $and: [ { authorizedId: authStruct.authorizedId }, { authorizerId: authStruct.authorizerId } ] } ); - let arr = await s.toArray(); - if (arr.length > 0) { - arr.forEach(d => auths.push(d)); + if ((await s.count()) > 0) { + await s.forEach(d => auths.push(d)); } } else { let s = this.getLocalData('authorization',{authorizedId:authStruct.authorizedId}); @@ -1569,8 +1300,7 @@ export class StructBackend extends Service { let otherAuthset; if(Array.isArray(auths)) { - for(let i = 0; i < auths.length; i++) { - const auth = auths[i]; + auths.forEach(async (auth) => { if(auth.ownerId === getStringId(user._id as string)) { //got your own auth //do nothing, just update your struct on the server if the other isn't found } else { //got the other associated user's auth, now can compare and verify @@ -1595,53 +1325,36 @@ export class StructBackend extends Service { auth.associatedAuthId = getStringId(authStruct._id); otherAuthset = auth; let copy = JSON.parse(JSON.stringify(auth)); - if(mmode) { + if(mode.includes('mongo')) { delete copy._id; - await this.collections.authorization.instance.updateOne( - { $and: [ - { authorizedId: authStruct.authorizedId }, - { authorizerId: authStruct.authorizerId }, - { ownerId: auth.ownerId } ] - }, {$set: copy}, {upsert: true}); + await this.collections.authorization.instance.updateOne({ $and: [ { authorizedId: authStruct.authorizedId }, { authorizerId: authStruct.authorizerId }, { ownerId: auth.ownerId } ] }, {$set: copy}, {upsert: true}); } else { this.setLocalData(copy); } } - } + }); } let copy = JSON.parse(JSON.stringify(authStruct)); - if(mmode) { + if(mode.includes('mongo')) { delete copy._id; await this.collections.authorization.instance.updateOne({ $and: [ { authorizedId: authStruct.authorizedId }, { authorizerId: authStruct.authorizerId }, { ownerId: authStruct.ownerId } ] }, {$set: copy}, {upsert: true}); } else { this.setLocalData(copy); } - if(getStringId(authStruct._id).includes('defaultId') && mmode) { + if(getStringId(authStruct._id).includes('defaultId') && mode.includes('mongo')) { let replacedAuth = await this.collections.authorization.instance.findOne(copy); if(replacedAuth) { authStruct._id = getStringId(replacedAuth._id); if(otherAuthset) { - let otherAuth = await this.collections.authorization.instance.findOne( - {$and: [ - { authorizedId: otherAuthset.authorizedId }, - { authorizerId: otherAuthset.authorizerId }, - { ownerId: otherAuthset.ownerId } ] - } - ); + let otherAuth = await this.collections.authorization.instance.findOne({$and: [ { authorizedId: otherAuthset.authorizedId }, { authorizerId: otherAuthset.authorizerId }, { ownerId: otherAuthset.ownerId } ] }); if(otherAuth) { otherAuth.associatedAuthId = getStringId(authStruct._id); let copy2 = JSON.parse(JSON.stringify(otherAuth)); delete copy2._id; - await this.collections.authorization.instance.updateOne( - { $and: [ - { authorizedId: otherAuth.authorizedId }, - { authorizerId: otherAuth.authorizerId }, - { ownerId: otherAuth.ownerId } - ] }, {$set: copy2}, {upsert: true} - ); + await this.collections.authorization.instance.updateOne({ $and: [ { authorizedId: otherAuth.authorizedId }, { authorizerId: otherAuth.authorizerId }, { ownerId: otherAuth.ownerId } ] }, {$set: copy2}, {upsert: true}); this.checkToNotify(user,[otherAuth]); } } @@ -1651,28 +1364,17 @@ export class StructBackend extends Service { return authStruct as AuthorizationStruct; //pass back the (potentially modified) authStruct } - //TODO: fine grained struct filtering - checkAuthorization = async ( + + async checkAuthorization( user:string|Partial|{_id:string}, struct, request='READ', //'WRITE' - token?:string - ) => { + mode = this.mode + ) { /* If user is not the owner of the struct, check that they have permissions */ - if(typeof user === 'string') { - if(this.users[user]) - user = this.users[user]; - else user = {_id:user}; - } - //console.log(struct) - // console.log( - // 'user', user._id, - // 'struct', struct - // ) - if(!user || !struct) return false; if(!struct.ownerId) return true; //no owner, return true @@ -1680,73 +1382,32 @@ export class StructBackend extends Service { if(typeof user === 'object') { if(struct.ownerId === getStringId(user._id as string)) { if((user as ProfileStruct).userRoles?.['admincontrol']) { - //do something + //do somethign } - //console.log('is owner') - return true; - } //else console.log('not owner') - } - - if(this.useAccessTokens) { //pass an access token for single client validation - if(!this.accessTokens.get(user._id) || this.accessTokens.get(user._id) !== token) //not authorized without a current token - { - //console.log('failed useAccessTokens') - return false; - } //else console.log('passed useAccessTokens'); - } - else if (this.useRefreshTokens) { //pass a refresh token for multi client validation - if(!this.refreshTokens.get(user._id) || this.refreshTokens.get(user._id) !== token) //not authorized without a current token - { - //console.log('failed useRefreshTokens') - return false; - } //else console.log('passed useRefreshTokens'); + else return true; + } + } else if (typeof user === 'string') { + if(struct.ownerId === user) { + return true; + } + else user = {_id:user}; } let auth1, auth2; - if(this.mode.includes('mongo')) { - auth1 = await this.collections.authorization.instance.findOne( - { $or: [ - { - authorizedId:getStringId(user._id as string), - authorizerId:struct.ownerId, - ownerId:getStringId(user._id as string) - }, - { - authorizedId:struct.ownerId, - authorizerId:getStringId(user._id as string), - ownerId:getStringId(user._id as string) - } - ] - } - ); - if(!auth1) return false; - auth2 = await this.collections.authorization.instance.findOne( - { $or: [ - { - authorizedId:getStringId(user._id as string), - authorizerId:struct.ownerId, - ownerId:getStringId(struct.ownerId as string) - }, - { - authorizedId:struct.ownerId, - authorizerId:getStringId(user._id as string), - ownerId:getStringId(struct.ownerId as string) - } - ] - } - ); + if(mode.includes('mongo')) { + auth1 = await this.collections.authorization.instance.findOne({$or: [{authorizedId:getStringId(user._id as string),authorizerId:struct.ownerId, ownerId:getStringId(user._id as string)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id as string), ownerId:getStringId(user._id as string)}]}); + auth2 = await this.collections.authorization.instance.findOne({$or: [{authorizedId:getStringId(user._id as string),authorizerId:struct.ownerId, ownerId:struct.ownerId},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id as string), ownerId:struct.ownerId}]}); } else { auth1 = this.getLocalData('authorization', {ownerId:getStringId(user._id as string)}).find((o) => { - if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) - return true; + if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) return true; }); auth2 = this.getLocalData('authorization', {ownerId:struct.ownerId}).find((o) => { - if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) - return true; + if(o.authorizedId === getStringId((user as any)._id) && o.authorizerId === struct.ownerId) return true; }); } if(!auth1 || !auth2) { + //console.log('auth bounced', user, struct, auth1, auth2); return false; } @@ -1768,6 +1429,7 @@ export class StructBackend extends Service { if(struct.structType === 'group') { if (auth1.authorizations[struct.name+'_admin'] && auth2.authorizations[struct.name+'_admin']) passed = true; + else passed = false; } //peers have access to most data for a user else if(auth1.authorizations['peer'] && auth2.authorizations['peer']) passed = true; @@ -1841,7 +1503,7 @@ export class StructBackend extends Service { //Local Data stuff (for non-mongodb usage of this server) //just assigns replacement object to old object if it exists, keeps things from losing parent context in UI - overwriteLocalData = (structs) => { + overwriteLocalData (structs) { if(Array.isArray(structs)){ structs.forEach((struct) => { let localdat = this.getLocalData(struct.structType,{'ownerId': struct.ownerId, '_id':getStringId(struct._id)}); @@ -1859,7 +1521,7 @@ export class StructBackend extends Service { } } - setLocalData = (structs) => { + setLocalData (structs) { let setInCollection = (s) => { let type = s.structType; @@ -1882,7 +1544,7 @@ export class StructBackend extends Service { } //pull a struct by collection, owner, and key/value pair from the local platform, leave collection blank to pull all ownerId associated data - getLocalData = (collection, query?): any => { + getLocalData(collection, query?): any { // Split Query let ownerId, key, value; @@ -1950,7 +1612,7 @@ export class StructBackend extends Service { } - deleteLocalData = (struct) => { + deleteLocalData(struct) { if(!struct) throw new Error('Struct not supplied') if(!struct.structType || !struct._id) return false; @@ -1959,13 +1621,4 @@ export class StructBackend extends Service { return true; } -} - - -let shallowqueryDummy = DS.ProfileStruct(); -for(const key in shallowqueryDummy) { - if(key === 'username'||key === 'lastName'||key === 'firstName'||key === 'name'||key === '_id'||key === 'pictureUrl') shallowqueryDummy[key] = 1 as any; - else delete shallowqueryDummy[key]; -} -//console.log(shallowqueryDummy); - +} \ No newline at end of file diff --git a/src/extras/struct/Struct.frontend.ts b/extras/struct/Struct.frontend.ts similarity index 81% rename from src/extras/struct/Struct.frontend.ts rename to extras/struct/Struct.frontend.ts index 815fb349..42e73b69 100644 --- a/src/extras/struct/Struct.frontend.ts +++ b/extras/struct/Struct.frontend.ts @@ -1,9 +1,7 @@ import { DataTablet, DS } from './datastructures/index' import { Data, ProfileStruct, AuthorizationStruct, GroupStruct, DataStruct, EventStruct, ChatroomStruct, CommentStruct, Struct } from './datastructures/types'; -import { genTimestampFromString, TimeSpecifier } from './genTimestamps' import { Service } from '../../services/Service'; import { User } from '../../services/router/Router'; -import { GraphNodeProperties } from '../../core/Graph'; export const randomId = (prefix?) => ((prefix) ? `${prefix}` : '') + Math.floor(1000000000000000*Math.random()) @@ -12,44 +10,27 @@ export const pseudoObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).t //intended for use with a UserRouter -export type StructFrontendProps = { - useAccessTokens?:boolean, - useRefreshTokens?:boolean -} & GraphNodeProperties - export class StructFrontend extends Service { name='structs' - currentUser: User //user from the endpoint service (e.g. websockets, Router) whose endpoints we want to use + currentUser: User //user from the UserRouter whose endpoints we want to use tablet = new DataTablet(); //DataTablet collections = this.tablet.collections; id: string = randomId() - useAccessTokens=false; - useRefreshTokens=false; - constructor( options?:any, user?:Partial ) { super(options); - this.load(this); - - if(options.useAccessTokens) this.useAccessTokens = options.useAccessTokens; - if(options.useRefreshTokens) this.useRefreshTokens = options.useRefreshTokens; + this.setTree(this); - if(user instanceof Object && Object.keys(user).length > 0) - this.setupUser(user); // Declares currentUser - } - - getToken(user:Partial) { - if(this.useAccessTokens) return user.accessToken; - else if (this.useRefreshTokens) return user.refreshToken; + if (user instanceof Object && Object.keys(user).length > 0) this.setupUser(user) // Declares currentUser } //TODO: make this able to be awaited to return the currentUser //uses a bunch of the functions below to set up a user and get their data w/ some cross checking for consistent profiles - setupUser = async(userinfo:Partial, callback=(currentUser)=>{}) => { + async setupUser(userinfo:Partial, callback=(currentUser)=>{}) { if(!userinfo) { console.error('must provide a minimum info object! e.g. {_id:"abc123"}'); @@ -64,20 +45,18 @@ export class StructFrontend extends Service { // let res = await this.login(); //console.log("Generating/Getting User: ", userinfo._id) - //console.log('getting user'); let res = await this.getUser(userinfo._id); - //console.log('setting user'); let user = res?.user; // console.log('user gotten', user) // console.log("getUser", user); let u; let newu = false; - //console.log('getUser result',user); - + console.log('getUser result',user); if(!user || !user._id) { //no profile, create new one and push initial results // if(!userinfo._id) userinfo._id = userinfo._id; - u = this.userStruct(userinfo,false); + console.log('creating new profile'); + u = this.userStruct(userinfo,true); newu = true; let wasSet = await this.setUser(u); let structs = this.getLocalData(undefined,{'ownerId': u._id}); @@ -90,21 +69,6 @@ export class StructFrontend extends Service { } else { u = user; - - let toUpdate = {_id:userinfo._id, ownerId: userinfo._id}; - let struct = this.userStruct(userinfo,false); - for(const key in struct) { - if((userinfo[key] && user[key] !== userinfo[key])) { - toUpdate[key] = userinfo[key]; - user[key] = userinfo[key]; - } - else if(struct[key] && !user[key]) { - toUpdate[key] = struct[key]; - user[key] = struct[key]; - } - } - - if(Object.keys(toUpdate).length > 2) await this.setUser(toUpdate as any); // u._id = user._id; //replace the unique mongo id for the secondary profile struct with the id for the userinfo for temp lookup purposes if(res?.authorizations){ @@ -122,7 +86,7 @@ export class StructFrontend extends Service { if(newu) {this.setLocalData(u);} else { - let data = await this.getAllUserData(u._id,undefined, [genTimestampFromString('last day'),Date.now()]); //todo: only query latest data + let data = await this.getAllUserData(u._id,undefined); //console.log("getServerData", data); if(!data || data.length === 0) { @@ -157,7 +121,6 @@ export class StructFrontend extends Service { }); if(toDelete.length > 0) this.deleteData(toDelete); //extraneous comments - //console.log('data:', data, 'resolve notifications:', notes); if(notes.length > 0) { this.resolveNotifications(notes, false, undefined); changed = true; @@ -174,12 +137,11 @@ export class StructFrontend extends Service { // u = new UserObj(u) // u = getUserCodes(u, true) this.setLocalData(u); //user is now set up in whatever case - //console.log('collections', this.tablet.collections); + console.log('collections', this.tablet.collections); } //console.log('u::',u) if(u) { - if(this.currentUser) Object.assign(this.currentUser,u); - else this.currentUser = u; + this.currentUser = u; callback(this.currentUser); //console.log('currentUser', u) return this.currentUser; @@ -240,7 +202,7 @@ export class StructFrontend extends Service { delete this.currentUser.userRoles[struct.name+'_client']; uset = true; } - if(uset) this.setUser(this.currentUser as any); //update roles + if(uset) this.setUser(this.currentUser); //update roles } } this.setLocalData(struct); @@ -276,21 +238,21 @@ export class StructFrontend extends Service { }); } + //console.log(data); + if (data?.message === 'notifications') { + //console.log('notifications', this.currentUser); + this.checkForNotifications(); //pull notifications + } + if (data?.message === 'deleted') { + this.deleteLocalData(data.data); //remove local instance + } + this.onResult(data); } - structNotification = () => { - //console.log('struct notifications') - this.checkForNotifications(); - } - - structDeleted = (struct:{_id:string,structType:string}) => { - this.deleteLocalData([struct]); //remove local instance - } - //just a customizable callback to preserve the default while adding your own - onResult = (data) => { - + onResult(data) { + } @@ -311,13 +273,13 @@ export class StructFrontend extends Service { parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) } */ - addStruct = async ( + async addStruct ( structType:string='struct', props:any={}, //add any props you want to set, adding users[] with ids will tell who to notify if this struct is updated parentUser?:{[key:string]:any}, parentStruct?:{[key:string]:any}, updateServer:boolean = true - ) => { + ) { let newStruct = DS.Struct(structType, props, parentUser, parentStruct); if(updateServer) newStruct = await this.updateServerData([newStruct])[0]; @@ -326,40 +288,19 @@ export class StructFrontend extends Service { } //info can be email, id, username, or name. Returns their profile and authorizations - getUser = async (info:string|number='', basicInfo?:boolean, callback=this.baseServerCallback) => { + getUser = async (info:string|number='',callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getUser', args:[this.currentUser._id, info, basicInfo, this.getToken(this.currentUser)]})); + let res = (await this.currentUser.request({route:'getUser', args:[this.currentUser._id, info]}))?.[0]; callback(res); - return (res as {user:ProfileStruct, groups:GroupStruct[], authorizations:AuthorizationStruct[]} | undefined); - } - } - - //safely query user basic identification info for lookup - queryUsers = async ( - info:string, //name, email, username, etc - skip?:number, - limit?:number, - callback=this.baseServerCallback - ) => { - if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'queryUsers', args:[ - this.currentUser._id, - info, - skip, - limit, - undefined, - this.getToken(this.currentUser) - ]})) // Pass Array - callback(res); - return res + return (res as {user:ProfileStruct, groups:[], authorizations:[]} | undefined); } } //get user basic info by id - getUsers = async (ids:(string|number)[]=[], basicInfo?:boolean, callback=this.baseServerCallback) => { + getUsers = async (ids:(string|number)[]=[],callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getUsersByIds', args:[this.currentUser._id, ids, basicInfo]})) // Pass Array - callback(res); + let res = (await this.currentUser.request({route:'getUsersByIds', args:[this.currentUser._id, ids]})) // Pass Array + callback(res) return res } } @@ -374,44 +315,27 @@ export class StructFrontend extends Service { } //pull all of the collections (except excluded collection names e.g. 'groups') for a user from the server - getAllUserData = async (ownerId:string|number, excluded:any[]=[], timeRange?:[number|TimeSpecifier,number|TimeSpecifier], callback=this.baseServerCallback) => { - if(timeRange) { - if(typeof timeRange[0] === 'string') timeRange[0] = genTimestampFromString(timeRange[0]); - if(typeof timeRange[1] === 'string') timeRange[1] = genTimestampFromString(timeRange[1]); - } + getAllUserData = async (ownerId:string|number, excluded:any[]=[], callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getAllData', args:[this.currentUser._id, ownerId, excluded, timeRange, this.getToken(this.currentUser)]} )); + let res = (await this.currentUser.request({route:'getAllData', args:[ownerId, excluded]} )); callback(res) return res } } - query = async (collection:string, mongoQuery={}, findOne=false, skip=0, callback=this.baseServerCallback) => { + query = async (collection:string, queryObj={}, findOne=false, skip=0, callback=this.baseServerCallback) => { if(this.currentUser?.request) { - if(!collection || !mongoQuery) return undefined; - let res = (await this.currentUser.request({route:'query',args:[this.currentUser._id, collection, mongoQuery, findOne, skip, this.getToken(this.currentUser)]} )); + if(!collection || !queryObj) return undefined; + let res = (await this.currentUser.request({route:'query',args:[this.currentUser._id, collection,queryObj,findOne,skip]} )); if(typeof callback === 'function') callback(res); return res; } } - //get data by a range of time via utcTimeStamps, default key is timestamp - getDataByTimeRange(collection, timeRange?:[number|TimeSpecifier,number|TimeSpecifier], ownerId?:string|number|undefined, limit:number=0, skip:number=0, key?:string) { - let query = {} as any; - if(timeRange) { - if(typeof timeRange[0] === 'string') timeRange[0] = genTimestampFromString(timeRange[0]); - if(typeof timeRange[1] === 'string') timeRange[1] = genTimestampFromString(timeRange[1]); - } - let range = {$gt:timeRange[0],$lt:timeRange[1]} - if(key) query[key] = range; - else query.timestamp = range; - return this.getData(collection, ownerId, query, limit, skip); - } - //get data by specified details from the server. You can provide only one of the first 3 elements. The searchDict is for mongoDB search keys - getData = async (collection:string, ownerId?:string|number|undefined, searchDict?, limit:number=0, skip:number=0, callback=this.baseServerCallback) => { + getData = async (collection:string,ownerId?:string|number|undefined,searchDict?,limit:number=0,skip:number=0,callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getData', args:[this.currentUser._id, collection, ownerId, searchDict, limit, skip, this.getToken(this.currentUser)]}));//?.[0] + let res = (await this.currentUser.request({route:'getData', args:[this.currentUser._id, collection, ownerId, searchDict, limit, skip]}));//?.[0] //console.log('GET DATA RES', res, JSON.stringify(collection), JSON.stringify(ownerId)); if(typeof callback === 'function') callback(res); return res; @@ -421,17 +345,17 @@ export class StructFrontend extends Service { //get data by specified details from the server. You can provide only one of the first 3 elements. The searchDict is for mongoDB search keys getDataByIds = async (structIds:any[]=[],ownerId?:string|number|undefined,collection?:string|undefined,callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getDataByIds', args:[this.currentUser._id, structIds, ownerId, collection, this.getToken(this.currentUser)]})); + let res = (await this.currentUser.request({route:'getDataByIds', args:[this.currentUser._id, structIds, ownerId, collection]})); if(typeof callback === 'function') callback(res); return res } } //get struct based on the parentId - getStructParentData = async (struct:Struct,callback=this.baseServerCallback) => { - if(!struct?.parent) return; + getStructParentData = async (struct:any,callback=this.baseServerCallback) => { + if(!struct.parent) return; if(this.currentUser?.request) { - let args = [this.currentUser._id, struct.parent?.structType,'_id',struct.parent?._id, this.getToken(this.currentUser)]; + let args = [this.currentUser._id, struct.parent?.structType,'_id',struct.parent?._id]; let res = (await this.currentUser.request({route:'getData', args}))?.[0] if(typeof callback === 'function') callback(res); @@ -455,9 +379,9 @@ export class StructFrontend extends Service { //sets the user profile data on the server - setUser = async (userStruct:ProfileStruct,callback=this.baseServerCallback) => { - if(userStruct && this.currentUser?.request) { - let res = (await this.currentUser.request({route:'setUser', args:[this.currentUser._id, this.stripStruct(userStruct), this.getToken(this.currentUser)]})) + setUser = async (userStruct={},callback=this.baseServerCallback) => { + if(this.currentUser?.request) { + let res = (await this.currentUser.request({route:'setUser', args:[this.currentUser._id, this.stripStruct(userStruct)]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -496,12 +420,13 @@ export class StructFrontend extends Service { user[prop] = usertoken[prop]; changed = true; } } - if(changed) return await this.setUser(user as any,callback); + if(changed) return await this.setUser(user,callback); return changed; } /* strip circular references and update data on the server, default callback will process the returned structs back into */ setData = async (structs:Partial|Partial[]=[],notify=true,callback=this.baseServerCallback) => { + if(this.currentUser?.request) { const copies = new Array(); if(!Array.isArray(structs) && typeof structs === 'object') structs = [structs]; @@ -509,7 +434,7 @@ export class StructFrontend extends Service { copies.push(this.stripStruct(struct)); }) - let res = (await this.currentUser.request({route:'setData', args:[this.currentUser._id, copies, notify, this.getToken(this.currentUser)]})); + let res = (await this.currentUser.request({route:'setData', args:[this.currentUser._id, copies, notify]})); if(typeof callback === 'function') callback(res); return res; } @@ -553,27 +478,27 @@ export class StructFrontend extends Service { } }); //console.log('deleting',toDelete); - let res = (await this.currentUser.request({route:'deleteData', args:[this.currentUser._id, toDelete, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'deleteData', args:[this.currentUser._id, toDelete]}))?.[0] if(typeof callback === 'function') callback(res) return res } } //delete user profile by ID on the server - deleteUser = async (userId:string=this.currentUser._id, deleteData?:boolean, callback=this.baseServerCallback) => { + deleteUser = async (userId, callback=this.baseServerCallback) => { if(this.currentUser?.request) { if(!userId) return; - let res = (await this.currentUser.request({route:'deleteUser', args:[this.currentUser._id, userId, deleteData, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'deleteUser', args:[this.currentUser._id, userId]}))?.[0] if(typeof callback === 'function') callback(res) return res } } //set a group struct on the server - setGroup = async (groupStruct:GroupStruct,callback=this.baseServerCallback) => { - if(groupStruct && this.currentUser?.request) { - let res = (await this.currentUser.request({route:'setGroup', args:[this.currentUser._id, this.stripStruct(groupStruct), this.getToken(this.currentUser)]})) + setGroup = async (groupStruct={},callback=this.baseServerCallback) => { + if(this.currentUser?.request) { + let res = (await this.currentUser.request({route:'setGroup', args:[this.currentUser._id, this.stripStruct(groupStruct)]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -582,7 +507,7 @@ export class StructFrontend extends Service { //get group structs or single one by Id getUserGroups = async (userId=this.currentUser._id, groupId='',callback=this.baseServerCallback) => { if(this.currentUser?.request) { - let res = (await this.currentUser.request({route:'getUserGroups', args:[this.currentUser._id, userId,groupId, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'getUserGroups', args:[this.currentUser._id, userId,groupId]})) if(typeof callback === 'function') callback(res) return res } @@ -594,16 +519,16 @@ export class StructFrontend extends Service { if(!groupId) return; this.deleteLocalData(groupId); - let res = (await this.currentUser.request({route:'deleteGroup', args:[this.currentUser._id, groupId, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'deleteGroup', args:[this.currentUser._id, groupId]}))?.[0] if(typeof callback === 'function') callback(res) return res } } //set an authorization struct on the server - setAuthorization = async (authorizationStruct:AuthorizationStruct,callback=this.baseServerCallback) => { - if(authorizationStruct && this.currentUser?.request) { - let res = (await this.currentUser.request({route:'setAuthorization', args:[this.currentUser._id, this.stripStruct(authorizationStruct), this.getToken(this.currentUser)]})) + setAuthorization = async (authorizationStruct={},callback=this.baseServerCallback) => { + if(this.currentUser?.request) { + let res = (await this.currentUser.request({route:'setAuthorization', args:[this.currentUser._id, this.stripStruct(authorizationStruct)]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -613,7 +538,7 @@ export class StructFrontend extends Service { getAuthorizations = async (userId=this.currentUser?._id, authorizationId='',callback=this.baseServerCallback) => { if(this.currentUser?.request) { if(userId === undefined) return; - let res = (await this.currentUser.request({route:'getAuthorizations', args:[this.currentUser._id, userId, authorizationId, this.getToken(this.currentUser)]})) + let res = (await this.currentUser.request({route:'getAuthorizations', args:[this.currentUser._id, userId, authorizationId]})) if(typeof callback === 'function') callback(res) return res } @@ -624,7 +549,8 @@ export class StructFrontend extends Service { if(this.currentUser?.request) { if(!authorizationId) return; this.deleteLocalData(authorizationId); - let res = (await this.currentUser.request({route:'deleteAuthorization', args:[this.currentUser._id, authorizationId, this.getToken(this.currentUser)]})); + + let res = (await this.currentUser.request({route:'deleteAuthorization', args:[authorizationId]}))?.[0] if(typeof callback === 'function') callback(res) return res } @@ -676,6 +602,7 @@ export class StructFrontend extends Service { return true; } + //setup authorizations automatically based on group setAuthorizationsByGroup = async (user=this.currentUser) => { @@ -830,13 +757,12 @@ export class StructFrontend extends Service { let u = authorizationStruct.authorizerId; if(u) { return new Promise(async resolve => { - this.getUser(u, true, async (data)=> { - let res; - if(!collection) res = await this.getAllUserData(u,['notification'],undefined,callback); - else res = await this.getData(collection,u,searchDict,limit,skip,callback); + this.getUser(u,async (data)=> { + if(!collection) await this.getAllUserData(u,['notification'],callback); + else await this.getData(collection,u,searchDict,limit,skip,callback); - resolve(res) - callback(res); + resolve(data) + callback(data); }); //gets profile deets }) } else return undefined; @@ -852,10 +778,10 @@ export class StructFrontend extends Service { let u = o.authorizerId; if(u) { let data; - let user = await this.getUser(u, true, callback); + let user = await this.getUser(u,callback); if(user) results.push(user); - if(!collection) data = await this.getAllUserData(u,['notification'],undefined,callback); + if(!collection) data = await this.getAllUserData(u,['notification'],callback); else data = await this.getData(collection,u,searchDict,limit,skip,callback); if(data) results.push(data); } @@ -898,11 +824,11 @@ export class StructFrontend extends Service { //get auths where you have granted somebody peer access getLocalUserPeerIds = (user=this.currentUser) => { - if(!user) return {} as any; - let result:any = {}; + if(!user) return [] as any[]; + let result:any[] = []; let authorizations = this.getLocalData('authorization',user._id); authorizations.forEach((a)=>{ - if(a.authorizations['peer'] && a.authorizerId === user._id) result[a.authorizedId] = true; + if(a.authorizations['peer'] && a.authorizerId === user._id) result.push(a.authorizedId); }); return result; } @@ -929,33 +855,31 @@ export class StructFrontend extends Service { } //pass a single struct or array of structs - deleteLocalData(structs:Struct[]) { + deleteLocalData(structs) { if(Array.isArray(structs)) structs.forEach(s => this.deleteStruct(s)); else this.deleteStruct(structs); //single return true; } - deleteStruct(struct:Struct) { - if(typeof struct === 'string') struct = this.getLocalData(undefined,{_id:struct}); //get the struct if an id was supplied + deleteStruct(struct) { + if(typeof struct === 'string') struct = this.getLocalData(struct); //get the struct if an id was supplied if(!struct) throw new Error('Struct not supplied') if(!struct.structType || !struct._id) return false; - this.tablet.collections.get(struct.structType as string).delete(struct._id); + this.tablet.collections.get(struct.structType).delete(struct._id); return true; } //strips circular references from the struct used clientside, returns a soft copy with the changes - stripStruct(struct:Struct) { + stripStruct(struct={}) { const copy = Object.assign({ }, struct); for(const prop in copy) { - if(copy[prop] === undefined || copy[prop] === "" || copy[prop].constructor.name === 'Map' || copy[prop].constructor.name === 'Set' || typeof copy[prop] === 'function') delete copy[prop]; //delete undefined - else if (Array.isArray(copy[prop]) && copy[prop].length === 0) delete copy[prop]; //get rid of empty arrays - else if(typeof copy[prop] === 'object' && Object.keys(copy[prop]).length === 0) delete copy[prop]; //get rid of empty objects + if(copy[prop] === undefined || copy[prop].constructor.name === 'Map' || typeof copy[prop] === 'function') delete copy[prop]; //delete undefined } return copy; } //create a struct with the prepared props to be filled out - createStruct(structType:string,props:{[key:string]:any},parentUser=this.currentUser,parentStruct?:Struct):any { + createStruct(structType,props,parentUser=this.currentUser,parentStruct?):any { let struct = DS.Struct(structType,props,parentUser,parentStruct) return struct; } @@ -965,22 +889,14 @@ export class StructFrontend extends Service { currentUser=false ) { let user = DS.ProfileStruct(undefined, props, props); - if(!user.name && user.firstName) - user.name = user.firstName + ' ' + user.lastName; - else if(user.name && !user.firstName) { - let split = user.name.split(' '); - user.firstName = split[0]; - user.lastName = split[split.length-1]; - } if(props._id) user.id = props._id; //references the token id else if(props.id) user.id = props.id; - else user.id = 'user'+Math.floor(Math.random()*1000000000000000); + else user.id = 'user'+Math.floor(Math.random()*10000000000); user._id = user.id as any; //for mongo stuff user.ownerId = user.id; - let dummy = DS.ProfileStruct(); for(const prop in props) { - if(Object.keys(dummy).indexOf(prop) < 0) { + if(Object.keys(DS.ProfileStruct()).indexOf(prop) < 0) { delete user[prop]; } //delete non-dependent data (e.g. tokens we only want to keep in a secure collection) } @@ -995,7 +911,7 @@ export class StructFrontend extends Service { authorizerUserName='', authorizedUserId='', authorizedUserName='', - authorizations:{}={}, + authorizations:{}={}, // TODO: really any[] or has type?? structs:{}={}, excluded:{}={}, groups:{}={}, @@ -1015,6 +931,7 @@ export class StructFrontend extends Service { newAuthorization.expires = expires; newAuthorization.status = 'PENDING'; newAuthorization.associatedAuthId = ''; + newAuthorization.ownerId = parentUser._id; //console.log('new authorization', newAuthorization) newAuthorization = await this.setAuthorization(newAuthorization); @@ -1043,6 +960,7 @@ export class StructFrontend extends Service { Object.assign(newGroup.users, newGroup.admins); Object.assign(newGroup.users, newGroup.peers); Object.assign(newGroup.users, newGroup.clients); + newGroup.ownerId = parentUser._id; //this.setLocalData(newGroup); @@ -1083,6 +1001,7 @@ export class StructFrontend extends Service { newDataInstance.type = type; newDataInstance.data = data; newDataInstance.expires = expires; + newDataInstance.ownerId = parentUser._id; //this.setLocalData(newDataInstance); @@ -1093,23 +1012,20 @@ export class StructFrontend extends Service { addEvent = async ( parentUser:Partial, - author:string='', - event:string|number='', - notes:string='', - startTime:string|number=undefined, - endTime:string|number=undefined, - grade:string|number=undefined, - value:any=undefined, - units:string=undefined, - location:any=undefined, - attachments:string|Data[]=undefined, - users:{[key:string]:true}=undefined, + author='', + event='', + notes='', + startTime=0, + endTime=0, + grade=0, + attachments:string|Data[]=[], + users:{}={}, updateServer=true ) => { if(!parentUser) return undefined; - if(users && Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); + if(Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); - let newEvent = this.createStruct('event', undefined, parentUser as any); + let newEvent = this.createStruct('event',undefined,parentUser as any); newEvent.author = author; newEvent.event = event; newEvent.notes = notes; @@ -1117,10 +1033,8 @@ export class StructFrontend extends Service { newEvent.endTime = endTime; newEvent.grade = grade; newEvent.attachments = attachments; - newEvent.value = value; - newEvent.units = units; newEvent.users = users; - newEvent.location = location; + newEvent.ownerId = parentUser._id; //this.setLocalData(newEvent); if(updateServer) newEvent = await this.updateServerData([newEvent])[0]; @@ -1132,12 +1046,12 @@ export class StructFrontend extends Service { parentUser:Partial, authorId='', message='', - attachments:string|Data[]=undefined, - users:{[key:string]:true}=undefined, + attachments:string|Data[]=[], + users:{}={}, updateServer=true ) => { if(!parentUser) return undefined; - if(users && Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); //adds the peer ids if none other provided + if(Object.keys(users).length === 0) users = this.getLocalUserPeerIds(parentUser as any); //adds the peer ids if none other provided let newChatroom = this.createStruct('chatroom',undefined,parentUser as any); newChatroom.message = message; @@ -1146,6 +1060,8 @@ export class StructFrontend extends Service { newChatroom.users = users; newChatroom.replies = []; newChatroom.comments = []; + newChatroom.ownerId = parentUser._id; + let update = [newChatroom]; if(updateServer) newChatroom = await this.updateServerData(update)[0]; @@ -1166,7 +1082,7 @@ export class StructFrontend extends Service { }, authorId='', message='', - attachments:string|Data[]=undefined, + attachments:string|Data[]=[], updateServer=true ) => { if(!roomStruct) return undefined; @@ -1180,6 +1096,7 @@ export class StructFrontend extends Service { newComment.attachments = attachments; newComment.users = roomStruct?.users; newComment.replies = []; + newComment.ownerId = parentUser._id; if (!updateServer) replyTo?.replies.push(newComment._id); //keep a local reference @@ -1204,5 +1121,6 @@ export class StructFrontend extends Service { if(updatedComment) return updatedComment as CommentStruct; return res as Array; } -} + +} diff --git a/src/extras/struct/datastructures/DataStructures.ts b/extras/struct/datastructures/DataStructures.ts similarity index 98% rename from src/extras/struct/datastructures/DataStructures.ts rename to extras/struct/datastructures/DataStructures.ts index dcdb635b..9274b7b5 100644 --- a/src/extras/struct/datastructures/DataStructures.ts +++ b/extras/struct/datastructures/DataStructures.ts @@ -20,7 +20,7 @@ export function Struct( structType: structType, //this is how you will look it up by type in the server ownerId: (parentUser as types.ProfileStruct)?._id, //owner user timestamp: Date.now(), //date of creation - parent: {structType:parentStruct?.structType, _id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) + parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) } if(!struct.ownerId) delete struct.ownerId; @@ -429,13 +429,10 @@ export function ProfileStruct( sex: '', birthday: '', type: '', - pictureUrl:'', userRoles: {}, socials: {}, data: {}, //arbitrary stuff - hidden: false, - accessToken:'', //for security - refreshToken:'', //for security + id: '' //references the token id which is behind a collection permission }; let struct = Struct('profile',props,parentUser,parentStruct); @@ -532,10 +529,7 @@ export function EventStruct( author:"", // startTime:"", //event began endTime:"", //event ended - grade:undefined, //severity - value:undefined, - units:undefined, - location:undefined, + grade:0, //severity notes:"", //additional details attachments:new Array(), users:{}, //users to be informed (i.e. peers) diff --git a/src/extras/struct/datastructures/DataTablet.ts b/extras/struct/datastructures/DataTablet.ts similarity index 100% rename from src/extras/struct/datastructures/DataTablet.ts rename to extras/struct/datastructures/DataTablet.ts diff --git a/src/extras/struct/datastructures/index.ts b/extras/struct/datastructures/index.ts similarity index 100% rename from src/extras/struct/datastructures/index.ts rename to extras/struct/datastructures/index.ts diff --git a/src/extras/struct/datastructures/types.ts b/extras/struct/datastructures/types.ts similarity index 89% rename from src/extras/struct/datastructures/types.ts rename to extras/struct/datastructures/types.ts index c16eb314..7e096035 100644 --- a/src/extras/struct/datastructures/types.ts +++ b/extras/struct/datastructures/types.ts @@ -6,8 +6,7 @@ export type Struct = { structType?:string|number, timestamp?:string|number, ownerId?:string|number, - parent?:{structType:string,_id:string|number}, - [key:string]:any + parent?:{structType:string,_id:string|number} } export type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined @@ -34,14 +33,11 @@ export type EventStruct = { event:string, //event type e.g. relapse, hospitalization author:string, startTime:string, //event began - endTime?:string, //event ended - grade?:string|number, //severity - value?:any, //e.g. heart rate, distance - units?:string, //e.g. bpm, millimeteres - notes?:string, //additional details - location?:any, - attachments?:Data|string|number[], //can be data or struct Ids - users?:{[key:string]:true}, //users to be informed (i.e. peers) + endTime:string, //event ended + grade:string|number, //severity + notes:string, //additional details + attachments:Data|string|number[], //can be data or struct Ids + users:{}, //users to be informed (i.e. peers) tag?:string|number } & Struct @@ -52,7 +48,7 @@ export type ChatroomStruct = { attachments: Data|string|number[], comments: string[], //all comment struct Ids replies: string[], //first level reply comment struct Ids - users: {[key:string]:true}, //user Ids + users: {}, //user Ids audioChatActive: boolean, videoChatActive: boolean, tag?:string|number @@ -63,7 +59,7 @@ export type CommentStruct = { replyTo:string, attachments: Data|string|number[], replies: string[], //struct Ids - users:{[key:string]:true}, //user Ids + users: {}, //user Ids tag?:string|number } & Struct @@ -90,11 +86,10 @@ export type DateStruct = { } & Struct export type ProfileStruct = { - username?: string, + username: string, name?: string, firstName?: string, lastName?: string, - fullName?: string, email?: string, phone?: string, sex?: string, @@ -103,11 +98,8 @@ export type ProfileStruct = { socials?: {}, data?: {}, type?: string, - hidden?: boolean, - pictureUrl: string, - accessToken?:string, - refreshToken?:string, - tag?:string|number + id?: string|number, + tag?:string|number } & Struct export type AuthorizationStruct = { diff --git a/src/extras/tinybuild.config.js b/extras/tinybuild.config.js similarity index 96% rename from src/extras/tinybuild.config.js rename to extras/tinybuild.config.js index 73cadfe9..8bf7c96e 100644 --- a/src/extras/tinybuild.config.js +++ b/extras/tinybuild.config.js @@ -9,7 +9,7 @@ const config = { bundleBrowser: true, //create plain js build? Can include globals and init scripts bundleESM: true, //create esm module js files bundleTypes: true, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: true, //create node platform plain js build, specify platform:'node' to do the rest of the files + bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. //minify: false, minifyWhitespace:true, diff --git a/src/extras/tinybuild.gpu.config.js b/extras/tinybuild.gpu.config.js similarity index 100% rename from src/extras/tinybuild.gpu.config.js rename to extras/tinybuild.gpu.config.js diff --git a/src/extras/tinybuild.storage.config.js b/extras/tinybuild.storage.config.js similarity index 100% rename from src/extras/tinybuild.storage.config.js rename to extras/tinybuild.storage.config.js diff --git a/src/extras/tsconfig.json b/extras/tsconfig.json similarity index 97% rename from src/extras/tsconfig.json rename to extras/tsconfig.json index 512d0007..d71f0ea1 100644 --- a/src/extras/tsconfig.json +++ b/extras/tsconfig.json @@ -4,8 +4,8 @@ /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, - "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "target": "es2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "es2020" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, "declaration": true, /* Generates corresponding '.d.ts' file. */ "allowJs": true, /* Allow javascript files to be compiled. */ "skipLibCheck": true /* Skip type checking of declaration files. */, diff --git a/src/extras/webgl-plot/webglplot.routes.ts b/extras/webgl-plot/webglplot.routes.ts similarity index 99% rename from src/extras/webgl-plot/webglplot.routes.ts rename to extras/webgl-plot/webglplot.routes.ts index 24f2c378..d21b4633 100644 --- a/src/extras/webgl-plot/webglplot.routes.ts +++ b/extras/webgl-plot/webglplot.routes.ts @@ -2,7 +2,7 @@ import { WorkerInfo } from '../../services/worker/Worker.service'//"graphscript" import { WebglLinePlotInfo,WebglLinePlotProps,WebglLinePlotUtil, WebglLineProps } from "webgl-plot-utils"//'../../../BrainsAtPlay_Libraries/webgl-plot-utils/webgl-plot-utils'//"webgl-plot-utils"//'../../BrainsAtPlay_Libraries/webgl-plot-utils/webgl-plot-utils'//"webgl-plot-utils"; import { FilterSettings } from "../algorithms/util/BiquadFilters"; -export { WebglLinePlotUtil, WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo } //re-export types for reference +export { WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo } //re-export types for reference export const webglPlotRoutes = { setupChart:function setupChart(settings:WebglLinePlotProps) { diff --git a/extras/yarn.lock b/extras/yarn.lock new file mode 100644 index 00000000..970faa9f --- /dev/null +++ b/extras/yarn.lock @@ -0,0 +1,73 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@types/node@~18.7.15": + "integrity" "sha512-XnjpaI8Bgc3eBag2Aw4t2Uj/49lLBSStHWfqKvIuXD7FIrZyMLWp8KuAFHAqxMZYTF9l08N1ctUn9YNybZJVmQ==" + "resolved" "https://registry.npmjs.org/@types/node/-/node-18.7.15.tgz" + "version" "18.7.15" + +"async@^2.1.4": + "integrity" "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==" + "resolved" "https://registry.npmjs.org/async/-/async-2.6.4.tgz" + "version" "2.6.4" + dependencies: + "lodash" "^4.17.14" + +"brainsatplay-math@~0.0.25": + "integrity" "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + "resolved" "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz" + "version" "0.0.25" + +"browserfs@^1.4.3": + "integrity" "sha512-tz8HClVrzTJshcyIu8frE15cjqjcBIu15Bezxsvl/i+6f59iNCN3kznlWjz0FEb3DlnDx3gW5szxeT6D1x0s0w==" + "resolved" "https://registry.npmjs.org/browserfs/-/browserfs-1.4.3.tgz" + "version" "1.4.3" + dependencies: + "async" "^2.1.4" + "pako" "^1.0.4" + +"bson-objectid@~2.0.4": + "integrity" "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + "resolved" "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz" + "version" "2.0.4" + +"gpujsutils@~1.0.12": + "integrity" "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" + "resolved" "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz" + "version" "1.0.12" + +"lodash@^4.17.14": + "integrity" "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "resolved" "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" + "version" "4.17.21" + +"pako@^1.0.4": + "integrity" "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + "resolved" "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz" + "version" "1.0.11" + +"tinybuild@file:../../../../AppData/Roaming/npm/node_modules/tinybuild": + "resolved" "file:../../../../AppData/Roaming/npm/node_modules/tinybuild" + "version" "0.3.181" + dependencies: + "chokidar" "~3.5.3" + "esbuild" "~0.14.49" + "ws" "^8.5.0" + +"web-worker@^1.2.0": + "integrity" "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + "resolved" "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz" + "version" "1.2.0" + +"webgl-plot-utils@~0.3.13": + "integrity" "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==" + "resolved" "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz" + "version" "0.3.13" + dependencies: + "webgl-plot" "~0.7.0" + +"webgl-plot@~0.7.0": + "integrity" "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + "resolved" "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz" + "version" "0.7.0" diff --git a/index.core.ts b/index.core.ts index e94571ea..7366430d 100644 --- a/index.core.ts +++ b/index.core.ts @@ -1,5 +1,2 @@ -export * from './src/core/Graph' -export * from './src/core/EventHandler' - -export * from './src/loaders' \ No newline at end of file +export * from './core/index' \ No newline at end of file diff --git a/examples/loaders/web_components/index.html b/index.html similarity index 71% rename from examples/loaders/web_components/index.html rename to index.html index 49564abb..7eaea076 100644 --- a/examples/loaders/web_components/index.html +++ b/index.html @@ -4,7 +4,7 @@ - diff --git a/index.node.ts b/index.node.ts index 6ae17440..7bd1b6a6 100644 --- a/index.node.ts +++ b/index.node.ts @@ -1,38 +1,34 @@ //frontend (browser-compatible) exports -export * from './src/core/Graph' -export * from './src/core/EventHandler' -export * from './src/loaders' +export * from './core/index' -export { methodstrings } from './src/loaders/methodstrings' +export * from './services/Service' +export * from './services/unsafe/Unsafe.service' -export * from './src/services/Service' -export * from './src/services/remote/remote.routes' - -export * from './src/services/ecs/ECS.service' +export * from './services/ecs/ECS.service' // export * from './services/dom/DOM.service' // export * from './services/dom/components/index' -export * from './src/services/e2ee/E2EE.service' +export * from './services/e2ee/E2EE.service' //export * from './services/gpu/GPU.service' -export * from './src/services/http/HTTP.node' +export * from './services/http/HTTP.node' -export * from './src/services/sse/SSE.node' +export * from './services/sse/SSE.node' -export * from './src/services/wss/WSS.node' +export * from './services/wss/WSS.node' -export * from './src/services/cmd/CMD.node' +export * from './services/cmd/CMD.node' -//export * from './src/services/struct/Struct.frontend' +//export * from './services/struct/Struct.frontend' -// export * from './src/services/webrtc/WebRTC.browser' +// export * from './services/webrtc/WebRTC.browser' -//export * from './src/services/worker/Worker.service' //this needs a polyfill to work in nodejs -//export * from './src/services/worker/Subprocess' +//export * from './services/worker/Worker.service' +//export * from './services/worker/Subprocess' -export * from './src/services/sessions/sessions.service' +export * from './services/sessions/sessions.service' -export * from './src/services/router/Router' \ No newline at end of file +export * from './services/router/Router' \ No newline at end of file diff --git a/index.ts b/index.ts index cebf97cd..c599acdc 100644 --- a/index.ts +++ b/index.ts @@ -1,43 +1,35 @@ //frontend (browser-compatible) exports +export * from './core/index' -export * from './src/core/Graph' -export * from './src/core/EventHandler' -export * from './src/loaders' -export * from './src/services/utils' +export * from './services/Service' +export * from './services/unsafe/Unsafe.service' -export { methodstrings } from './src/loaders/methodstrings' +export * from './services/ecs/ECS.service' -export * from './src/services/Service' -export * from './src/services/remote/remote.routes' +//export * from './services/dom/DOM.service' +export { DOMElement, addCustomElement } from './core/loaders/html/DOMElement' +export * from './core/loaders/html/html.loader' -export * from './src/services/ecs/ECS.service' - -export {html, xml} from './src/loaders/html/html' -export * from './src/loaders/html/html.loader' - -export { DOMElement, addCustomElement } from './src/loaders/html/DOMElement' -export * from './src/loaders/html/wc.loader' //includes the web component spec, html loader is a little leaner otherwise - -export * from './src/services/e2ee/E2EE.service' +export * from './services/e2ee/E2EE.service' //export * from './services/gpu/GPU.service' -export * from './src/services/http/HTTP.browser' +export * from './services/http/HTTP.browser' -export * from './src/services/sse/SSE.browser' +export * from './services/sse/SSE.browser' -export * from './src/services/wss/WSS.browser' +export * from './services/wss/WSS.browser' //export * from './services/struct/Struct.frontend' -export * from './src/services/webrtc/WebRTC.browser' +export * from './services/webrtc/WebRTC.browser' -export * from './src/services/worker/Worker.service' -export * from './src/services/worker/ProxyListener' -export * from './src/services/worker/WorkerCanvas' -//export * from './src/services/worker/Subprocess' +export * from './services/worker/Worker.service' +export * from './services/worker/ProxyListener' +export * from './services/worker/WorkerCanvas' +export * from './services/worker/Subprocess' -export * from './src/services/sessions/sessions.service' +export * from './services/sessions/sessions.service' -export * from './src/services/router/Router' \ No newline at end of file +export * from './services/router/Router' \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 5e09c1ee..271c491e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,28 +1,24 @@ { - "name": "graphscript", - "version": "0.3.1", + "name": "graphscript-core", + "version": "0.2.14", "lockfileVersion": 2, "requires": true, "packages": { "": { - "name": "graphscript", - "version": "0.3.1", - "license": "LGPL-3.0-or-later", + "name": "graphscript-core", + "version": "0.2.14", + "license": "AGPL-3.0-or-later", "dependencies": { - "better-sse": "~0.11.0", - "brainsatplay-math": "~0.1.0", - "web-worker": "~1.3.0", - "ws": "~8.16.0" + "web-worker": "^1.2.0" }, "devDependencies": { - "@types/node": "~18.7.15", - "@types/ws": "~8.5.3" + "@types/node": "~18.7.15" } }, "../../../AppData/Roaming/npm/node_modules/tinybuild": { "version": "0.3.127", "extraneous": true, - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "chokidar": "~3.5.3", "esbuild": "~0.14.41", @@ -42,53 +38,10 @@ "integrity": "sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA==", "dev": true }, - "node_modules/@types/ws": { - "version": "8.5.4", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", - "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/better-sse": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.11.0.tgz", - "integrity": "sha512-xY5Nmn9XyO5PiMw4//C+mNCUknaueugBqXMoMdEp2s9oNDVI4Vu6nhjduxA6yOxJVm/O6u3YC3FbLMHEvTzk3Q==", - "engines": { - "node": ">=12", - "pnpm": ">=6" - } - }, - "node_modules/brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" - }, "node_modules/web-worker": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.3.0.tgz", - "integrity": "sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==" - }, - "node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" } }, "dependencies": { @@ -98,35 +51,10 @@ "integrity": "sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA==", "dev": true }, - "@types/ws": { - "version": "8.5.4", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", - "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", - "dev": true, - "requires": { - "@types/node": "*" - } - }, - "better-sse": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.11.0.tgz", - "integrity": "sha512-xY5Nmn9XyO5PiMw4//C+mNCUknaueugBqXMoMdEp2s9oNDVI4Vu6nhjduxA6yOxJVm/O6u3YC3FbLMHEvTzk3Q==" - }, - "brainsatplay-math": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.1.0.tgz", - "integrity": "sha512-V95piSmlNtqf6vYXrhg/wu/IuTSQnM1jj5LXKHh68zVGYV9x2EEiR4TqcRMw3URbRHzME4DHkWNXJ1l2vwDhYg==" - }, "web-worker": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.3.0.tgz", - "integrity": "sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==" - }, - "ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", - "requires": {} + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", + "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" } } } diff --git a/package.json b/package.json index 8a9b9da1..49b459d2 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name": "graphscript", - "version": "0.3.12", + "version": "0.2.23", "description": "Comprehensive acyclic-graph based application architecture with microservices and networking", "main": "dist/index.js", "module": "dist/index.esm.js", "types": "dist/index.d.ts", "scripts": { - "start": "tinybuild && tinybuild path=tinybuild.node.config.js && tinybuild path=tinybuild.core.config.js && cd src/extras && npm start", + "start": "tinybuild && tinybuild path=tinybuild.node.config.js && tinybuild path=tinybuild.core.config.js && cd extras && npm start", "build": "tinybuild build", "serve": "tinybuild serve", "init": "node tinybuild/init.js", @@ -21,14 +21,13 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", - "devDependencies": { - "better-sse": "~0.11.0", - "brainsatplay-math": "~0.1.0", - "web-worker": "~1.3.0", - "ws": "~8.16.0", - "@types/node": "~18.7.15", - "@types/ws": "~8.5.3" + "license": "AGPL-3.0-or-later", + "dependencies": { + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", + "bson-objectid": "~2.0.3", + "web-worker": "~1.2.0", + "ws": "~8.11.0" }, "nodemonConfig": { "env": { @@ -38,5 +37,9 @@ "dist/", ".temp/" ] + }, + "devDependencies": { + "@types/node": "~18.7.15", + "@types/ws": "~8.5.3" } } diff --git a/src/services/Service.ts b/services/Service.ts similarity index 66% rename from src/services/Service.ts rename to services/Service.ts index bd4d7462..fcbc06f5 100644 --- a/src/services/Service.ts +++ b/services/Service.ts @@ -1,5 +1,5 @@ -import { Graph, GraphNode, GraphOptions } from "../../src/core/Graph"; -import {loaders} from '../../src/loaders'; +import { Graph, GraphNode, GraphOptions } from "../core/Graph2"; +import {loaders} from '../core/loaders'; export type TypedArray = @@ -23,27 +23,23 @@ export type ServiceMessage = { export type ServiceOptions = GraphOptions & { - services?:{[key:string]:Service|Function|{[key:string]:any}}, - restrict?:{[key:string]:boolean} //only allow the receive() (and on some services the remote subscribe() calls) to run specific nodes + services?:{[key:string]:Service|Function|{[key:string]:any}} } export class Service extends Graph { name = `service${Math.floor(Math.random()*1000000000000000)}`; - restrict?:{[key:string]:boolean}; - constructor(options?:ServiceOptions) { super({ //assign properties to the graph ...options, loaders: options?.loaders ? Object.assign({...loaders},options.loaders) : {...loaders} - //roots: + //tree: }); if(options?.services) this.addServices(options.services); - if(options?.restrict) this.restrict = options.restrict; - this.load(this); + if (!!options.graph) this.setTree(this); // Avoid setting the tree twice } addServices = (services:{[key:string]:Graph|Service|Function|{[key:string]:any}}) => { @@ -59,9 +55,7 @@ export class Service extends Graph { }); this.__node.nodes.forEach((n,k) => { - if(!(services[s] as Service).__node.nodes.get(k)) - (services[s] as Graph).__node.nodes.set(k,n) - }) + if(!(services[s] as Service).__node.nodes.get(k)) (services[s] as Graph).set(k,n) }) let set = this.set; @@ -69,7 +63,7 @@ export class Service extends Graph { (services[s] as Graph).set(tag,node); return set(tag,node); } - + let del = this.delete; this.delete = (tag:string) => { @@ -79,7 +73,7 @@ export class Service extends Graph { } else if(typeof services[s] === 'object') { - this.load(services[s]); //just a roots + this.setTree(services[s]); //just a tree } } } @@ -92,21 +86,14 @@ export class Service extends Graph { let m = method.toLowerCase(); //lower case is enforced in the route keys let src = this.__node.nodes.get(route); if(!src) { - src = this.__node.roots[route]; + src = this.__node.tree[route]; } if(src?.[m]) { - if(typeof src[m] !== 'function') { - if(args) { - if(Array.isArray(args) && args.length === 1) src[m] = args[0]; - else src[m] = args; - return; //set value, don't echo - } //if args were passed set the value + if(!(src[m] instanceof Function)) { + if(args) src[m] = args; //if args were passed set the value return src[m]; //could just be a stored local variable we are returning like a string or object } - else { - if(Array.isArray(args)) return src[m](...args); - else return src[m](args); - } + else return src[m](args); }//these could be any function or property call else return this.handleServiceMessage({route,args,method}) //process normally if the method doesn't return @@ -114,12 +101,10 @@ export class Service extends Graph { handleServiceMessage(message:ServiceMessage) { let call; - //console.log(message); if(typeof message === 'object') { if(message.route) call = message.route; else if (message.node) call = message.node; } if(call) { - //console.log('call',call,'message',message, 'nodes:', this.nodes.keys(),this) if(Array.isArray(message.args)) return this.run(call,...message.args); else return this.run(call,message.args); } else return message; @@ -139,59 +124,52 @@ export class Service extends Graph { ...args:[ServiceMessage|any,...any[]]|any[] ) => { if(typeof args[0] === 'object') { - const message = args[0]; - if(message.method) { //run a route method directly, results not linked to graph - return this.handleMethod(message.route, message.method, message.args); - } else if(message.route) { - return this.handleServiceMessage(message); - } else if (message.node){ - return this.handleGraphNodeCall(message.node, message.args); + if(args[0].method) { //run a route method directly, results not linked to graph + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if(args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node){ + return this.handleGraphNodeCall(args[0].node, args[0].args); } else if(this.__node.keepState) { - if(message.route) - this.setState({[message.route]:message.args}); - if(message.node) - this.setState({[message.node]:message.args}); + if(args[0].route) + this.setState({[args[0].route]:args[0].args}); + if(args[0].node) + this.setState({[args[0].node]:args[0].args}); } - return undefined; - } else return undefined; + return args; + } else return args; } //process http requests, socket messages, webrtc, osc, etc. with this customizable callback. This default still works in some scenarios receive:(...args)=>any|void = ( ...args:[ServiceMessage|any,...any[]]|any[] //generalized args for customizing, it looks weird I know ) => { - if(args[0]) { - let message = args[0]; - if(typeof message === 'string') { - let substr = message.substring(0,8); - if(substr.includes('{') || substr.includes('[')) { - if(substr.includes('\\')) message = message.replace(/\\/g,""); //double jsonified string - if(message[0] === '"') { message = message.substring(1,message.length-1)}; - //console.log(message) - message = JSON.parse(message); //parse stringified args - } + if(args[0]) if(typeof args[0] === 'string') { + let substr = args[0].substring(0,8); + if(substr.includes('{') || substr.includes('[')) { + if(substr.includes('\\')) args[0] = args[0].replace(/\\/g,""); //double jsonified string + if(args[0][0] === '"') { args[0] = args[0].substring(1,args[0].length-1)}; + //console.log(args[0]) + args[0] = JSON.parse(args[0]); //parse stringified args } + } - if(typeof message === 'object') { - if(message.method) { //run a route method directly, results not linked to graph - if(this.restrict?.[message.route]) return undefined; - return this.handleMethod(message.route, message.method, message.args); - } else if(message.route) { - if(this.restrict?.[message.route]) return undefined; - return this.handleServiceMessage(message); - } else if (message.node){ - if(typeof message.node === 'string' && this.restrict?.[message.node]) return undefined; - return this.handleGraphNodeCall(message.node, message.args); - } else if(this.__node.keepState) { - if(message.route) - this.setState({[message.route]:message.args}); - if(message.node) - this.setState({[message.node]:message.args}); - } - return undefined; + + if(typeof args[0] === 'object') { + if(args[0].method) { //run a route method directly, results not linked to graph + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if(args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node){ + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if(this.__node.keepState) { + if(args[0].route) + this.setState({[args[0].route]:args[0].args}); + if(args[0].node) + this.setState({[args[0].node]:args[0].args}); } - } - return undefined; + return args; + } else return args; }//these are fairly identical on the base template plus json parsing on the receive end //we may want to auto pipe outputs from a node through our frontend<-->backend service protocol @@ -225,16 +203,16 @@ export class Service extends Graph { callback?:(res:any)=>any|void ) => { if(source instanceof GraphNode) { - if(callback) return source.__node.state.subscribeEventOnce(source.__node.unique,(res)=>{ + if(callback) return source.__node.state.subscribeTriggerOnce(source.__node.unique,(res)=>{ let mod = callback(res); //either a modifier or a void function to do a thing before transmitting the data if(mod !== undefined) this.transmit({route:destination, args:mod, method}); else this.transmit({route:destination, args:res, method},endpoint); }) - else return this.__node.state.subscribeEventOnce(source.__node.unique,(res)=>{ + else return this.__node.state.subscribeTriggerOnce(source.__node.unique,(res)=>{ this.transmit({route:destination, args:res, method},endpoint); }); } else if(typeof source === 'string') - return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,(res)=>{ + return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,(res)=>{ this.transmit({route:destination, args:res, method},endpoint); }); } @@ -252,14 +230,6 @@ export class Service extends Graph { this.transmit(...args); return args; } - log = (...args:any)=>{ - console.log(...args); - return true; - } - error = (...args:any) => { - console.error(...args); - return true; - } } @@ -270,8 +240,8 @@ export function isTypedArray(x:any) { //https://stackoverflow.com/a/40319428 export const recursivelyAssign = (target,obj) => { for(const key in obj) { - if(obj[key]?.constructor.name === 'Object' && !Array.isArray(obj[key])) { - if(target[key]?.constructor.name === 'Object' && !Array.isArray(target[key])) recursivelyAssign(target[key], obj[key]); + if(typeof obj[key] === 'object' && !Array.isArray(obj[key])) { + if(typeof target[key] === 'object' && !Array.isArray(target[key])) recursivelyAssign(target[key], obj[key]); else target[key] = recursivelyAssign({},obj[key]); } else target[key] = obj[key]; } diff --git a/src/services/cmd/CMD.node.ts b/services/cmd/CMD.node.ts similarity index 92% rename from src/services/cmd/CMD.node.ts rename to services/cmd/CMD.node.ts index a9d4bf1b..24eefdd0 100644 --- a/src/services/cmd/CMD.node.ts +++ b/services/cmd/CMD.node.ts @@ -1,7 +1,7 @@ //for running parallel processes (with their own memory, as opposed to workers which share memory) in node.js import {ChildProcess, fork, Serializable, spawn} from 'child_process' import { Service, ServiceMessage, ServiceOptions } from '../Service'; -import { Graph, GraphNode, GraphNodeProperties } from '../../core/Graph'; +import { Graph, GraphNode, GraphNodeProperties } from '../../Graph'; import path from 'path'; //enable message passing between child processes. @@ -27,7 +27,7 @@ export type CMDInfo = { request:(message:ServiceMessage|any,method?:string) => Promise, post:(route:string, args:any, method?:string) => boolean, run:(route:any, args?:any, method?:string) => Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean) => number, + subscribe:(route:any, callback?:((res:any)=>void)|string) => number, unsubscribe:(route:any, sub:number) => Promise } & CMDRoute @@ -47,7 +47,7 @@ export class CMDService extends Service { } subprocessloader = { - 'process':(node: CMDRoute & GraphNode, parent: GraphNode, graph: Graph, roots:any, properties:any) => { + 'process':(node: CMDRoute & GraphNode, parent: GraphNode, graph: Graph, tree:any, properties:any) => { if((node as CMDRoute).command) { this.createProcess((node as CMDRoute)); } @@ -56,7 +56,7 @@ export class CMDService extends Service { constructor(options?:ServiceOptions) { super(options) - this.load(this); + this.setTree(this); this.connections.processes = this.processes; @@ -152,8 +152,8 @@ export class CMDService extends Service { } - newprocess.subscribe = (route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean) => { - return this.subscribeToProcess(route, newprocess._id, callback, args, key, subInput); + newprocess.subscribe = (route:any, callback?:((res:any)=>void)|string) => { + return this.subscribeToProcess(route, newprocess._id, callback); } newprocess.unsubscribe = (route:any, sub:number) => { @@ -226,8 +226,7 @@ export class CMDService extends Service { return res; } - subscribeProcess(route:string, childprocess:ChildProcess|string, args?:any[], key?:string, subInput?:boolean) { - if(this.restrict?.[route]) return undefined; + subscribeProcess(route:string, childprocess:ChildProcess|string,key?:string, subInput?:boolean) { if(typeof childprocess === 'string' && this.processes[childprocess]) { childprocess = this.processes[childprocess].process; } @@ -240,12 +239,12 @@ export class CMDService extends Service { } else { (childprocess as ChildProcess).send(JSON.stringify({args:res, callbackId:route})); } - },args,key,subInput); + },key,subInput); } - subscribeToProcess(route:string, processId:string, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean) { + subscribeToProcess(route:string, processId:string, callback?:((res:any)=>void)|string, key?:string, subInput?:boolean) { if(typeof processId === 'string' && this.processes[processId]) { - this.__node.state.subscribeEvent(processId, (res) => { + this.__node.state.subscribeTrigger(processId, (res) => { if(res?.callbackId === route) { if(!callback) this.setState({[processId]:res.args}); //just set state else if(typeof callback === 'string') { //run a local node @@ -254,7 +253,7 @@ export class CMDService extends Service { else callback(res.args); } }); - return this.processes[processId].request(JSON.stringify({route:'subscribeSocket', args:[route,processId,args,key,subInput]})); + return this.processes[processId].request(JSON.stringify({route:'subscribeSocket', args:[route,processId,key,subInput]})); } } diff --git a/src/services/cmd/childprocess.js b/services/cmd/childprocess.js similarity index 68% rename from src/services/cmd/childprocess.js rename to services/cmd/childprocess.js index 3f346950..8f19efe6 100644 --- a/src/services/cmd/childprocess.js +++ b/services/cmd/childprocess.js @@ -1,10 +1,10 @@ //stock child process that runs services import { CMDService } from "./CMD.node"; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; const service = new CMDService({ - routes:[remoteGraphRoutes] + routes:[unsafeRoutes] }); //now we can send/receive messages console.log("Child process listening...") \ No newline at end of file diff --git a/src/services/e2ee/E2EE.service.ts b/services/e2ee/E2EE.service.ts similarity index 98% rename from src/services/e2ee/E2EE.service.ts rename to services/e2ee/E2EE.service.ts index 460c79dd..4cc1bbf6 100644 --- a/src/services/e2ee/E2EE.service.ts +++ b/services/e2ee/E2EE.service.ts @@ -1,6 +1,6 @@ //End to end encryption using sjcl and keygen stuff, should involve webworkers -import { GraphNode } from "../../core/Graph"; +import { GraphNode } from "../../core/Graph2"; import { Service, ServiceMessage, ServiceOptions } from "../Service"; import sjcl from "./sjcl"; //stanford javascript cryptography library, super minimal! @@ -34,7 +34,7 @@ export class E2EEService extends Service { else Object.assign(this.keys,keys); } - this.load(this); + this.setTree(this); } addKey = ( diff --git a/services/e2ee/sjcl.d.ts b/services/e2ee/sjcl.d.ts new file mode 100644 index 00000000..2f1d140f --- /dev/null +++ b/services/e2ee/sjcl.d.ts @@ -0,0 +1,685 @@ +// Type definitions for sjcl v1.0.8 +// Project: http://crypto.stanford.edu/sjcl/ +// Definitions by: Eugene Chernyshov , Vytautas Mizgiris +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = sjcl; +export as namespace sjcl; + +declare namespace sjcl { + export var arrayBuffer: SjclArrayBufferModes; + export var bn: BigNumberStatic; + export var bitArray: BitArrayStatic; + export var codec: SjclCodecs; + export var hash: SjclHashes; + export var exception: SjclExceptions; + export var cipher: SjclCiphers; + export var mode: SjclModes; + export var misc: SjclMisc; + export var ecc: SjclEllipticCurveCryptography; + export var random: SjclRandom; + export var prng: SjclRandomStatic; + export var keyexchange: SjclKeyExchange; + export var json: SjclJson; + export var encrypt: SjclConvenienceEncryptor; + export var decrypt: SjclConvenienceDecryptor; + + // ________________________________________________________________________ + + interface BigNumber { + radix: number; + maxMul: number; + + copy(): BigNumber; + + /// Initializes this with it, either as a bn, a number, or a hex string. + initWith: TypeHelpers.BigNumberBinaryOperator; + + /// Returns true if "this" and "that" are equal. Calls fullReduce(). + /// Equality test is in constant time. + equals(that: BigNumber | number): boolean; + + /// Get the i'th limb of this, zero if i is too large. + getLimb(index: number): number; + + /// Constant time comparison function. + /// Returns 1 if this >= that, or zero otherwise. + greaterEquals(that: BigNumber | number): boolean; + + /// Convert to a hex string. + toString(): string; + + /// this += that. Does not normalize. + addM: TypeHelpers.BigNumberBinaryOperator; + + /// this *= 2. Requires normalized; ends up normalized. + doubleM(): BigNumber; + + /// this /= 2, rounded down. Requires normalized; ends up normalized. + halveM(): BigNumber; + + /// this -= that. Does not normalize. + subM: TypeHelpers.BigNumberBinaryOperator; + + mod: TypeHelpers.BigNumberBinaryOperator; + + /// return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. + inverseMod: TypeHelpers.BigNumberBinaryOperator; + + /// this + that. Does not normalize. + add: TypeHelpers.BigNumberBinaryOperator; + + /// this - that. Does not normalize. + sub: TypeHelpers.BigNumberBinaryOperator; + + /// this * that. Normalizes and reduces. + mul: TypeHelpers.BigNumberBinaryOperator; + + /// this ^ 2. Normalizes and reduces. + square(): BigNumber; + + /// this ^ n. Uses square-and-multiply. Normalizes and reduces. + power(n: BigNumber | number[] | number): BigNumber; + + /// this * that mod N + mulmod: TypeHelpers.BigNumberTrinaryOperator; + + /// this ^ x mod N + powermod: TypeHelpers.BigNumberTrinaryOperator; + + /// this ^ x mod N with Montomery reduction + montpowermod: TypeHelpers.BigNumberTrinaryOperator; + + trim(): BigNumber; + + /// Reduce mod a modulus. Stubbed for subclassing. + reduce(): BigNumber; + + /// Reduce and normalize. + fullReduce(): BigNumber; + + /// Propagate carries. + normalize(): BigNumber; + + /// Constant-time normalize. Does not allocate additional space. + cnormalize(): BigNumber; + + /// Serialize to a bit array + toBits(len?: number): BitArray; + + /// Return the length in bits, rounded up to the nearest byte. + bitLength(): number; + } + + interface BigNumberStatic { + new (): BigNumber; + new (n: BigNumber | number | string): BigNumber; + + fromBits(bits: BitArray): BigNumber; + random: TypeHelpers.Bind1; + prime: { + p127: PseudoMersennePrimeStatic; + // Bernstein's prime for Curve25519 + p25519: PseudoMersennePrimeStatic; + // Koblitz primes + p192k: PseudoMersennePrimeStatic; + p224k: PseudoMersennePrimeStatic; + p256k: PseudoMersennePrimeStatic; + // NIST primes + p192: PseudoMersennePrimeStatic; + p224: PseudoMersennePrimeStatic; + p256: PseudoMersennePrimeStatic; + p384: PseudoMersennePrimeStatic; + p521: PseudoMersennePrimeStatic; + }; + + pseudoMersennePrime(exponent: number, coeff: number[][]): PseudoMersennePrimeStatic; + } + + interface PseudoMersennePrime extends BigNumber { + reduce(): PseudoMersennePrime; + fullReduce(): PseudoMersennePrime; + inverse(): PseudoMersennePrime; + } + + interface PseudoMersennePrimeStatic extends BigNumberStatic { + new (): PseudoMersennePrime; + new (n: BigNumber | number | string): PseudoMersennePrime; + } + + // ________________________________________________________________________ + + interface BitArray extends Array {} + + interface BitArrayStatic { + /// Array slices in units of bits. + bitSlice(a: BitArray, bstart: number, bend: number): BitArray; + + /// Extract a number packed into a bit array. + extract(a: BitArray, bstart: number, blength: number): number; + + /// Concatenate two bit arrays. + concat(a1: BitArray, a2: BitArray): BitArray; + + /// Find the length of an array of bits. + bitLength(a: BitArray): number; + + /// Truncate an array. + clamp(a: BitArray, len: number): BitArray; + + /// Make a partial word for a bit array. + partial(len: number, x: number, _end?: number): number; + + /// Get the number of bits used by a partial word. + getPartial(x: number): number; + + /// Compare two arrays for equality in a predictable amount of time. + equal(a: BitArray, b: BitArray): boolean; + + /// Shift an array right. + _shiftRight(a: BitArray, shift: number, carry?: number, out?: BitArray): BitArray; + + /// xor a block of 4 words together. + _xor4(x: number[], y: number[]): number[]; + + /// byteswap a word array inplace. (does not handle partial words) + byteswapM(a: BitArray): BitArray; + } + + // ________________________________________________________________________ + + interface SjclCodec { + fromBits(bits: BitArray): T; + toBits(value: T): BitArray; + } + + interface SjclArrayBufferCodec extends SjclCodec { + fromBits(bits: BitArray, padding?: boolean, padding_count?: number): ArrayBuffer; + hexDumpBuffer(buffer: ArrayBuffer): void; + } + + interface SjclCodecs { + arrayBuffer: SjclArrayBufferCodec; + utf8String: SjclCodec; + hex: SjclCodec; + bytes: SjclCodec; + base32: SjclCodec; + base32hex: SjclCodec; + base64: SjclCodec; + base64url: SjclCodec; + z85: SjclCodec; + } + + // ________________________________________________________________________ + + interface SjclHash { + reset(): SjclHash; + update(data: BitArray | string): SjclHash; + finalize(): BitArray; + } + + interface SjclHashStatic { + new (hash?: SjclHash): SjclHash; + hash(data: BitArray | string): BitArray; + } + + interface SjclHashes { + sha1: SjclHashStatic; + sha256: SjclHashStatic; + sha512: SjclHashStatic; + ripemd160: SjclHashStatic; + } + + // ________________________________________________________________________ + + interface SjclExceptions { + corrupt: SjclExceptionFactory; + invalid: SjclExceptionFactory; + bug: SjclExceptionFactory; + notReady: SjclExceptionFactory; + } + + interface SjclExceptionFactory { + new (message: string): Error; + } + + // ________________________________________________________________________ + + interface SjclCiphers { + aes: SjclCipherStatic; + } + + interface SjclCipher { + encrypt(data: number[]): number[]; + decrypt(data: number[]): number[]; + } + + interface SjclCipherStatic { + new (key: number[]): SjclCipher; + } + + // ________________________________________________________________________ + + interface SjclModes { + gcm: SjclGCMMode; + ccm: SjclCCMMode; + ocb2: SjclOCB2Mode; + ocb2progressive: SjclOCB2ProgressiveMode; + cbc: SjclCBCMode; + ctr: SjclCTRMode; + } + + interface SjclArrayBufferModes { + ccm: SjclArrayBufferCCMMode; + } + + interface SjclGCMMode { + encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + } + + interface SjclArrayBufferCCMMode { + compat_encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + compat_decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + encrypt( + prf: SjclCipher, + plaintext_buffer: ArrayBuffer, + iv: BitArray, + adata?: ArrayBuffer, + tlen?: number, + ol?: number, + ): ArrayBuffer; + decrypt( + prf: SjclCipher, + ciphertext_buffer: ArrayBuffer, + iv: BitArray, + tag: BitArray, + adata?: ArrayBuffer, + tlen?: number, + ol?: number, + ): ArrayBuffer; + } + + interface SjclCCMMode { + listenProgress(cb: (val: number) => void): void; + unListenProgress(cb: (val: number) => void): void; + encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray; + } + + interface SjclOCB2Mode { + encrypt( + prf: SjclCipher, + plaintext: BitArray, + iv: BitArray, + adata?: BitArray, + tlen?: number, + premac?: boolean, + ): BitArray; + decrypt( + prf: SjclCipher, + ciphertext: BitArray, + iv: BitArray, + adata?: BitArray, + tlen?: number, + premac?: boolean, + ): BitArray; + pmac(prf: SjclCipher, adata: BitArray): number[]; + } + + interface SjclOCB2ProgressiveProcessor { + process(data: BitArray): BitArray; + finalize(): BitArray; + } + + interface SjclOCB2ProgressiveMode { + createEncryptor( + prp: SjclCipher, + iv: BitArray, + adata?: BitArray, + tlen?: number, + premac?: boolean, + ): SjclOCB2ProgressiveProcessor; + createDecryptor( + prp: SjclCipher, + iv: BitArray, + adata?: BitArray, + tlen?: number, + premac?: boolean, + ): SjclOCB2ProgressiveProcessor; + } + + interface SjclCBCMode { + encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + } + + interface SjclCTRMode { + encrypt(prf: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + decrypt(prf: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray; + } + + // ________________________________________________________________________ + + interface PBKDF2Params { + iter?: number | undefined; + salt?: BitArray | undefined; + } + + interface SjclMisc { + pbkdf2( + password: BitArray | string, + salt: BitArray | string, + count?: number, + length?: number, + Prff?: SjclPRFFamilyStatic, + ): BitArray; + hmac: SjclHMACStatic; + cachedPbkdf2( + password: string, + obj?: PBKDF2Params, + ): { + key: BitArray; + salt: BitArray; + }; + hkdf( + ikm: BitArray, + keyBitLength: number, + salt: BitArray | string, + info: BitArray | string, + Hash?: SjclHashStatic, + ): BitArray; + scrypt( + password: BitArray | string, + salt: BitArray | string, + N?: number, + r?: number, + p?: number, + length?: number, + Prff?: SjclPRFFamilyStatic, + ): BitArray; + } + + class SjclPRFFamily { + encrypt(data: BitArray | string): BitArray; + } + + interface SjclHMAC extends SjclPRFFamily { + mac(data: BitArray | string): BitArray; + reset(): void; + update(data: BitArray | string): void; + digest(): BitArray; + } + + interface SjclPRFFamilyStatic { + new (key: BitArray): SjclPRFFamily; + } + + interface SjclHMACStatic { + new (key: BitArray, Hash?: SjclHashStatic): SjclHMAC; + } + + // ________________________________________________________________________ + + interface SjclEllipticCurveCryptography { + point: SjclEllipticalPointStatic; + pointJac: SjclPointJacobianStatic; + curve: SjclEllipticalCurveStatic; + curves: { + c192: SjclEllipticalCurve; + c224: SjclEllipticalCurve; + c256: SjclEllipticalCurve; + c384: SjclEllipticalCurve; + c521: SjclEllipticalCurve; + k192: SjclEllipticalCurve; + k224: SjclEllipticalCurve; + k256: SjclEllipticalCurve; + }; + curveName(curve: SjclEllipticalCurve): string; + deserialize(key: SjclECCKeyPairData): SjclECCPublicKey; + deserialize(key: SjclECCKeyPairData): SjclECCSecretKey; + basicKey: SjclECCBasic; + elGamal: SjclElGamal; + ecdsa: SjclECDSA; + } + + interface SjclEllipticalPoint { + toJac(): SjclPointJacobian; + mult(k: BigNumber): SjclEllipticalPoint; + mult2(k: BigNumber, k2: BigNumber, affine2: SjclEllipticalPoint): SjclEllipticalPoint; + multiples(): Array; + negate(): SjclEllipticalPoint; + isValid(): boolean; + toBits(): BitArray; + } + + interface SjclEllipticalPointStatic { + new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber): SjclEllipticalPoint; + } + + interface SjclPointJacobian { + add(T: SjclEllipticalPoint): SjclPointJacobian; + doubl(): SjclPointJacobian; + toAffine(): SjclEllipticalPoint; + mult(k: BigNumber, affine: SjclEllipticalPoint): SjclPointJacobian; + mult2( + k1: BigNumber, + affine: SjclEllipticalPoint, + k2: BigNumber, + affine2: SjclEllipticalPoint, + ): SjclPointJacobian; + negate(): SjclPointJacobian; + isValid(): boolean; + } + + interface SjclPointJacobianStatic { + new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber, z?: BigNumber): SjclPointJacobian; + toAffineMultiple(points: Array): Array; + } + + interface SjclEllipticalCurve { + fromBits(bits: BitArray): SjclEllipticalPoint; + } + + interface SjclEllipticalCurveStatic { + new ( + Field: BigNumber, + r: BigNumber, + a: BigNumber, + b: BigNumber, + x: BigNumber, + y: BigNumber, + ): SjclEllipticalCurve; + } + + interface SjclKeyPair

{ + pub: P; + sec: S; + } + + interface SjclKeysGenerator

{ + (curve: SjclEllipticalCurve | number, paranoia: number, sec?: BigNumber): SjclKeyPair; + } + + interface SjclECCKeyPairData { + type: string; + secretKey: boolean; + point: string; + curve: string; + } + + interface SjclECCPublicKeyData { + x: BitArray; + y: BitArray; + } + + class SjclECCPublicKey { + serialize(): SjclECCKeyPairData; + get(): SjclECCPublicKeyData; + getType(): string; + } + + class SjclECCSecretKey { + serialize(): SjclECCKeyPairData; + get(): BitArray; + getType(): string; + } + + interface SjclECCPublicKeyFactory { + new (curve: SjclEllipticalCurve, point: SjclEllipticalPoint | BitArray): T; + } + + interface SjclECCSecretKeyFactory { + new (curve: SjclEllipticalCurve, exponent: BigNumber): T; + } + + interface SjclECCBasic { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys(cn: string): SjclKeysGenerator; + } + + class SjclElGamalPublicKey extends SjclECCPublicKey { + kem( + paranoia: number, + ): { + key: BitArray; + tag: BitArray; + }; + } + + class SjclElGamalSecretKey extends SjclECCSecretKey { + unkem(tag: BitArray): BitArray; + dh(pk: SjclECCPublicKey): BitArray; + dhJavaEc(pk: SjclECCPublicKey): BitArray; + } + + interface SjclElGamal { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys: SjclKeysGenerator; + } + + class SjclECDSAPublicKey extends SjclECCPublicKey { + verify(hash: BitArray, rs: BitArray, fakeLegacyVersion: boolean): boolean; + } + + class SjclECDSASecretKey extends SjclECCSecretKey { + sign(hash: BitArray, paranoia: number, fakeLegacyVersion: boolean, fixedKForTesting?: BigNumber): BitArray; + } + + interface SjclECDSA { + publicKey: SjclECCPublicKeyFactory; + secretKey: SjclECCSecretKeyFactory; + generateKeys: SjclKeysGenerator; + } + + // ________________________________________________________________________ + + interface SjclRandom { + randomWords(nwords: number, paranoia?: number): BitArray; + setDefaultParanoia(paranoia: number, allowZeroParanoia: string): void; + addEntropy(data: number | number[] | string, estimatedEntropy: number, source: string): void; + isReady(paranoia?: number): boolean; + getProgress(paranoia?: number): number; + startCollectors(): void; + stopCollectors(): void; + addEventListener(name: string, cb: Function): void; + removeEventListener(name: string, cb: Function): void; + } + + interface SjclRandomStatic { + new (defaultParanoia: number): SjclRandom; + } + + // ________________________________________________________________________ + + interface SjclKeyExchange { + srp: SjclSecureRemotePassword; + } + + interface SjclSRPGroup { + N: BigNumber; + g: BigNumber; + } + + interface SjclSecureRemotePassword { + makeVerifier(username: string, password: string, salt: BitArray, group: SjclSRPGroup): BitArray; + makeX(username: string, password: string, salt: BitArray): BitArray; + knownGroup(i: number | string): SjclSRPGroup; + } + + // ________________________________________________________________________ + + interface SjclCipherParams { + v?: number | undefined; + iter?: number | undefined; + ks?: number | undefined; + ts?: number | undefined; + mode?: string | undefined; + adata?: string | undefined; + cipher?: string | undefined; + } + + interface SjclCipherEncryptParams extends SjclCipherParams { + salt: BitArray; + iv: BitArray; + } + + interface SjclCipherDecryptParams extends SjclCipherParams { + salt?: BitArray | undefined; + iv?: BitArray | undefined; + } + + interface SjclCipherEncrypted extends SjclCipherEncryptParams { + kemtag?: BitArray | undefined; + ct: BitArray; + } + + interface SjclCipherDecrypted extends SjclCipherEncrypted { + key: BitArray; + } + + interface SjclConvenienceEncryptor { + ( + password: SjclElGamalPublicKey | BitArray | string, + plaintext: string, + params?: SjclCipherEncryptParams, + rp?: SjclCipherEncrypted, + ): SjclCipherEncrypted; + } + + interface SjclConvenienceDecryptor { + ( + password: SjclElGamalSecretKey | BitArray | string, + ciphertext: SjclCipherEncrypted | string, + params?: SjclCipherDecryptParams, + rp?: SjclCipherDecrypted, + ): string; + } + + interface SjclJson { + encrypt: SjclConvenienceEncryptor; + decrypt: SjclConvenienceDecryptor; + encode(obj: Object): string; + decode(obj: string): Object; + } + + // ________________________________________________________________________ + + namespace TypeHelpers { + interface One { + (value: T): BigNumber; + } + + interface BigNumberBinaryOperator extends One, One, One {} + + interface Two { + (x: T1, N: T2): BigNumber; + } + + interface Bind1 extends Two, Two, Two {} + + interface BigNumberTrinaryOperator extends Bind1, Bind1, Bind1 {} + } +} diff --git a/src/services/e2ee/sjcl.js b/services/e2ee/sjcl.js similarity index 99% rename from src/services/e2ee/sjcl.js rename to services/e2ee/sjcl.js index f7ee4499..c3c3ea97 100644 --- a/src/services/e2ee/sjcl.js +++ b/services/e2ee/sjcl.js @@ -57,8 +57,4 @@ b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c Promise) { super(options); - this.load(this); + this.setTree(this); this.listen(path,fetched); } @@ -87,7 +87,7 @@ export class HTTPfrontend extends Service { type:XMLHttpRequestResponseType='', mimeType?:string|undefined ) => { - if(typeof message === 'object' && !message.byteLength && (type === 'json' || type === 'text' || !type)) { + if(typeof message === 'object' && (type === 'json' || type === 'text' || !type)) { message = JSON.stringify(message); } @@ -118,7 +118,7 @@ export class HTTPfrontend extends Service { url:string|URL ) => { let obj = message; - if(typeof obj === 'object' && !obj.byteLength) { + if(typeof obj === 'object') { message = JSON.stringify(obj); } if(obj?.method?.toLowerCase() == 'get' || message?.toLowerCase() === 'get') return this.GET(url); diff --git a/services/http/HTTP.node.ts b/services/http/HTTP.node.ts new file mode 100644 index 00000000..d360f8ff --- /dev/null +++ b/services/http/HTTP.node.ts @@ -0,0 +1,977 @@ +import { Service, ServiceMessage, ServiceOptions } from "../Service"; +import * as http from 'http' +import * as https from 'https' +import * as fs from 'fs' +import * as path from 'path' +import { GraphNode, GraphNodeProperties } from "../../Graph"; + + +export type ServerProps = { + host:string, + port:number, + certpath?:string, + keypath?:string, + passphrase?:string, + startpage?: string, + errpage?:string, + pages?:{ + [key:'all'|string]:string|{ //objects get loaded as nodes which you can modify props on + template?:string, + onrequest?:GraphNode|string|((self:HTTPbackend, node:GraphNode, request:http.IncomingMessage, response:http.ServerResponse)=>void), //run a function or node? the template, request and response are passed as arguments, you can write custom node logic within this function to customize inputs etc. + redirect?:string, // can redirect the url to call a different route instead, e.g. '/':{redirect:'home'} sets the route passed to the receiver as 'home' + inject?:{[key:string]:{}|null}|string[]|string| ((...args:any)=>any) //append html + } & GraphNodeProperties + }, + protocol?:'http'|'https', + type?:'httpserver'|string, + keepState?:boolean, //setState whenever a route is run? State will be available at the address (same key of the object storing it here) + onopen?:(served:ServerInfo)=>void, //onopen callback + onclose?:(served:ServerInfo)=>void, //server close callback + _id?:string, + [key:string]:any +} + +export type ServerInfo = { + server:https.Server|http.Server, + address:string, + terminate:()=>void, + graph:HTTPbackend, + _id:string +} & ServerProps + +export type ReqOptions = { + protocol:'http'|'https'|string + host:string, + port:number, + method:string, + path?:string, + headers?:{ + [key:string]:any, + 'Content-Type'?:string, //e.g... + 'Content-Length'?:number + } +} + +//http/s server +export class HTTPbackend extends Service { + + name='http'; + + server:any + + debug:boolean=false + + servers:{ + [key:string]:ServerInfo + }={} + + mimeTypes:{[key:string]:string} = { + '.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.txt':'text/plain', + '.png': 'image/png', '.jpg': 'image/jpg', '.jpeg': 'image/jpg','.gif': 'image/gif', '.svg': 'image/svg+xml', '.xhtml':'application/xhtml+xml', '.bmp':'image/bmp', + '.wav': 'audio/wav', '.mp3':'audio/mpeg', '.mp4': 'video/mp4', '.xml':'application/xml', '.webm':'video/webm', '.webp':'image/webp', '.weba':'audio/webm', + '.woff': 'font/woff', 'woff2':'font/woff2', '.ttf': 'application/font-ttf', '.eot': 'application/vnd.ms-fontobject', '.otf': 'application/font-otf', + '.wasm': 'application/wasm', '.zip':'application/zip','.xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.tif':'image/tiff', + '.sh':'application/x-sh', '.csh':'application/x-csh', '.rar':'application/vnd.rar','.ppt':'application/vnd.ms-powerpoint', '.pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation', + '.odt':'application/vnd.oasis.opendocument.text','.ods':'application/vnd.oasis.opendocument.spreadsheet','.odp':'application/vnd.oasis.opendocument.presentation', + '.mpeg':'video/mpeg','.mjs':'text/javascript','.cjs':'text/javascript','.jsonld':'application/ld+json', '.jar':'application/java-archive', '.ico':'image/vnd.microsoft.icon', + '.gz':'application/gzip', 'epub':'application/epub+zip', '.doc':'application/msword', '.docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + '.csv':'text/csv', '.avi':'video/x-msvideo', '.aac':'audio/aac', '.mpkg':'application/vnd.apple.installer+xml','.oga':'audio/ogg','.ogv':'video/ogg','ogx':'application/ogg', + '.php':'application/x-httpd-php', '.rtf':'application/rtf', '.swf':'application/x-shockwave-flash', '.7z':'application/x-7z-compressed', '.3gp':'video/3gpp' + }; + + constructor( + options?:ServiceOptions, + settings?:{ host?:string, port?:number, protocol?:'http'|'https', certpath?:string, keypath?:string } + ) { + super(options); + this.setTree(this); + + //console.log(settings); + if(settings) { + if(settings.protocol === 'https') { + this.setupHTTPSserver( settings as any ) + } else this.setupHTTPserver( settings as any); + } + + } + + //on server started + onStarted = (protocol:'http'|'https'|string,host:string,port:number) => { + console.log(`🐱 Node server running at + ${protocol}://${host}:${port}/` + ); + } + + setupServer = ( + options:ServerProps={ + protocol:'http', + host:'localhost', + port:8080, + startpage:'index.html' + }, + requestListener?:http.RequestListener, + onStarted?:()=>void + )=>{ + //console.log(options); + if(options.pages) { + for(const key in options.pages) { + if (typeof options.pages[key] === 'string') { + this.addPage(`${options.port}/${key}`,options.pages[key] as string) + } else if (typeof options.pages[key] === 'object') { + if((options.pages[key] as any).template) { + (options.pages[key] as any).get = (options.pages[key] as any).template; + } + if(key !== '_all') this.setTree({[`${options.port}/${key}`]:options.pages[key]}); + } + } + } + + if(options.protocol === 'https') { + return this.setupHTTPSserver(options as any, requestListener, onStarted); + } + else + return this.setupHTTPserver(options, requestListener, onStarted); + } + + open = this.setupServer; + + //insecure server + setupHTTPserver = ( + options:ServerProps={ + host:'localhost' as string, + port:8080 as number, + startpage:'index.html', + errpage:undefined + }, + requestListener?:http.RequestListener, + onStarted:()=>void = ()=>{this.onStarted('http',options.host,options.port)} + ) => { + + const host = options.host; + const port = options.port; + options.protocol = 'http'; + + if(!host || !port) return; + + const address = `${host}:${port}`; + + if(this.servers[address]) this.terminate(this.servers[address]); + + if(!('keepState' in options)) options.keepState = true; //default true + + const served = { + server:undefined as any, + type:'httpserver', + address, + ...options + } as ServerInfo + + if(!requestListener) requestListener = (request:http.IncomingMessage,response:http.ServerResponse) => { + + let received:any = { + args:{request, response}, + method:request.method, + served + } + + let url = (request as any).url.slice(1); + if(!url) url = '/'; + //console.log(options) + if(options.pages) { + if(typeof options.pages[url] === 'object') { + if((options.pages[url] as any).onrequest) { + if(typeof (options.pages[url] as any).onrequest === 'string') { + (options.pages[url] as any).onrequest = this.__node.nodes.get((url).onrequest); + } + if(typeof (options.pages[url] as any).onrequest === 'object') { + if((options.pages[url] as any).onrequest.__operator) { + ((options.pages[url] as any).onrequest as GraphNode).__operator(options.pages[url], request, response); + } + } else if(typeof (options.pages[url] as any).onrequest === 'function') { + (options.pages[url] as any).onrequest(this, this.__node.nodes.get(options.port + '/' + url), request, response); + } + } + if((options.pages[url] as any).redirect) { + url = (options.pages[url] as any).redirect; + received.redirect = url; + } + } + } + received.route = url; + this.receive(received); + } //default requestListener + + //var http = require('http'); + const server = http.createServer( + requestListener + ); + + served.server = server; + served.terminate = () => { + this.terminate(served); + } + served.service = this; + + // server.on('upgrade', (request, socket, head) => { + // this.onUpgrade(request, socket, head); + // }); + + this.servers[address] = served; + served._id = options._id ? options._id : address; + + //SITE AVAILABLE ON PORT: + return new Promise((resolve,reject) => { + server.on('error',(err)=>{ + console.error('Server error:', err.toString()); + reject(err); + }); + server.listen( + port,host, + ()=>{ + onStarted(); + if(served.onopen) served.onopen(served); + resolve(served); + } + ); + }) as Promise ; + } + + //secure server + setupHTTPSserver = ( + options:ServerProps = { + host:'localhost' as string, + port:8080 as number, + startpage:'index.html', + certpath:'cert.pem' as string, + keypath:'key.pem' as string, + passphrase:'encryption' as string, + errpage:undefined as undefined|string + }, + requestListener?:http.RequestListener, + onStarted:()=>void = ()=>{this.onStarted('https',options.host,options.port)} + ) => { + + const host = options.host; + const port = options.port; + options.protocol = 'https'; + + if(!host || !port || !options.certpath || !options.keypath) return; + + if(this.servers[`${host}:${port}`]) this.terminate(this.servers[`${host}:${port}`]) + + var opts = { + key: fs.readFileSync(options.keypath), + cert: fs.readFileSync(options.certpath), + passphrase:options.passphrase + }; + + if(!('keepState' in options)) options.keepState = true; //default true + + const address = `${host}:${port}`; + + const served = { + server:undefined as any, + type:'httpserver', + address, + ...options + } as ServerInfo; + + //default requestListener + if(!requestListener) requestListener = (request:http.IncomingMessage,response:http.ServerResponse) => { + + let received:any = { + args:{request, response}, + method:request.method, + served + } + + let url = (request as any).url.slice(1); + if(!url) url = '/'; + if(options.pages) { + if(typeof options.pages[url] === 'object') { + if((options.pages[url] as any).redirect) { + url = (options.pages[url] as any).redirect; + received.redirect = url; + } + if((options.pages[url] as any).onrequest) { + if(typeof (options.pages[url] as any).onrequest === 'string') { + (options.pages[url] as any).onrequest = this.__node.nodes.get((options.pages[url] as any).onrequest); + } + if(typeof (options.pages[url] as any).onrequest === 'object') { + if((options.pages[url] as any).onrequest.__operator) { + ((options.pages[url] as any).onrequest as GraphNode).__operator(options.pages[url], request, response); + } + } else if(typeof (options.pages[url] as any).onrequest === 'function') { + (options.pages[url] as any).onrequest(this,options.pages[url], request, response); + } + } + } + } + received.route = url; + this.receive(received); + } //default requestListener + + + //var http = require('http'); + const server = https.createServer( + opts, + requestListener + ); + + served.server = server; + served.terminate = () => { + this.terminate(served); + } + served.service = this; + + // server.on('upgrade', (request, socket, head) => { + // this.onUpgrade(request, socket, head); + // }); + + this.servers[address] = served; + served._id = options._id ? options._id : address; + + //SITE AVAILABLE ON PORT: + return new Promise((resolve,reject) => { + server.on('error',(err)=>{ + console.error('Server error:', err.toString()); + reject(err); + }) + server.listen( + port,host, + ()=>{ + onStarted(); + if(served.onopen) served.onopen(served); + resolve(served); + } + ); + }) as Promise; + } + + transmit = ( //generalized http request. The default will try to post back to the first server in the list + message:any | ServiceMessage, + options:string|{ + protocol:'http'|'https'|string + host:string, + port:number, + method:string, + path?:string, + headers?:{ + [key:string]:any, + 'Content-Type'?:string, + 'Content-Length'?:number + } + }, + ondata?:(chunk:any)=>void, + onend?:()=>void + + ) => { + let input = message; + if(typeof input === 'object') input = JSON.stringify(input); + + if(typeof options === 'string' && message) return this.POST(options,message); + else if(typeof options === 'string') return this.GET(options); + + if(!options) { //fill a generic post request for the first server if none provided + let server = this.servers[Object.keys(this.servers)[0]]; + options = { + protocol:server.protocol as any, + host:server.host, + port:server.port, + method:'POST', + path:message.route, + headers:{ + 'Content-Type':'application/json', + 'Content-Length':input.length + } + }; + } //get first server and use its settings for a generic post request + else if (!options.headers) { + options.headers = { + 'Content-Type':'application/json', + 'Content-Length':input.length + } + } + + return this.request(options,input,ondata,onend); + } + + withResult = ( + response:http.ServerResponse, + result:any, + message:{ + route:string, + args:{request:http.IncomingMessage,response:http.ServerResponse}, //data will be an object containing request, response + method?:string, + served?:ServerInfo //server deets + } + ) => { + if(result && !response.writableEnded && !response.destroyed) { + + let mimeType = 'text/plain'; + + if(typeof result === 'string') { + let extname = path.extname(result); + + if(extname && fs.existsSync(path.join(process.cwd(),result))) { //load file paths if returned + mimeType = this.mimeTypes[extname] || 'application/octet-stream'; + + result = fs.readFileSync(path.join(process.cwd(),result)); + + if(mimeType === 'text/html' && (message.served?.pages?._all || message.served?.pages?.[message.route])) { + result = this.injectPageCode(result.toString(),message.route,message.served as any) as any; + } + } + if(typeof result === 'string' && result.includes('<') && result.includes('>') && (result.indexOf('<') < result.indexOf('>'))) //probably an html template + { + if(message?.served?.pages?._all || message?.served?.pages?.[message.route]) { + result = this.injectPageCode(result,message.route,message.served) as any; + } + response.writeHead(200,{'Content-Type':'text/html'}); + response.end(result,'utf-8'); + return; + } + } else if(typeof result === 'object') { + result = JSON.stringify(result); + mimeType = 'application/json' + } + + response.writeHead(200,{'Content-Type':mimeType}); + response.end(result,'utf-8'); + } + } + + injectPageCode = ( + templateString:string, + url:string, + served:ServerInfo + ) => { + + if ((served?.pages?.[url] as any)?.inject) { //inject per url + if(typeof (served as any).pages[url].inject === 'object') + templateString = this.buildPage((served as any).pages[url].inject as any, templateString); + else if (typeof (served as any).pages[url].inject === 'function') + templateString += ((served as any).pages[url].inject as any)(); + else if (typeof (served as any).pages[url].inject === 'string' || typeof (served as any).pages[url].inject === 'number') + templateString += (served as any).pages[url].inject; + } + if((served?.pages?._all as any)?.inject) { //any per server + if(typeof (served.pages as any)._all.inject === 'object') + templateString = this.buildPage((served as any).pages._all.inject, templateString); + else if (typeof (served as any).pages._all.inject === 'function') + templateString += (served as any).pages._all.inject(); + else if (typeof (served as any).pages._all.inject === 'string' || typeof (served as any).pages._all.inject === 'number') + templateString += (served as any).pages._all.inject; + } + + return templateString; + } + + receive = ( //our fancy request response handler + message:{ + route:string, + args:{request:http.IncomingMessage,response:http.ServerResponse}, //data will be an object containing request, response + method?:string, + node?:string, // alt for route + served?:ServerInfo, //server deets + redirect?:string //if we redirected the route according to page options + } + ) => { + const request = message.args.request; + const response = message.args.response; + const method = message.method; + const served = message.served; + + if(this.debug) console.log(request.method, request.url); + //console.log(request); //debug + + let result = new Promise((resolve,reject) => { + + response.on('error', (err) => { + if(!response.writableEnded || !response.destroyed ) { + response.statusCode = 400; + response.end(undefined,undefined as any,()=>{ + reject(err); + }); + } + }); + + let getFailed = () => { + if(response.writableEnded || response.destroyed) reject(requestURL); + if(requestURL == './' || requestURL == served?.startpage) { + let template = `

Brains@Play Server

`; //start page dummy + if(served?.pages?._all || served?.pages?.error) { + template = this.injectPageCode(template,message.route,served) as any; + } + response.writeHead(200, { 'Content-Type': 'text/html' }); + response.end(template,'utf-8',() => { + resolve(template); + }); //write some boilerplate server page, we should make this an interactive debug page + if(served?.keepState) this.setState({[served.address]:template}); + //return; + } + else if(this.debug) console.log(`File ${requestURL} does not exist on path!`); + response.writeHead(500); //set response headers + response.end(undefined,undefined as any,()=>{ + reject(requestURL); + }); + + //return; + } + + if(method === 'GET' || method === 'get') { + //process the request, in this case simply reading a file based on the request url + var requestURL = '.' + request.url; + + if (requestURL == './' && served?.startpage) { //root should point to start page + requestURL = served.startpage; //point to the start page + } + + if((request.url !== '/' || served?.startpage) && fs.existsSync(path.join(process.cwd(),requestURL))) { + + if(response.writableEnded || response.destroyed) reject(requestURL); + //read the file on the server + fs.readFile(path.join(process.cwd(),requestURL), (error, content) => { + if (error) { + if(error.code == 'ENOENT') { //page not found: 404 + if(served?.errpage) { + fs.readFile(served.errpage, (er, content) => { + response.writeHead(404, { 'Content-Type': 'text/html' }); //set response headers + + + //add hot reload if specified + // if(process.env.HOTRELOAD && requestURL.endsWith('.html') && cfg.hotreload) { + // content = addHotReloadClient(content,`${cfg.socket_protocol}://${cfg.host}:${cfg.port}/hotreload`); + // } + + if(served.pages?._all || served.pages?.error) { + content = this.injectPageCode(content.toString(),message.route,served) as any; + } + + response.end(content, 'utf-8'); //set response content + reject(content); + //console.log(content); //debug + }); + } + else { + response.writeHead(404, { 'Content-Type': 'text/html' }); + let content = `

Error: ${error.code}

` + if(served?.pages?._all || served?.pages?.[message.route]) { + content = this.injectPageCode(content.toString(),message.route,served as any) as any; + } + response.end(content,'utf-8', () => { + reject(error.code); + }); + //return; + } + } + else { //other error + response.writeHead(500); //set response headers + response.end('Something went wrong: '+error.code+' ..\n','utf-8', () => { + reject(error.code); + }); //set response content + //return; + } + } + else { //file read successfully, serve the content back + + //set content type based on file path extension for the browser to read it properly + var extname = String(path.extname(requestURL)).toLowerCase(); + + var contentType = this.mimeTypes[extname] || 'application/octet-stream'; + + if(contentType === 'text/html' && (served?.pages?._all || served?.pages?.[message.route])) { + content = this.injectPageCode(content.toString(),message.route,served as any) as any; + } + + response.writeHead(200, { 'Content-Type': contentType }); //set response headers + response.end(content, 'utf-8', () => { + //console.log(response,content,contentType); + resolve(content); + }); //set response content + + //console.log(content); //debug + //return; + } + }); + } else if (message.route) { + let route; + if(served) { + let rt = `${served.port}/${message.route}`; + if(this.__node.nodes.get(rt)) route = rt + } + if(!route && this.__node.nodes.get(message.route)) route = message.route; + + if(route) { + let res:any; + if(message.method) { + res = this.handleMethod(route, message.method, undefined); //these methods are being passed request/response in the data here, post methods will parse the command objects instead while this can be used to get html templates or play with req/res custom callbakcs + } + else if (message.node) { + res = this.handleGraphNodeCall(message.node, undefined); + } + else res = this.handleServiceMessage({route,args:undefined,method:message.method}); + + if(res instanceof Promise) res.then((r) => { + if(served?.keepState) this.setState({[served.address]:res}); + this.withResult(response,r,message); + resolve(res); + + //return; + }) + else if(res) { + if(served?.keepState) this.setState({[served.address]:res}); + this.withResult(response,res,message); + resolve(res); + // return; + } //else we can move on to check the get post + } + else if (message.redirect) { + response.writeHead(301, {'Location':message.redirect}); + response.end(); + resolve(true); + } + else getFailed(); + } else getFailed(); + } else { + //get post/put/etc body if any + let body:any = []; + request.on('data',(chunk)=>{ //https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ + body.push(chunk); + }).on('end',() => { + body = Buffer.concat(body).toString(); //now it's a string + + if(typeof body === 'string') { + let substr = body.substring(0,8); + if(substr.includes('{') || substr.includes('[')) { + if(substr.includes('\\')) body = body.replace(/\\/g,""); + if(body[0] === '"') { body = body.substring(1,body.length-1)}; + body = JSON.parse(body); //parse stringified args, this is safer in a step + } + } + + let route,method,args; + if(body?.route){ //if arguments were posted + route = this.__node.tree[body.route]; + method = body.method; + args = body.args; + if(!route) { + if(typeof body.route === 'string') if(body.route.includes('/') && body.route.length > 1) body.route = body.route.split('/').pop(); + route = this.__node.tree[body.route]; + } + } + if(!route) { //body post did not provide argument so use the request route + if (message?.route) { + let route = this.__node.tree[message.route]; + method = message.method; + args = message.args; + if(!route) { + if(typeof message.route === 'string') if(message.route.includes('/') && message.route.length > 1) message.route = message.route.split('/').pop() as string; + route = this.__node.tree[message.route]; + } + } + } + let res:any = body; + if(route) { + if(body.method) { + res = this.handleMethod(route, method, args); + } + else if (body.node) { + res = this.handleGraphNodeCall(body.node, body.args); + } + else res = this.handleServiceMessage({route, args:args, method:method}); + + if(res instanceof Promise) { + res.then((r) => { + this.withResult(response,r,message); + if(served?.keepState) this.setState({[served.address]:res}); + resolve(res); + }); + } else { + this.withResult(response,res,message); + if(served?.keepState) this.setState({[served.address]:res}); + resolve(res); + } + } + else if(!response.writableEnded || !response.destroyed) { + response.statusCode = 200; + response.end(undefined,undefined as any, () => { + resolve(res); + }); //posts etc. shouldn't return anything but a 200 usually + } else resolve(res); //get requests resolve first and return otherwise this will resolve + }); + + } + + + }).catch((er)=>{ console.error("Request Error:", er); }); + + return result; + } + + request = ( + options:ReqOptions|any, + send?:any, + ondata?:(chunk:any)=>void, + onend?:()=>void + ) => { + + let client = http; + + if ((options.protocol as string)?.includes('https')) { + client = https as any; + } + + delete options.protocol; + + const req = client.request(options,(res)=>{ + if(ondata) res.on('data',ondata) + if(onend) res.on('end',onend); + }); + + if(options.headers) { + for(const head in options.headers) { + req.setHeader(head,options.headers[head]) + } + } + + if(send) req.write(send); + req.end(); + + return req; + } + + POST = ( + url:string|URL, + data:any, + headers?:{ + 'Content-Type'?:string, + 'Content-Length'?:number, + [key:string]:any + } + ) => { + + let urlstring = url; + if(urlstring instanceof URL) urlstring = url.toString(); + let protocol = urlstring.startsWith('https') ? 'https' : 'http'; + let host, port,path; + let split = urlstring.split('/'); + split.forEach((s) => { + if(s.includes(':')) { + let ss = s.split(':'); + host = ss[0]; port = ss[1]; + } + }); + + if(split.length > 3) { + path = split.slice(3).join('/'); + } + + let req = this.request( + { + protocol, + host, + port, + path, + method:'POST', + headers + }, + data + ); + + return req; + } + + GET = (url:string|URL|http.RequestOptions) => { + return new Promise((resolve, reject) => { + + let client = http; + + let urlstring = url; + if(url instanceof URL) urlstring = url.toString(); + + if ((urlstring as string).includes('https')) { + client = https as any; + } + + client.get(url, (resp) => { + let chunks:any[] = []; + + // A chunk of data has been recieved. + resp.on('data', (chunk) => { + chunks.push(chunk); + }); + + // The whole response has been received. Print out the result. + resp.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + + }).on("error", (err) => { + reject(err); + }); + }); + } + + terminate = (served:string|ServerInfo) => { + if(typeof served === 'string') served = this.servers[served]; + + if(typeof served === 'object') { + served.server.close(); + if(served.onclose) served.onclose(served); + } + } + + getRequestBody(req:http.IncomingMessage) { + let chunks:any[] = []; + return new Promise((resolve,reject) => { + req.on('data',(chunk) => { + chunks.push(chunk); + }).on('end',() => { + resolve(Buffer.concat(chunks)); + }).on('error',(er)=>{ + reject(er); + }) + }); + } + + //??? just need a way to pass a fake request/response in + // spoofRequest = (url:string, body:any, type:string='json', server:http.Server|https.Server) => { + // return this.receive({ + // route:url, + // args:{request:{ + // url, + // } as http.IncomingMessage, response:{} as http.ServerResponse}, + // method:'GET' + // }) + // } + + addPage = (path:string, template:string) => { //add an html page template as a get + if(typeof template === 'string') { + if(!template.includes(''; //add a root + } + if(typeof this.__node.tree[path] === 'object') { + (this.__node.tree[path] as any).get = template; + this.__node.nodes.get(path).get = template; + } + else this.setTree({ + [path]: { + get:template + } + }); + } + + addHTML = (path:string, template:string) => { //add an html component template e.g. route: component/button then set up logic to chain + if(typeof template === 'string') { + if(!template.includes('<') || (!template.includes('>'))) template = '
'+template+'
'; + } + if(typeof this.__node.tree[path] === 'object') { + (this.__node.tree[path] as any).get = template; + this.__node.nodes.get(path).get = template; + } + else this.setTree({ + [path]: { + get:template + } + }); + } + + buildPage = (pageStructure:{[key:string]:{}|null|any} | string[] | string | ((...args:any)=>any), baseTemplate:string) => { //construct a page from available components, child component templates will be inserted before the last '<' symbol or at end of the previous string depending + let result = ``; if(baseTemplate) result += baseTemplate; + let appendTemplate = (obj:{[key:string]:{}|null|any}|string[],r:string|any, res:string) => { + if(typeof obj[r] === 'object') { + for(const key in obj) { + appendTemplate(obj,key,res); //recursive append + } + } else if(this.__node.tree[r]?.get) { + let toAdd = this.__node.tree[r]?.get; + if(typeof toAdd === 'function') toAdd = toAdd(obj[r]); + if(typeof toAdd === 'string') { + let lastDiv = res.lastIndexOf('<'); + if(lastDiv > 0) { + let end = res.substring(lastDiv) + res = res.substring(0,lastDiv) + toAdd + end; + } res += toAdd; + } + + } else if (typeof this.__node.tree[r] === 'function' || this.__node.tree[r]?.__operator) { + let routeresult; + if(this.__node.tree[r]?.__operator) routeresult = this.__node.tree[r].__operator(obj[r]); + else routeresult = (this.__node.tree[r] as Function)(obj[r]); //template function, pass props + if(typeof routeresult === 'string') { + let lastDiv = res.lastIndexOf('<'); + if(lastDiv > 0) { + let end = res.substring(lastDiv) + res = res.substring(0,lastDiv) + routeresult + end; + } + else res += routeresult; + //console.log(lastDiv, res, routeresult) + } + } else if (typeof this.__node.tree[r] === 'string') res += this.__node.tree[r]; + return res; + } + + if(Array.isArray(pageStructure)) { + pageStructure.forEach((r)=>{ + result = appendTemplate(pageStructure,r,result); + }) + } else if (typeof pageStructure === 'object') { + for(const r in pageStructure) { + result = appendTemplate(pageStructure,r,result); + } + } else if (typeof pageStructure === 'string') result += pageStructure; + else if (typeof pageStructure === 'function') result += pageStructure(); + //console.log(result,pageStructure,this.routes) + return result; + } + + hotreload = (socketURL:string|URL=`http://localhost:8080/wss`) => { + + if(socketURL instanceof URL) socketURL = socketURL.toString(); + + const HotReloadClient = (url=`http://localhost:8080/wss`) => { + //hot reload code injected from backend + //const socketUrl = `ws://${cfg.host}:${cfg.hotreload}`; + let socket = new WebSocket(url); + socket.addEventListener('close',()=>{ + // Then the server has been turned off, + // either due to file-change-triggered reboot, + // or to truly being turned off. + + // Attempt to re-establish a connection until it works, + // failing after a few seconds (at that point things are likely + // turned off/permanantly broken instead of rebooting) + const interAttemptTimeoutMilliseconds = 100; + const maxDisconnectedTimeMilliseconds = 3000; + const maxAttempts = Math.round(maxDisconnectedTimeMilliseconds/interAttemptTimeoutMilliseconds); + let attempts = 0; + const reloadIfCanConnect = ()=>{ + attempts ++ ; + if(attempts > maxAttempts){ + console.error("Could not reconnect to dev server."); + return; + } + socket = new WebSocket(url); + socket.onerror = (er) => { + console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`); + } + socket.addEventListener('error',()=>{ + setTimeout(reloadIfCanConnect,interAttemptTimeoutMilliseconds); + }); + socket.addEventListener('open',()=>{ + location.reload(); + }); + }; + reloadIfCanConnect(); + }); + } + + return ` + + ` + } + +} \ No newline at end of file diff --git a/services/http/boilerplate/index.ts b/services/http/boilerplate/index.ts new file mode 100644 index 00000000..14dc6f16 --- /dev/null +++ b/services/http/boilerplate/index.ts @@ -0,0 +1,28 @@ + +export function htmlBodyBoilerPlate(html:string|string[]) { + let template = `` + if(Array.isArray(html)) { + html.forEach((src) => { + template += src; + }) + } else { + template += html; + } + template += `` + return template; +} + +export function scriptBoilerPlate(scripts:string|string[]) { + let template = `` + if(Array.isArray(scripts)) { + scripts.forEach((src) => { + template += ``; + }) + } else { + template += ``; + } + template += `` + return template; +} + + diff --git a/src/services/router/Router.ts b/services/router/Router.ts similarity index 71% rename from src/services/router/Router.ts rename to services/router/Router.ts index 5f112e49..10917934 100644 --- a/src/services/router/Router.ts +++ b/services/router/Router.ts @@ -1,4 +1,4 @@ -import { Graph, GraphNode } from "../../core/Graph" +import { Graph, GraphNode } from "../../core/Graph2" import { Service, ServiceMessage, ServiceOptions } from "../Service" /* @@ -18,38 +18,17 @@ Frontend 1 Frontend 2 */ -//TODO: -//Make this simpler or maybe rethink some of the base organization in the Service to accomodate more of this level of functionality. - - export type User = { //users have macros to call grouped connections generically, based on what's available _id:string, - - //work with available connections, you can set the preferred order (e.g. sse, websockets, http) send:(...args:any[])=>any, request:(...args:any[])=>Promise|Promise[]|undefined, post:(...args:any[])=>void, run:(...args:any[])=>Promise|Promise[]|undefined, subscribe:(...args:any[])=>Promise|Promise[]|undefined, unsubscribe:(...args:any[])=>Promise|Promise[]|undefined, - - //can work with all of the connections associated with a user if you use the Router's connection management system - sendAll?:(...args:any[])=>any, - requestAll?:(...args:any[])=>Promise|undefined, - postAll?:(...args:any[])=>void, - runAll?:(...args:any[])=>Promise|undefined, - subscribeAll?:(...args:any[])=>Promise|undefined, - unsubscribeAll?:(...args:any[])=>Promise|undefined, - terminate:(...args:any[]) => boolean, - - //specific to a service connection if we wrap a sub-service connection instead of going thru Router - onmessage?:(...args:any[])=>void, - onerror?:(...args:any[])=>void, - //You can set a new onclose function specific to router scope - onclose?:((user:User)=>void)|((...args:any[])=>void), - - [key:string]:any //w/e else, it's just a data structure for general use with some methods + onclose?:(user:User)=>void, + [key:string]:any } @@ -72,7 +51,7 @@ export type ConnectionInfo = { request?:(message:any, method?:any,...a:any[])=>Promise|Promise[], post?:(route:any, args?:any, method?:string, ...a:any[])=>void, run?:(route:any, args?:any, method?:string, ...a:any[])=>Promise|Promise[], - subscribe?:(route:any, callback?:((res:any)=>void)|string, ...a:any[])=>Promise|undefined, + subscribe?:(route:any, callback?:((res:any)=>void)|string, ...a:any[])=>Promise|Promise[]|undefined, unsubscribe?:(route:any, sub:number, ...arrayBuffer:any[])=>Promise|Promise[], terminate:(...a:any[]) => boolean, onclose?:(connection:ConnectionInfo,...args:any[])=>void @@ -94,7 +73,6 @@ export type RouterOptions = { }, //configure new connections after adding the relevant services? } //can be a service constructor } - timeout?:number, //timeout for user connections order?:string[], [key:string]:any } & ServiceOptions @@ -104,7 +82,7 @@ export class Router extends Service { name = 'router' //we need to store connection settings and available endpoints - connections:{ //this is a flattened reference with ALL active connections from each respective service + connections:{ [key:string]:ConnectionInfo //the services/graphs/nodes and connections by which to send on, these will be the corresponding info objects and the create/terminate functions for the appropriate services }={} @@ -124,27 +102,26 @@ export class Router extends Service { users:{[key:string]:User} = {}; //jsonifiable information - userTimeout = 10000; - order:string[]; //execute connections in preferred order constructor(options?:RouterOptions){ super(options); - this.load(this); + this.setTree(this); + if(options) { if(options.order) this.order = options.order; - if(options.timeout) this.userTimeout = options.timeout; - if(options.graph) { + + if(options.graph && options.graph) { for(const key in options.graph) { let opt = (options.graph[key] as any); - if (typeof opt === 'function') opt = new opt() as Service; //instantiate a class prototype + if (typeof opt === 'function') opt = new opt({graph: this}) as Service; //instantiate a class prototype if(opt?.__node?.nodes) { opt.name = key; opt.__node.tag = key; this.addServices({[opt.name]:opt}); - this.routeService(opt, (opt as any).connections); + this.routeService(opt, opt.connections); } else { - if(typeof opt?.service === 'function') opt.service = new opt.service(); + if(typeof opt?.service === 'function') opt.service = new opt.service({graph: this}); if(opt?.service?.__node?.nodes) { opt.service.name = key; opt.service.__node.tag = key; this.addServices({[opt.service.name]:opt.service}); @@ -152,13 +129,16 @@ export class Router extends Service { opt.service ); } + if(typeof opt?.service === 'object') { if(opt.connections) { if(Array.isArray(opt.connections)) { (opt.connections as any).forEach((k) => { this.addServiceConnections(opt[key].service,k); }) - } else this.addServiceConnections(opt.service,opt.connections); + } else { + this.addServiceConnections(opt.service,opt.connections); + } } if(opt.config) { for(const c in opt.config) { @@ -192,25 +172,22 @@ export class Router extends Service { receiving?:boolean //is this the receiving router? ) => { - let user:User if(!info._id) { info._id = `user${Math.floor(Math.random()*1000000000000000)}`; - } - if(this.users[info._id]) { - user = this.users[info._id]; //existing user - } else { - user = Object.assign({}, info) as any;//Profile(info._id,info) as User; } + + let user:User = Object.assign({},info) as any;//Profile(info._id,info) as User; if(connections){ for(const key in connections) { if(typeof connections[key] === 'object') { if(!(connections[key] as any).connection._id) { await new Promise((res,rej) => { + console.log('STARTING!') let start = performance.now(); let checker = () => { if(!(connections[key] as any).connection._id) { - if(performance.now() - start > this.userTimeout) { + if(performance.now() - start > 3000) { delete connections[key]; rej(false); } else { @@ -235,9 +212,6 @@ export class Router extends Service { connections[key] = this.addConnection(connections[key], user._id) as any; } } - - - if(config) { for(const c in config) { this.openConnection( @@ -249,106 +223,50 @@ export class Router extends Service { } } + let send = (message:any, ...a:any[]) => { + let connection = this.getConnection(user._id, 'send'); + if(connection?.send) return connection.send(message, ...a); + } - if(!this.users[info._id]) { - let send = (message:any, ...a:any[]) => { - let connection = this.getConnection(user._id, 'send'); - if(connection?.send) return connection.send(message, ...a); - } - - let sendAll = (message:any, ...a:any[]) => { - let connections = this.getConnections(user._id, 'send'); - for(const key in connections) - if(connections[key]?.send) return connections[key].send(message, ...a); - } - - let request = (message:any, method?:any, ...a:any[]) => { - let connection = this.getConnection(user._id, 'request'); - if(connection?.request) return connection.request(message, method, ...a); - } - - let requestAll = (message:any, method?:any, ...a:any[]) => { - let connections = this.getConnections(user._id, 'request'); - let results = []; - for(const key in connections) - if(connections[key]?.request) results.push(connections[key].request(message, method, ...a)); - return Promise.all(results); - } - - let post = (route:any, args?:any, method?:string, ...a:any[]) => { - let connection = this.getConnection(user._id, 'post'); - if(connection?.post) return connection.post(route, args, method, ...a); - } - - let postAll = (route:any, args?:any, method?:string, ...a:any[]) => { - let connections = this.getConnections(user._id, 'post'); - for(const key in connections) - if(connections[key]?.post) connections[key].post(route, args, method, ...a); - } - - let run = (route:any, args?:any, method?:string, ...a:any[]) => { - let connection = this.getConnection(user._id, 'run'); - if(connection?.run) return connection.run(route, args, method, ...a); - } + let request = (message:any, method?:any, ...a:any[]) => { + let connection = this.getConnection(user._id, 'request'); + if(connection?.request) return connection.request(message, method, ...a); + } - let runAll = (route:any, args?:any, method?:string, ...a:any[]) => { - let connections = this.getConnections(user._id, 'run'); - let results = []; - for(const key in connections) - if(connections[key]?.run) results.push(connections[key].run(route, args, method, ...a)); - return Promise.all(results); - } + let post = (route:any, args?:any, method?:string, ...a:any[]) => { + let connection = this.getConnection(user._id, 'post'); + if(connection?.post) return connection.post(route, args, method, ...a); + } - let subscribe = (route:any, callback?:((res:any)=>void)|string, ...a:any[]) => { - let connection = this.getConnection(user._id, 'subscribe'); - if(connection?.subscribe) return connection.subscribe(route, callback, ...a); - } + let run = (route:any, args?:any, method?:string, ...a:any[]) => { + let connection = this.getConnection(user._id, 'run'); + if(connection?.run) return connection.run(route, args, method, ...a); + } - let subscribeAll = (route:any, callback?:((res:any)=>void)|string, ...a:any[]) => { - let connections = this.getConnections(user._id, 'subscribe'); - let results = []; - for(const key in connections) - if(connections[key]?.post) results.push(connections[key].subscribe(route, callback, ...a)); - return Promise.all(results) as Promise; - } + let subscribe = (route:any, callback?:((res:any)=>void)|string,...a:any[]) => { + let connection = this.getConnection(user._id, 'subscribe'); + if(connection?.subscribe) return connection.subscribe(route, callback, ...a); + } - let unsubscribe = (route:any, sub:number, ...a:any[]) => { - let connection = this.getConnection(user._id, 'unsubscribe'); - if(connection?.unsubscribe) return connection.unsubscribe(route, sub, ...a); - } + let unsubscribe = (route:any, sub:number, ...a:any[]) => { + let connection = this.getConnection(user._id, 'unsubscribe'); + if(connection?.unsubscribe) return connection.unsubscribe(route, sub, ...a); + } - let unsubscribeAll = (route:any, subs?:{[key:string]:number}, ...a:any[]) => { - let connections = this.getConnections(user._id, 'unsubscribe'); - let results = []; - for(const key in connections) - if(connections[key]?.post && subs[key]) results.push(connections[key].unsubscribe(route, subs[key], ...a)); - return Promise.all(results) as Promise; - } + let terminate = () => { + return this.removeUser(user) + } - let terminate = () => { - return this.removeUser(user) - } + user.send = send; + user.request = request; + user.post = post; + user.run = run; + user.subscribe = subscribe; + user.unsubscribe = unsubscribe; + user.terminate = terminate; + //these are macros to get available connections - user.send = send; - user.request = request; - user.post = post; - user.run = run; - user.subscribe = subscribe; - user.unsubscribe = unsubscribe; - user.terminate = terminate; - - user.sendAll = sendAll; - user.requestAll = requestAll; - user.postAll = postAll; - user.runAll = runAll; - user.subscribeAll = subscribeAll; - user.unsubscribeAll = unsubscribeAll; - user.terminateAll = terminate; - //these are macros to get available connections - - - this.users[user._id] = user; - } + this.users[user._id] = user; if(connections && !receiving) { let connectionIds = {}; @@ -372,6 +290,8 @@ export class Router extends Service { } } + console.log('User has been added!', info) + return user; } @@ -392,25 +312,10 @@ export class Router extends Service { } //pick the preferred connection by service name if passing a source, or pick the connection by id if not a source - getConnection = (sourceId:string, hasMethod?:string, connectionId?:string):User|ConnectionInfo|undefined => { - - if(this.connections[sourceId]) { - return this.connections[sourceId]; //regardless of method, as this is a direct connection reference - } - else if(this.sources[sourceId]) { + getConnection = (sourceId:string, hasMethod?:string):ConnectionInfo|undefined => { + if(this.sources[sourceId]) { //console.log(this.sources[sourceId]); - if(hasMethod?.includes('All')) return this.users[sourceId]; - - if(connectionId) { - if(hasMethod) { - if(this.sources[sourceId][connectionId]?.[hasMethod]) - return this.sources[sourceId][connectionId]; - } - else if(this.sources[sourceId][connectionId]) - return this.sources[sourceId][connectionId]; - else return undefined; - } - else if (this.order) { + if (this.order) { for(let i = 0; i < this.order.length; i++) { let k = this.order[i]; for(const key in this.sources[sourceId as string]) { @@ -423,22 +328,14 @@ export class Router extends Service { continue; } } - if(hasMethod) { - if(this.sources[sourceId as string][key][hasMethod]) - return this.sources[sourceId as string][key]; - } - else return this.sources[sourceId as string][key]; + return this.sources[sourceId as string][key]; } } else if (this.sources[sourceId as string][key].service === k) { if(this.sources[sourceId as string][key].connectionType && (this.sources[sourceId as string][key].service as any)?.name) { if(!this.serviceConnections[(this.sources[sourceId as string][key] as any).service.name]) this.removeConnection(this.sources[sourceId as string][key]); //some auto cleanup continue; } - if(hasMethod) { - if(this.sources[sourceId as string][key][hasMethod]) - return this.sources[sourceId as string][key]; - } - else return this.sources[sourceId as string][key]; + return this.sources[sourceId as string][key]; } } } @@ -453,9 +350,8 @@ export class Router extends Service { continue; } } - if(hasMethod) { - if(this.sources[sourceId as string][k][hasMethod]) - return this.sources[sourceId as string][k]; + if(hasMethod && this.sources[sourceId as string][k][hasMethod]) { + return this.sources[sourceId as string][k]; } else { return this.sources[sourceId as string][k]; @@ -463,7 +359,7 @@ export class Router extends Service { } } - } else if (this.order && !this.connections[sourceId]) { + } else if (this.order) { for(let i = 0; i < this.order.length; i++) { let k = this.order[i]; if(this.sources[k]?.[sourceId]) { @@ -473,8 +369,7 @@ export class Router extends Service { continue; } } - if(hasMethod) { - if(this.sources[k][sourceId][hasMethod]) + if(hasMethod && this.sources[k][sourceId as string]?.[hasMethod]) { return this.sources[k][sourceId as string]; } else { @@ -484,6 +379,9 @@ export class Router extends Service { } } + if(typeof sourceId === 'string' && this.connections[sourceId] && this.connections[sourceId].send) { + return this.connections[sourceId]; //regardless of method, as this is a direct connection reference + } } @@ -500,113 +398,59 @@ export class Router extends Service { if(typeof this.sources[sourceId][key][k] === 'object') { let pass = true; if(hasMethod && !this.sources[sourceId][key][k][hasMethod]) pass = false; - if(props) { - for(const p in props) { - if(typeof this.sources[sourceId][key][k][p] === 'object' && typeof props[p] === 'object') { - //check one level down - for(const pp in props[p]) { - if(props[p][pp] !== this.sources[sourceId][key][k][p][pp]) { - pass = false; - break; - } + for(const p in props) { + if(typeof this.sources[sourceId][key][k][p] === 'object' && typeof props[p] === 'object') { + //check one level down + for(const pp in props[p]) { + if(props[p][pp] !== this.sources[sourceId][key][k][p][pp]) { + pass = false; + break; } } - else if(this.sources[sourceId][key][k][p] !== props[p]) { - pass = false; - } else { - pass = false; - break; - } + } + else if(this.sources[sourceId][key][k][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; } } if(pass) { found[this.sources[sourceId][key][k]._id] = this.sources[sourceId][key][k]; - } + } } } } else { let pass = true; if(hasMethod && !this.sources[sourceId][key][hasMethod]) pass = false; - if(props) { - for(const p in props) { - if(typeof this.sources[sourceId][key][p] === 'object' && typeof props[p] === 'object') { - //check one level down - for(const pp in props[p]) { - if(props[p][pp] !== this.sources[sourceId][key][p][pp]) { - pass = false; - break; - } + for(const p in props) { + if(typeof this.sources[sourceId][key][p] === 'object' && typeof props[p] === 'object') { + //check one level down + for(const pp in props[p]) { + if(props[p][pp] !== this.sources[sourceId][key][p][pp]) { + pass = false; + break; } } - else if(this.sources[sourceId][key][p] !== props[p]) { - pass = false; - } else { - pass = false; - break; - } + } + else if(this.sources[sourceId][key][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; } } if(pass) { - found[this.sources[sourceId][key]._id] = this.sources[sourceId][key]; + if(this.getConnection(this.sources[sourceId][key] as any, hasMethod)) + found[this.sources[sourceId][key]._id] = this.sources[sourceId][key]; } } } } - return found; - } - } - - - //e.g. from a user endpoint, run 'runConnection' on another user Id to interact with them - runConnection = async ( - userId:string, - method:'run'|'post'|'subscribe'|'unsubscribe'|'terminate'|'send'|'request'| - 'runAll'|'postAll'|'subscribeAll'|'unsubscribeAll'|'sendAll'|'requestAll', - args:any[], - connectionId?:string - ) => { - let sendTo; - if(method.indexOf('All') > -1) { - sendTo = this.users[userId]; - } else { - sendTo = this.getConnection(userId, method, connectionId); - } - if(sendTo) { - let res = (sendTo[method] as Function)(...args); - res = await res; - return res; } } - subscribeThroughConnection = ( - route:string, //the route on the endpoint we want to subscribe to outputs from - remoteRelay:string|ConnectionInfo, //the endpoint/user Id linking a router we are trying to relay messages through - remoteEndpoint:string, //the endpoint/user on the other router that we want to subscribe to through the router - callback:string|((res:any)=>void), - ...args:any[] - ) => { - if(typeof remoteRelay === 'string') { - remoteRelay = this.getConnection(remoteRelay, 'run') as ConnectionInfo; - } - - if(typeof remoteRelay === 'object') - return new Promise((res,rej) => { - (remoteRelay as any).run('routeConnections',[route,remoteEndpoint,(remoteRelay as any)._id,...args]).then((sub) => { - this.__node.state.subscribeEvent(remoteEndpoint, (res) => { - if(res?.callbackId === route) { - if(!callback) this.setState({[remoteEndpoint]:res.args}); - else if(typeof callback === 'string') { //just set state - this.setState({[callback]:res.args}); - } - else callback(res.args); - } - }); - res(sub); - }).catch(rej); - }); - } - - addConnection = (options:ConnectionProps|ConnectionInfo|string,source?:string, autoRemove=true) => { + addConnection = (options:ConnectionProps|ConnectionInfo|string,source?:string) => { let settings:ConnectionInfo = {} as any; if(typeof options === 'string') { if (this.connections[options]) { @@ -627,7 +471,7 @@ export class Router extends Service { if(typeof options === 'string' && this.__node.nodes.get(options)) options = {connection:this.__node.nodes.get(options)}; } if(!options || typeof options === 'string') return undefined; - + if(source) settings.source = source; if(options.connection instanceof GraphNode) { @@ -780,7 +624,6 @@ export class Router extends Service { } if(typeof c !== 'object') return undefined; settings._id = c._id; - settings.connection = options.connection as any; settings.send = c.send; settings.request = c.request; settings.run = c.run; @@ -796,12 +639,7 @@ export class Router extends Service { let oldonclose = c.onclose; c.onclose = (...args:any[]) => { if(settings.onclose) settings.onclose(settings, ...args); - if( - autoRemove && - settings.source && - this.users[settings.source] && - Object.keys(this.sources[settings.source]).length === 0 - ) { + if(this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { this.removeUser(settings.source, false); } if(oldonclose) oldonclose(...args); @@ -811,12 +649,7 @@ export class Router extends Service { let oldonclose = c.onclose; c.onclose = (...args:any[]) => { this.removeConnection(settings); - if( - autoRemove && - settings.source && - this.users[settings.source] && - Object.keys(this.sources[settings.source]).length === 0 - ) { //automatically clear a user if all of their connections + if(this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { this.removeUser(settings.source, false); } if(oldonclose) oldonclose(...args); @@ -888,18 +721,22 @@ export class Router extends Service { source?:string, order?:string[], ) => { + //console.log(service) this.services[service.name] = service; if(service.__node?.nodes) this.__node.nodes.forEach((n,k) => { if(!service.__node?.nodes.get(k)) { - service.__node?.nodes.set(k,n); - } else service.__node?.nodes.set(this.name + '.' + k,n); + service.set(k,n); + } else { + service.set(this.name + '.' + k,n); + } }); if(service.users) service.users = this.users; //needed for sessions service rn, should find more elegant solution if(connections) { - if(typeof connections === 'string') this.addServiceConnections(service,connections,source); - else { + if(typeof connections === 'string') { + this.addServiceConnections(service,connections,source); + } else { for(const c in connections) { this.addServiceConnections(service,c,source); } @@ -917,20 +754,22 @@ export class Router extends Service { connectionsKey:any, source?:string ) => { - if(typeof service === 'string') { - service = this.services[service]; - } + + if(typeof service === 'string') service = this.services[service]; + if(connectionsKey && service[connectionsKey]) { let newConnections = {}; if(!this.serviceConnections[service.name]) this.serviceConnections[service.name] = {}; this.serviceConnections[service.name][connectionsKey] = service[connectionsKey]; for(const key in service[connectionsKey]) { - if(!this.connections[key]) - { - newConnections[key] = this.addConnection({connection:service[connectionsKey][key], service},source); + if(!this.connections[key]) { + const res = this.addConnection({ connection: service[connectionsKey][key], service }, source); + if (res) { + newConnections[key] = res; newConnections[key].connectionType = connectionsKey; - } + } else console.log('Could not make connection', connectionsKey, key , service[connectionsKey][key]) + } } return newConnections; } @@ -942,21 +781,60 @@ export class Router extends Service { source?:string, ...args:any[] //potentially other arguments in custom services ) => { + if(typeof service === 'string') { service = this.services[service]; } + if(service?.__node.nodes) { let connection = service.run('open', options, ...args); if(connection instanceof Promise) { return connection.then(async (info) => { if(!info._id) { - await connectionHasId(info,this.userTimeout); + await new Promise((res,rej) => { + let start = performance.now(); + let checker = () => { + if(!info._id) { + if(performance.now() - start > 3000) { + rej(false); + } else { + setTimeout(()=>{ + checker(); + },100); //check every 100ms + } + } else { + res(true); + } + } + + checker(); + + }).catch((er) => {console.error('Connections timed out:', er); }); } if(info._id) this.addConnection({connection:info, service}, source); }) } else if(connection) { if(!connection._id) { - await connectionHasId(connection,this.userTimeout); + await new Promise((res,rej) => { + + let start = performance.now(); + let checker = () => { + if(!connection._id) { + if(performance.now() - start > 3000) { + rej(false); + } else { + setTimeout(()=>{ + checker(); + },100); //check every 100ms + } + } else { + res(true); + } + } + + checker(); + + }).catch((er) => {console.error('Connections timed out:', er); }); } if(connection._id) return this.addConnection({connection, service}, source); } @@ -968,6 +846,34 @@ export class Router extends Service { return connection.terminate(); } + subscribeThroughConnection = ( + route:string, //the route on the endpoint we want to subscribe to outputs from + relay:string|ConnectionInfo, //the router we are trying to relay messages through + endpoint:string, //the endpoint on the router that we want to subscribe to through the router + callback:string|((res:any)=>void), + ...args:any[] + ) => { + if(typeof relay === 'string') { + relay = this.getConnection(relay,'run') as ConnectionInfo; + } + + if(typeof relay === 'object') + return new Promise((res,rej) => { + (relay as any).run('routeConnections',[route,endpoint,(relay as any)._id,...args]).then((sub) => { + this.__node.state.subscribeTrigger(endpoint, (res) => { + if(res?.callbackId === route) { + if(!callback) this.setState({[endpoint]:res.args}); + else if(typeof callback === 'string') { //just set state + this.setState({[callback]:res.args}); + } + else callback(res.args); + } + }); + res(sub); + }).catch(rej); + }); + } + //we will use the router to relay subscriptions between endpoints generically routeConnections = ( route:string, //the route on the endpoint we want to subscribe to outputs from @@ -996,8 +902,9 @@ export class Router extends Service { if((transmitter as ConnectionInfo)?.subscribe && (receiver as ConnectionInfo)?.send) { let res:Promise = new Promise((res,rej) => { - (transmitter as ConnectionInfo).subscribe( + (transmitter as any).subscribe( route, + (transmitter as any)._id, (res:any) => { if(!this.connections[(receiver as any)._id] && rxsrc) { if(this.sources[rxsrc]) { @@ -1041,27 +948,5 @@ export class Router extends Service { } -} -//e.g. check if a websocket etc has the id so its ready for sending commands -export function connectionHasId(connection:{_id?:string, [key:string]:any}, timeout=10000) { - return new Promise((res,rej) => { - let start = performance.now(); - let checker = () => { - if(!connection._id) { - if(performance.now() - start > timeout) { - rej(false); - } else { - setTimeout(()=>{ - checker(); - },100); //check every 100ms - } - } else { - res(true); - } - } - - checker(); - }).catch((er) => {console.error('Connection timed out:', er); }) as Promise; - } \ No newline at end of file diff --git a/src/services/sessions/sessions.service.ts b/services/sessions/sessions.service.ts similarity index 51% rename from src/services/sessions/sessions.service.ts rename to services/sessions/sessions.service.ts index 1861086f..3ddfb11f 100644 --- a/src/services/sessions/sessions.service.ts +++ b/services/sessions/sessions.service.ts @@ -1,24 +1,10 @@ import { stringifyFast } from "../utils"; import { Service, ServiceOptions } from "../Service"; import { User } from "../router/Router"; -import { loaders } from "../../loaders/index"; - -/** - * Sessions are a way to run a loop that monitors data structures to know procedurally when and what to update - * - * OneWaySession: source sends props to listener, define listener, source default is creating user - * SharedSession: two modes: - * Hosted: Host receives props from all users based on propnames, users receive hostprops - * Shared: All users receive the same props based on their own updates - * - * There's also these older stream API functions that are more pure for monitoring objects/arrays and updating new data e.g. out of a buffer. - * Need to esplain/demo all that too.... @@__@@ - */ - +import { loaders } from "../../core/loaders"; //parse from this object/endpoint and send to that object/endpoint, e.g. single users -//todo: make this hurt brain less to reconstruct the usage -export type OneWaySessionProps = { +export type PrivateSessionProps = { _id?:string, settings?:{ listener:string, @@ -28,10 +14,9 @@ export type OneWaySessionProps = { moderators?:{[key:string]:boolean}, password?:string, ownerId?:string, - onopen?:(session:OneWaySessionProps)=>void, - onhasupdate?:(session:OneWaySessionProps, updated:any)=>void, //host-side - onmessage?:(session:OneWaySessionProps, updated:any)=>void, //user-side - onclose?:(session:OneWaySessionProps)=>void, + onopen?:(session:PrivateSessionProps)=>void, + onmessage?:(session:PrivateSessionProps)=>void, + onclose?:(session:PrivateSessionProps)=>void, [key:string]:any //arbitrary props e.g. settings, passwords }, data?:{ @@ -44,14 +29,8 @@ export type OneWaySessionProps = { export type SessionUser = { _id:string, //unique identifier for user, used as key in users object and in general sessions:{[key:string]:any}, - sessionSubs:{[key:string]:{ - onopenSub?:number, - onmessage?:(session:SharedSessionProps, update:any, user:SessionUser)=>void, - onopen?:(session:SharedSessionProps, user:SessionUser)=>void, - onclose?:(session:SharedSessionProps, user:SessionUser)=>void - }} [key:string]:any -} & User //extend base users on the router or just wrapping a connection from another service +} & Partial //sessions for shared user data and game/app logic for synchronous and asynchronous sessions to stream selected properties on user objects as they are updated export type SharedSessionProps = { @@ -60,18 +39,16 @@ export type SharedSessionProps = { name:string, propnames:{[key:string]:boolean}, users?:{[key:string]:boolean}, - host?:string, //if there is a host, all users only receive from the host's prop updates and vise versa + host?:string, //if there is a host, all users only receive from the host's prop updates hostprops?:{[key:string]:boolean}, - inheritHostData?:boolean, //new hosts adopt old host data? Default true admins?:{[key:string]:boolean}, moderators?:{[key:string]:boolean}, spectators?:{[key:string]:boolean}, banned?:{[key:string]:boolean}, password?:string, ownerId?:string, - onhasupdate?:(session:SharedSessionProps, updated:any)=>void, //host-side onopen?:(session:SharedSessionProps)=>void, - onmessage?:(session:SharedSessionProps, updated:any)=>void, + onmessage?:(session:SharedSessionProps)=>void, onclose?:(session:SharedSessionProps)=>void, [key:string]:any //arbitrary props e.g. settings, passwords }, @@ -81,7 +58,7 @@ export type SharedSessionProps = { [key:string]:any } }, - oneWay?:{ //host driven sessions will share only what the host shares to all users, while hosts will receive hidden data + private?:{ //host driven sessions will share only what the host shares to all users, while hosts will receive hidden data [key:string]:any }, [key:string]:any @@ -104,7 +81,6 @@ export type StreamInfo = { } } -//Todo: streamline, we don't *really* need 3 types of streaming data structures but on the other hand everything is sort of optimized so just keep it export class SessionsService extends Service { name='sessions'; @@ -113,45 +89,35 @@ export class SessionsService extends Service { //complex user sessions with some premade rulesets sessions:{ - oneWay:{[key:string]:OneWaySessionProps}, //sync user props <--> user props + private:{[key:string]:PrivateSessionProps}, //sync user props <--> user props shared:{[key:string]:SharedSessionProps}//sync user props <--> all other users props } = { - oneWay:{}, + private:{}, shared:{} } - invites:{ - [key:string]:{ //userId - [key:string]:{//session Id - session:OneWaySessionProps|SharedSessionProps|string, - endpoint?:string //userid to send joinSession call to - } //session options - } - } = {} - - constructor(options?:ServiceOptions, users?:{[key:string]:SessionUser}) { super(options); this.setLoaders(loaders); - this.load(this); + this.setTree(this); if(users) this.users = users; } getSessionInfo = ( - sessionIdOrName?:string, //id or name (on shared sessions) + sessionId?:string, //id or name (on shared sessions) userId?:string ) => { - if(!sessionIdOrName) { + if(!sessionId) { return this.sessions.shared; } else { - if(this.sessions.oneWay[sessionIdOrName]) { - let s = this.sessions.oneWay[sessionIdOrName]; + if(this.sessions.private[sessionId]) { + let s = this.sessions.private[sessionId]; if(s.settings) if(s.settings.source === userId || s.settings.listener === userId || s.settings.ownerId === userId || s.settings.admins?.[userId as string] || s.settings.moderators?.[userId as string]) - return {oneWay:{[sessionIdOrName]:s}}; - } else if(this.sessions.shared[sessionIdOrName]) { - return {shared:{[sessionIdOrName]:this.sessions.shared[sessionIdOrName]}}; + return {private:{[sessionId]:s}}; + } else if(this.sessions.shared[sessionId]) { + return {shared:{[sessionId]:this.sessions.shared[sessionId]}}; } else { let res = {}; for(const id in this.sessions.shared) { @@ -163,43 +129,31 @@ export class SessionsService extends Service { } } - openOneWaySession = ( - options:OneWaySessionProps={}, - sourceUserId?:string, - listenerUserId?:string + openPrivateSession = ( + options:PrivateSessionProps={}, + userId?:string ) => { if(!options._id) { - options._id = `oneWay${Math.floor(Math.random()*1000000000000000)}`; - if(this.sessions.oneWay[options._id]) { + options._id = `private${Math.floor(Math.random()*1000000000000000)}`; + if(this.sessions.private[options._id]) { delete options._id; - this.openOneWaySession(options,sourceUserId); //regen id + this.openPrivateSession(options,userId); //regen id } } - if(options._id && sourceUserId && this.users[sourceUserId]) { - if(sourceUserId){ - if(!options.settings) - options.settings = { - listener:sourceUserId, - source:sourceUserId, - propnames:{latency:true}, - admins:{[sourceUserId]:true}, - ownerId:sourceUserId - }; - if(!options.settings.listener) - options.settings.listener = listenerUserId ? listenerUserId : sourceUserId; - if(!options.settings.source) - options.settings.source = sourceUserId; - if(!this.users[sourceUserId].sessions) - this.users[sourceUserId].sessions = {}; - this.users[sourceUserId].sessions[options._id] = options; + if(options._id && userId && this.users[userId]) { + if(userId){ + if(!options.settings) options.settings = { listener:userId, source:userId, propnames:{latency:true}, admins:{[userId]:true}, ownerId:userId }; + if(!options.settings.listener) options.settings.listener = userId; + if(!options.settings.source) options.settings.source = userId; + if(!this.users[userId].sessions) this.users[userId].sessions = {}; + this.users[userId].sessions[options._id] = options; } if(!options.data) options.data = {}; - if(options.onopen) options.onopen(options); - if(this.sessions.oneWay[options._id]) { - return this.updateSession(options,sourceUserId); + if(this.sessions.private[options._id]) { + return this.updateSession(options,userId); } else if(options.settings?.listener && options.settings.source) - this.sessions.oneWay[options._id] = options; //need the bare min in here + this.sessions.private[options._id] = options; //need the bare min in here } return options; } @@ -212,41 +166,21 @@ export class SessionsService extends Service { options._id = `shared${Math.floor(Math.random()*1000000000000000)}`; if(this.sessions.shared[options._id]) { delete options._id; - return this.openSharedSession(options,userId); //regen id + this.openSharedSession(options,userId); //regen id } } if(options._id && userId && this.users[userId]){ if(typeof userId === 'string') { - if(!options.settings) - options.settings = { - name:'shared', - propnames:{latency:true}, - users:{[userId]:true}, - admins:{[userId]:true}, - ownerId:userId - }; + if(!options.settings) options.settings = { name:'shared', propnames:{latency:true}, users:{[userId]:true}, admins:{[userId]:true}, ownerId:userId }; - if(!options.settings.users) - options.settings.users = {[userId]:true}; - if(!options.settings.admins) - options.settings.admins = {[userId]:true}; - if(!options.settings.ownerId) - options.settings.ownerId = userId; - if(!this.users[userId].sessions) - this.users[userId].sessions = {}; + if(!options.settings.users) options.settings.users = {[userId]:true}; + if(!options.settings.admins) options.settings.admins = {[userId]:true}; + if(!options.settings.ownerId) options.settings.ownerId = userId; + if(!this.users[userId].sessions) this.users[userId].sessions = {}; this.users[userId].sessions[options._id] = options; - } - else if (!options.settings) - options.settings = { - name:'shared', - propnames:{latency:true}, - users:{} - }; - if(!options.data) - options.data = { oneWay:{}, shared:{} }; - if(!options.settings.name) - options.name = options.id; - if(options.onopen) options.onopen(options); + } else if (!options.settings) options.settings = {name:'shared', propnames:{latency:true}, users:{}}; + if(!options.data) options.data = { private:{}, shared:{} }; + if(!options.settings.name) options.name = options.id; if(this.sessions.shared[options._id]) { return this.updateSession(options,userId); } @@ -255,50 +189,37 @@ export class SessionsService extends Service { return options; } - open = (options:any,userId?:string) => { - if(options.listener) this.openOneWaySession(options,userId); - else this.openSharedSession(options,userId); - } - //update session properties, also invoke basic permissions checks for who is updating updateSession = ( - options:OneWaySessionProps | SharedSessionProps, + options:PrivateSessionProps | SharedSessionProps, userId?:string ) => { //add permissions checks based on which user ID is submitting the update let session:any; if(options._id){ - session = this.sessions.oneWay[options._id]; - if(!session) - session = this.sessions.shared[options._id]; - if(session && userId) { - if(session.settings && ( - session?.settings.source === userId || - session.settings.admins?.[userId] || - session.settings.moderators?.[userId] || - session.settings.ownerId === userId - )) { - return this.recursivelyAssign(session, options); + session = this.sessions.private[options._id]; + if(!session) session = this.sessions.shared[options._id]; + if(this.sessions.private[options._id] && userId) { + let sesh = this.sessions.shared[options._id]; + if(sesh.settings && (sesh?.settings.source === userId || sesh.settings.admins?.[userId] || sesh.settings.moderators?.[userId] || sesh.settings.ownerId === userId)) { + return Object.assign(this.sessions.shared[options._id],options); } } else if(options.settings?.source) { - return this.openOneWaySession(options as OneWaySessionProps,userId); + return this.openPrivateSession(options as PrivateSessionProps,userId); } else return this.openSharedSession(options as SharedSessionProps,userId); } return false; } - //add a user id to a session, Run this at the session host location and clientside if separate. remoteUser will take care of this on either endpoint for you - //supply options e.g. to make them a moderator or update properties to be streamed dynamically + //add a user id to a session, supply options e.g. to make them a moderator or update properties to be streamed dynamically joinSession = ( sessionId:string, userId:string, - options?:SharedSessionProps|OneWaySessionProps, - remoteUser:boolean=true //ignored if no endpoint on user object - ):SharedSessionProps|OneWaySessionProps|false => { + options?:SharedSessionProps|PrivateSessionProps + ) => { if(!userId && !this.users[userId]) return false; if(!this.users[userId].sessions) this.users[userId].sessions = {}; - let sesh = this.sessions.shared[sessionId] as SharedSessionProps|OneWaySessionProps; - if(!sesh) sesh = this.sessions.oneWay[sessionId]; + let sesh = this.sessions.shared[sessionId]; //console.log(sessionId,userId,sesh,this.sessions); if(sesh?.settings) { if(sesh.settings?.banned) { @@ -309,233 +230,70 @@ export class SessionsService extends Service { if(options.settings.password !== sesh.settings.password) return false } (sesh.settings.users as any)[userId] = true; - sesh.settings.newUser = true; this.users[userId].sessions[sessionId] = sesh; if(options) { return this.updateSession(options,userId); }; //console.log(sesh) - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'joinSession',args:[sessionId,userId,sesh]}); //callbacks on the sesh should disappear with json.stringify() in the send calls when necessary - } - return sesh; - } - else if (options?.source || options?.listener) { - sesh = this.openOneWaySession(options as OneWaySessionProps,userId); - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'joinSession',args:[sessionId,userId,sesh]}); - } - return sesh; - } - else if (options) { - sesh = this.openSharedSession(options as SharedSessionProps,userId); - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'joinSession',args:[sessionId,userId,sesh]}); - } return sesh; - } + } else if (options?.source || options?.listener) return this.openPrivateSession(options as PrivateSessionProps,userId); + else if (options) return this.openSharedSession(options as SharedSessionProps,userId); return false; } - inviteToSession = ( - session:OneWaySessionProps|SharedSessionProps|string, - userInvited:string, - inviteEndpoint?:string, //your user/this socket endpoint's ID as configured on router - remoteUser:boolean=true - ) => { - if(remoteUser && this.users[userInvited]?.send) { - this.users[userInvited]?.send({route:'receiveSessionInvite', args:[ - session, - userInvited, - inviteEndpoint - ]}); - } else { - this.receiveSessionInvite(session,userInvited,inviteEndpoint); - } - } - - //subscribe to this clientside to do stuff when getting notified - receiveSessionInvite = ( - session:OneWaySessionProps|SharedSessionProps|string, //this session - userInvited:string, //invite this user - endpoint?:string //is the session on another endpoint (user or other?)? - ) => { - if(!this.invites[userInvited]) this.invites[userInvited] = {}; - let id = typeof session === 'string' ? session : session._id; - this.invites[userInvited][id] = {session, endpoint}; - - return id; - } - - acceptInvite = ( //will wait for endpoint to come back if remote invitation - session:OneWaySessionProps|SharedSessionProps|string, //session id is minimum - userInvited:string, - remoteUser=true - ):Promise => { - let id = typeof session === 'string' ? session : session._id; - let invite = this.invites[userInvited]?.[id]; - let endpoint; - if(invite) { - session = invite.session; - endpoint = invite.endpoint; - delete this.invites[userInvited]?.[id]; - } - return new Promise((res,rej) => { - if(!id) res(false); - if(remoteUser && endpoint && this.users[endpoint]?.send) { - //wait for the remote joinSession call to come back - let resolved; - let timeout = setTimeout(()=>{ - if(!resolved) { - this.unsubscribe('joinSession',subbed); rej(new Error('Session join timed out')); - } - },10000); - let subbed = this.subscribe('joinSession', (result:SharedSessionProps|OneWaySessionProps|false)=>{ - if(typeof result === 'object' && result?._id === id) { - if(result.setting?.users?.includes(userInvited)) { - //we've joined the session - this.unsubscribe('joinSession', subbed); - resolved = true; - if(timeout) clearTimeout(timeout); - res(result); - } - } - }); - this.users[endpoint]?.send({route:'joinSession',args:[id,userInvited,undefined,true]}); - //10sec timeout - } else res(this.joinSession(id, userInvited, typeof session === 'object' ? session : undefined)); - }); - } - - rejectInvite = ( - session:OneWaySessionProps|SharedSessionProps|string, - userInvited:string, - remoteUser=true - ) => { - let id = typeof session === 'string' ? session : session._id; - if(this.invites[userInvited]?.[id]) { - let endpoint = this.invites[userInvited][id].endpoint; - delete this.invites[userInvited][id]; - if(remoteUser && endpoint && this.users[endpoint]?.send) { - this.users[endpoint].send({route:'rejectInvite',args:[id,userInvited]}); //listen on host end too to know if invite was rejected - } - return true; - } - } - - //Remove a user from a session. OneWay sessions will be closed - //Run this at the session host location leaveSession = ( - session:OneWaySessionProps|SharedSessionProps|string, + sessionId:string, userId:string, - clear:boolean=true, //clear all data related to this user incl permissions - remoteUser:boolean=true //send user an all-clear to unsubscribe on their end + clear:boolean=true //clear all data related to this user incl permissions ) => { - let sessionId:string|undefined; - if(typeof session === 'string') { - sessionId = session; - session = this.sessions.oneWay[sessionId]; - if(!session) session = this.sessions.shared[sessionId]; - } else sessionId = session._id; + let session:any = this.sessions.private[sessionId]; + if(!session) session = this.sessions.shared[sessionId]; if(session) { - if(this.sessions.oneWay[sessionId]) { - if( userId === session.settings.source || - userId === session.settings.listener || - session.settings.admins?.[userId] || - session.settings.moderators?.[userId] - ) { - delete this.sessions.oneWay[sessionId]; - delete this.users[userId]?.sessions[sessionId]; - delete this.users[userId]?.sessionSubs?.[sessionId]; + if(this.sessions.private[sessionId]) { + if(userId === session.settings.source || userId === session.settings.listener || session.settings.admins?.[userId] || session.settings.moderators?.[userId]) { + delete this.sessions.private[sessionId]; + delete this.users[userId].sessions[sessionId]; if(clear) { if(session.settings.admins?.[userId]) delete (this.sessions.shared[sessionId].settings?.admins as any)[userId]; if(session.settings.moderators?.[userId]) delete (this.sessions.shared[sessionId].settings?.moderators as any)[userId]; } - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'unsubscribeFromSession',args:[session._id, userId, clear]}); - } else { - this.unsubsribeFromSession(session, userId, clear); - } } } else if (this.sessions.shared[sessionId]) { delete this.sessions.shared.settings.users[userId]; - delete this.users[userId]?.sessions[sessionId]; - delete this.users[userId]?.sessionSubs?.[sessionId]; + delete this.users[userId].sessions[sessionId]; if(clear) { if(session.settings.admins?.[userId]) delete (this.sessions.shared[sessionId].settings?.admins as any)[userId]; if(session.settings.moderators?.[userId]) delete (this.sessions.shared[sessionId].settings?.moderators as any)[userId]; if(session.data.shared[userId]) delete this.sessions.shared[sessionId].data?.shared[userId]; if(session.settings.host === userId) { - this.swapHost(session, undefined, true); - delete session.data.shared[userId]; + delete session.settings.host; + delete session.data.shared; + session.data.shared = {}; + this.swapHost(session); } } - if(remoteUser && this.users[userId]?.send) { - this.users[userId].send({route:'unsubscribeFromSession',args:[session._id, userId, clear]}); - } else { - this.unsubsribeFromSession(session, userId, clear); - } } return true; } return false; } - //Delete a session. Run this at the session host location - deleteSession = (session:string|OneWaySessionProps|SharedSessionProps, userId:string, remoteUsers=true) => { - - if(typeof session === 'string') { - let id = session; - session = this.sessions.oneWay[id]; - if(!session) session = this.sessions.shared[id]; - } - if(session) { - if(session.source === userId || session.listener === userId || session.admins?.[userId] || session.ownerId === userId) { - for(const user in session.settings.users) { - if(this.users[user]?.sessions) delete this.users[user].sessions[session._id]; - if(this.users[user]?.sessionSubs) delete this.users[user].sessionSubs[session._id]; - if(remoteUsers) { - if(session.users) { - for(const key in session.users) { - if(this.users[key]?.send) - this.users[key].send({route:'unsubscribeFromSession',args:[session._id, key]}); - } - } - else if(session.listener) { - if(this.users[session.listener]?.send) - this.users[session.listener].send({route:'unsubscribeFromSession',args:[session._id, session.listener]}); - } else if (this.users[userId]?.send) { - this.users[userId].send({route:'unsubscribeFromSession',args:[session._id, userId]}); - } - } else { - this.unsubsribeFromSession(session, user); - } - } - if(this.sessions.oneWay[session._id]) delete this.sessions.oneWay[session._id]; - else if(this.sessions.shared[session._id]) delete this.sessions.oneWay[session._id]; - if(session.onclose) session.onclose(session); - } - } - return true; - } - getFirstMatch(obj1:{[key:string]:any},obj2:{[key:string]:any}) { for(const i in obj1) { - if(i in obj2) return i; + for(const j in obj2) { + if(i === j) return i; + } } return false; } swapHost = ( - session:OneWaySessionProps|SharedSessionProps|string, - newHostId?:string, - adoptData:boolean=true, //copy original session hosts data? - remoteUser=true + session:PrivateSessionProps|SharedSessionProps|string, + newHostId?:string ) => { if(typeof session === 'string') { - if(this.sessions.oneWay[session]) session = this.sessions.oneWay[session]; + if(this.sessions.private[session]) session = this.sessions.private[session]; else if(this.sessions.shared[session]) session = this.sessions.shared[session]; } if(typeof session === 'object' && session.settings) { - let oldHost = session.settings.host; delete session.settings.host; if(newHostId) { if(session.settings.users[newHostId]) session.settings.host = newHostId; @@ -552,112 +310,71 @@ export class SessionsService extends Service { if(match) session.settings.host = match; }//sendAll leadership when host swapping if(!session.settings.host) session.settings.host = Object.keys(session.settings.users)[0]; //replace host - if(adoptData && oldHost && session.settings.inheritHostData !== false) { - if(session.data?.shared[oldHost]) { //oneWay data will stay the same - if(session.data?.shared[oldHost]) { - session.data.shared[session.settings.host] = Object.assign( - session.data.shared[session.settings.host] ? session.data.shared[session.settings.host] : {}, - session.data.shared[oldHost] - ); - if(remoteUser) { + return true; + } + return false; + } - } - } + deleteSession = (sessionId:string, userId:string) => { + let session:any = this.sessions.private[sessionId]; + if(!session) session = this.sessions.shared[sessionId]; + if(session) { + if(session.source === userId || session.listener === userId || session.admins?.[userId] || session.ownerId === userId) { + for(const user in session.settings.users) { + if(this.users[user].sessions) delete this.users[user].sessions[sessionId]; } + if(this.sessions.private[sessionId]) delete this.sessions.private[sessionId] + else if(this.sessions.shared[sessionId]) delete this.sessions.private[sessionId] } - return true; } - return false; + return true; } - //run these on the clientside user subscribeToSession = ( - session:SharedSessionProps|OneWaySessionProps|string, + session:SharedSessionProps|PrivateSessionProps|string, userId:string, - onmessage?:(session:SharedSessionProps|OneWaySessionProps, update:any, user:SessionUser)=>void, - onopen?:(session:SharedSessionProps|OneWaySessionProps, user:SessionUser)=>void, - onclose?:(session:SharedSessionProps|OneWaySessionProps, user:SessionUser)=>void + onmessage?:(session:SharedSessionProps|PrivateSessionProps, userId:string)=>void, + onopen?:(session:SharedSessionProps|PrivateSessionProps, userId:string)=>void, + onclose?:(session:SharedSessionProps|PrivateSessionProps, userId:string)=>void ) => { if(typeof session === 'string') { - let s = this.sessions.oneWay[session]; + let s = this.sessions.private[session]; if(!s) s = this.sessions.shared[session] as any; if(!s) return undefined; session = s; - } - - let user = this.users[userId]; - if(!user) return undefined; - if(!user.sessionSubs) user.sessionSubs = {}; - if(!user.sessionSubs[session._id]) user.sessionSubs[session._id] = {}; - - if(onmessage) user.sessionSubs[session._id].onmessage = onmessage; - if(onopen) this.sessionSubs[userId][session._id].onopen = onopen; - if(onclose) user.sessionSubs[session._id].onclose = onclose; - if(typeof onopen === 'function') { + } + + if(typeof session.onopen === 'function') { let sub = this.subscribe('joinSession',(res) => { - if(res._id === (session as any)._id) - this.sessionSubs[userId][(session as any)._id].onopen(session as any, user); + if(res._id === (session as any)._id) (session as any).onopen(session, userId); this.unsubscribe('joinSession', sub as number); - }); - user.sessionSubs[session._id].onopenSub = sub; + }) } - - return session; - } - - //run these on the clientside user - unsubsribeFromSession = ( - session:SharedSessionProps|OneWaySessionProps|string, - userId?:string, - clear=true //clear session data (default true) - ) => { - if(typeof session === 'string') { - let s = this.sessions.oneWay[session]; - if(!s) s = this.sessions.shared[session] as any; - if(!s) return undefined; - session = s; - } - const clearSessionSubs = (Id:string, s:SharedSessionProps|OneWaySessionProps) => { - let u = this.users[Id]; - if(!u) return undefined; - if(u.sessionSubs?.[s._id]) { - if(u.sessionSubs[s._id].onopenSub) { - this.unsubscribe('joinSession', u.sessionSubs[s._id].onopenSub as number); - } - } - if(u.sessionSubs[s._id].onclose) u.sessionSubs[s._id].onclose(s as any, u); - delete u.sessionSubs[s._id]; - } + if(typeof session === 'object') { //we need to fire onmessage events when the session updates (setState for sessionId) and when the user updates - if(userId) { - clearSessionSubs(userId, session); - } else { - for(const key in this.users) { - clearSessionSubs(key, session); - } - } + if(onmessage) session.onmessage = onmessage; + if(onopen) session.onclose = onopen; + if(onclose) session.onclose = onclose; - if(clear) { - if(this.sessions.oneWay[session._id]) delete this.sessions.oneWay[session._id]; - else if(this.sessions.shared[session._id]) delete this.sessions.shared[session._id]; + + // if(typeof session.onmessage === 'function') + // this.subscribe(session._id,(session)=>{ session.onmessage(session,userId); }); + + // this.setState({[session._id]:session}); } + return session; } //iterate all subscriptions, e.g. run on backend - sessionUpdateCheck = ( - sessionHasUpdate?:( - session:OneWaySessionProps|SharedSessionProps, - update:{shared?:any,oneWay?:any} - )=>void,transmit=true - ) => { + sessionUpdateCheck = (transmit=true) => { let updates:any = { - oneWay:{}, + private:{}, shared:{} }; - for(const session in this.sessions.oneWay) { - const sesh = this.sessions.oneWay[session]; + for(const session in this.sessions.private) { + const sesh = this.sessions.private[session]; const updateObj = { _id:sesh._id, settings:{ @@ -667,31 +384,27 @@ export class SessionsService extends Service { data:{} } as any; //pull user's updated props and send to listener if(!this.users[sesh.source]) { - delete this.sessions.oneWay[session]; - continue; - } + delete this.sessions.private[session] + break; + } if(sesh.settings && sesh.data) { for(const prop in sesh.settings.propnames) { - if(prop in this.users[sesh.source]) { - if(this.sessions.oneWay[session].data) { + if( this.users[sesh.source][prop]) { + if(this.sessions.private[session].data) { if(typeof sesh.data[prop] === 'object') { if(this.users[sesh.source][prop] && (stringifyFast(sesh.data[prop]) !== stringifyFast(this.users[sesh.source][prop]) || !(prop in sesh.data))) updateObj.data[prop] = this.users[sesh.source][prop]; } - else if(prop in this.users[sesh.source] && (sesh.data[prop] !== this.users[sesh.source][prop] || !(prop in sesh.data))) + else if(this.users[sesh.source][prop] && (sesh.data[prop] !== this.users[sesh.source][prop] || !(prop in sesh.data))) updateObj.data[prop] = this.users[sesh.source][prop]; } else updateObj.data[prop] = this.users[sesh.source][prop]; - } else if(this.sessions.oneWay[session]?.data && prop in this.sessions.oneWay[session]?.data) - delete (this.sessions.oneWay[session].data as any)[prop]; + } else if(this.sessions.private[session]?.data?.[prop]) delete (this.sessions.private[session].data as any)[prop]; } } if(Object.keys(updateObj.data).length > 0) { - this.recursivelyAssign(this.sessions.oneWay[session].data, updateObj.data); //set latest data on the source object as reference - updates.oneWay[sesh._id as string] = updateObj; - - if(sessionHasUpdate) sessionHasUpdate(sesh,updateObj); - if(sesh.settings.onhasupdate) sesh.onhasupdate(sesh,updateObj); + this.recursivelyAssign(this.sessions.private[session].data, updateObj.data); //set latest data on the source object as reference + updates.private[sesh._id as string] = updateObj; } } @@ -706,99 +419,85 @@ export class SessionsService extends Service { } as any; if(sesh.settings?.host) { //host receives object of all other users - const oneWayData = {}; //host receives all users' props + const privateData = {}; //host receives all users' props const sharedData = {}; //users receive host props for(const user in sesh.settings.users) { - if(!this.users[user]) { //if no user found assume they're to be kicked from session + if(!this.users[user]) { delete sesh.settings.users[user]; //dont need to delete admins, mods, etc as they might want to come back <_< - if( sesh.settings.host === user ) - this.swapHost(sesh, undefined, true); - if( sesh.data?.shared[user] ) - delete sesh.data.shared[user]; - if( sesh.data?.oneWay?.[user] ) - delete sesh.data.shared[user]; + if( sesh.data?.shared[user]) delete sesh.data.shared[user]; + if( sesh.data?.private?.[user]) delete sesh.data.shared[user]; + if(sesh.settings.host === user) this.swapHost(sesh); updateObj.settings.users = sesh.settings.users; updateObj.settings.host = sesh.settings.host; continue; - } else if (sesh.settings.newUser) { //propagate who joined the room too - updateObj.settings.users = sesh.settings.users; - updateObj.settings.host = sesh.settings.host; - sesh.settings.newUser = false; } - if(user !== sesh.settings.host) { //the host will receive the oneWay data - oneWayData[user] = {}; + if(user !== sesh.settings.host) { + privateData[user] = {}; for(const prop in sesh.settings.propnames) { - if(prop in this.users[user]) { - if(sesh.data?.oneWay && !(user in sesh.data.oneWay)) { - if(typeof this.users[user][prop] === 'object') - oneWayData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); - else oneWayData[user][prop] = this.users[user][prop]; - } else if(typeof oneWayData[user][prop] === 'object' && sesh.data) { - if(prop in this.users[user][prop] && (stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data))) - oneWayData[user][prop] = this.users[user][prop]; + if(this.users[user][prop]) { + if(sesh.data?.private && !(user in sesh.data.private)) { + if(typeof this.users[user][prop] === 'object') privateData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); + else privateData[user][prop] = this.users[user][prop]; + } else if(typeof privateData[user][prop] === 'object' && sesh.data) { + if(this.users[user][prop] && (stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data))) + privateData[user][prop] = this.users[user][prop]; } - else if(this.users[user][prop] && sesh.data?.oneWay?.[prop] !== this.users[user][prop]) - oneWayData[user][prop] = this.users[user][prop]; - } else if (sesh.data?.oneWay?.[user] && prop in sesh.data?.oneWay?.[user]) - delete sesh.data.oneWay[user][prop]; //if user deleted the prop, session can delete it + else if(this.users[user][prop] && sesh.data?.private?.[prop] !== this.users[user][prop]) + privateData[user][prop] = this.users[user][prop]; + } else if (sesh.data?.private?.[user]?.[prop]) delete sesh.data.private[user][prop]; //if user deleted the prop, session can delete it } - if(Object.keys(oneWayData[user]).length === 0) - delete oneWayData[user]; - } else { //the rest of the users will receive the shared data + if(Object.keys(privateData[user]).length === 0) delete privateData[user]; + } else { sharedData[user] = {}; for(const prop in sesh.settings.hostprops) { - if(prop in this.users[user]) { + if(this.users[user][prop]) { if(sesh.data && !(user in sesh.data.shared)) { - if(typeof this.users[user][prop] === 'object') - sharedData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); + if(typeof this.users[user][prop] === 'object') sharedData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); else sharedData[user][prop] = this.users[user][prop]; } else if(typeof sharedData[user][prop] === 'object' && sesh.data) { - if((stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data.shared[user]))) + if(this.users[user][prop] && (stringifyFast(sesh.data?.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data.shared[user]))) sharedData[user][prop] = this.users[user][prop]; - } else if(sesh.data?.shared[user][prop] !== this.users[user][prop]) + } + else if(this.users[user][prop] && sesh.data?.shared[user][prop] !== this.users[user][prop]) sharedData[user][prop] = this.users[user][prop]; - } else if (sesh.data?.shared[user] && prop in sesh.data?.shared[user]) - delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it + } else if (sesh.data?.shared[user]?.[prop]) delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it } } } - if(Object.keys(oneWayData).length > 0) { - updateObj.data.oneWay = oneWayData; + if(Object.keys(privateData).length > 0) { + updateObj.data.private = privateData; } if(Object.keys(sharedData).length > 0) { updateObj.data.shared = sharedData; } - } else { //all users receive the same update via shared data when no host set + } else { //all users receive the same update when no host set const sharedData = {}; //users receive all other user's props if(sesh.settings?.users) { for(const user in sesh.settings.users) { - if(!this.users[user]) { //if no user found assume they're to be kicked from session + if(!this.users[user]) { delete sesh.settings.users[user]; //dont need to delete admins, mods, etc as they might want to come back <_< - if( sesh.settings.host === user ) - this.swapHost(sesh, undefined, true); - if( sesh.data?.shared[user] ) - delete sesh.data.shared[user]; - if( sesh.data?.oneWay?.[user] ) - delete sesh.data.shared[user]; + if( sesh.data?.shared[user]) delete sesh.data.shared[user]; + if( sesh.data?.private?.[user]) delete sesh.data.shared[user]; + if(sesh.settings.host === user) this.swapHost(sesh); updateObj.settings.users = sesh.settings.users; updateObj.settings.host = sesh.settings.host; continue; } sharedData[user] = {}; for(const prop in sesh.settings.propnames) { - if(prop in this.users[user]) { + if(this.users[user][prop]) { if(sesh.data && !(user in sesh.data.shared)) { if(typeof this.users[user][prop] === 'object') sharedData[user][prop] = this.recursivelyAssign({},this.users[user][prop]); else sharedData[user][prop] = this.users[user][prop]; - } else if(typeof sesh.data?.shared[user]?.[prop] === 'object') { + } else if(typeof sesh.data?.shared[user][prop] === 'object') { if((stringifyFast(sesh.data.shared[user][prop]) !== stringifyFast(this.users[user][prop]) || !(prop in sesh.data.shared[user]))) { //if(stringifyFast(this.users[user][prop]).includes('peer')) console.log(stringifyFast(this.users[user][prop])) sharedData[user][prop] = this.users[user][prop]; } - } else if(sesh.data?.shared[user]?.[prop] !== this.users[user][prop]) + } + else if(sesh.data?.shared[user][prop] !== this.users[user][prop]) sharedData[user][prop] = this.users[user][prop]; - } else if (sesh.data?.shared[user] && prop in sesh.data?.shared[user]) - delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it + } else if (sesh.data?.shared[user]?.[prop]) delete sesh.data.shared[user][prop]; //if user deleted the prop, session can delete it } if(Object.keys(sharedData[user]).length === 0) delete sharedData[user]; } @@ -806,26 +505,24 @@ export class SessionsService extends Service { //console.log(sharedData); updateObj.data.shared = sharedData; } - } + } } - if(updateObj.data.shared || updateObj.data.oneWay) { + if(updateObj.data.shared || updateObj.data.private) updates.shared[sesh._id as string] = updateObj; - if(updateObj.data.shared) { - Object.assign(this.sessions.shared[session].data?.shared, updateObj.data.shared); - //set latest data on the source object as reference - } - if(updateObj.data.oneWay) { - Object.assign(this.sessions.shared[session].data?.oneWay, updateObj.data.oneWay); - //set latest data on the source object as reference - } - if(sessionHasUpdate) sessionHasUpdate(sesh,updateObj); - if(sesh.settings.onhasupdate) sesh.settings.onhasupdate(sesh,updateObj); + + if(updateObj.data.shared) { + this.recursivelyAssign(this.sessions.shared[session].data?.shared,updateObj.data.shared) + //set latest data on the source object as reference + } + if(updateObj.data.private) { + this.recursivelyAssign(this.sessions.shared[session].data?.private,updateObj.data.private) + //set latest data on the source object as reference } } - if(Object.keys(updates.oneWay).length === 0) delete updates.oneWay; + if(Object.keys(updates.private).length === 0) delete updates.private; if(Object.keys(updates.shared).length === 0) delete updates.shared; if(Object.keys(updates).length === 0) return undefined; @@ -838,82 +535,91 @@ export class SessionsService extends Service { } - //transmit updates to users and setState locally based on userId. Todo: this could be more efficient + //transmit updates to users and setState locally based on userId transmitSessionUpdates = (updates:{ - oneWay:{[key:string]:any}, + private:{[key:string]:any}, shared:{[key:string]:any} }) => { let users = {}; - if(updates.oneWay) { - for(const s in updates.oneWay) { //oneWay session ids - let session = this.sessions.oneWay[s]; + if(updates.private) { + for(const s in updates.private) { + let session = this.sessions.private[s]; if(session?.settings) { - let u = session.settings.listener; //single user listener - if(!users[u]) users[u] = {}; - users[u].oneWay[s] = updates.oneWay[s]; + let u = session.settings.listener; + if(!users[u]) users[u] = {private:{}}; + else if(!users[u].private) users[u].private = {}; + users[u].private[s] = updates.private[s]; } } } if(updates.shared) { - for(const s in updates.shared) { //shared session ids + for(const s in updates.shared) { let session = this.sessions.shared[s]; if(session?.settings) { - for(const u in session.settings.users) { //for users in session - if(!users[u]) users[u] = {}; - users[u].shared[s] = updates.shared[s]; + let copy; + if(session.settings.host) { + copy = Object.assign({},updates.shared[s]); + delete copy.data.private; + } + for(const u in session.settings.users) { + if(!users[u]) users[u] = {shared:{}}; + else if(!users[u].shared) users[u].shared = {}; + if(session.settings.host) { + if(u !== session.settings.host) { + users[u].shared[s] = copy; + } else users[u].shared[s] = updates.shared[s]; + } + else users[u].shared[s] = updates.shared[s]; } } } } - //each user will receive an update for all sessions they are subscribed to //console.log(users) let message = {route:'receiveSessionUpdates', args:null as any} for(const u in users) { message.args = [u, users[u]]; - if((this.users[u] as any)?.send) (this.users[u] as any).send(JSON.stringify(message)); + if((this.users[u] as any).send) (this.users[u] as any).send(JSON.stringify(message)); this.setState({[u]:Object.create(message)}) } return users; } - //receive updates as a user - receiveSessionUpdates = (origin:any, update:{oneWay:{[key:string]:any},shared:{[key:string]:any}}|string) => { //following operator format we get the origin passed + //receive updates as users + receiveSessionUpdates = (origin:any, update:{private:{[key:string]:any},shared:{[key:string]:any}}|string) => { //following operator format we get the origin passed if(update) if(typeof update === 'string') update = JSON.parse(update as string); if(typeof update === 'object') { let user = this.users[origin]; - if(user) { - if(!user.sessions) user.sessions = {oneWay:{},shared:{}}; - if(!user.sessionSubs) user.sessionSubs = {}; - } - - if(update.oneWay) { - for(const key in update.oneWay) { - this.recursivelyAssign(this.sessions.oneWay[key].data, update.oneWay[key].data); - if(this.sessions.oneWay[key]?.settings.onmessage) - this.sessions.oneWay[key].settings.onmessage(this.sessions.oneWay[key], update.oneWay[key]); - if(user?.sessionSubs[user._id]?.[key]?.onmessage) - user.sessionSubs[user._id][key].onmessage(user.sessions[key], update, user); + if(!user) return undefined; + if(!user.sessions) user.sessions = {}; + + if(update.private) { + for(const key in update.private) { + if(!user.sessions[key]) continue; + this.recursivelyAssign(user.sessions[key].data,update.private[key].data); + if(user.sessions[key].onmessage) + user.sessions[key].onmessage(user.sessions[key],user._id) } } if(update.shared) { for(const key in update.shared) { - if(update.shared[key].settings.users) this.sessions.shared[key].settings.users = update.shared[key].settings.users; - if(update.shared[key].settings.host) this.sessions.shared[key].settings.host = update.shared[key].settings.host; - if(update.shared[key].data.oneWay) this.recursivelyAssign(this.sessions.shared[key].data.oneWay, update.shared[key].data.oneWay); - if(update.shared[key].data.shared) this.recursivelyAssign(this.sessions.shared[key].data.shared, update.shared[key].data.shared); - if(this.sessions.shared[key]?.settings.onmessage) - this.sessions.shared[key].settings.onmessage(this.sessions.shared[key], update.shared[key]); - if(user?.sessionSubs[user._id]?.[key]?.onmessage) - user.sessionSubs[user._id][key].onmessage(user.sessions[key], update, user); + if(!user.sessions[key]) continue; + if(update.shared[key].settings.users) user.sessions[key].settings.users = update.shared[key].settings.users; + if(update.shared[key].settings.host) user.sessions[key].settings.host = update.shared[key].settings.host; + if(update.shared[key].data.private) this.recursivelyAssign(user.sessions[key].data.private, update.shared[key].data.private); + if(update.shared[key].data.shared) this.recursivelyAssign(user.sessions[key].data.shared, update.shared[key].data.shared); + if(user.sessions[key].onmessage) + user.sessions[key].onmessage(user.sessions[key],user._id) } } return user; } } + //you either need to run this loop on a session to + // pass updates up to the server from your user manually getUpdatedUserData = (user:SessionUser) => { const updateObj = {}; for(const key in user.sessions) { @@ -962,7 +668,7 @@ export class SessionsService extends Service { } //e.g. run on frontend - userUpdateCheck = (user:SessionUser, onupdate?:(user:SessionUser, updateObj:{[key:string]:any})=>void) => { + userUpdateCheck = (user:SessionUser) => { //console.log('checking',user, this); if(user.sessions) { const updateObj = this.getUpdatedUserData(user); @@ -972,8 +678,7 @@ export class SessionsService extends Service { if(Object.keys(updateObj).length > 0) { let message = { route:'setUserProps', args:[user._id, updateObj] }; if(user.send) user.send(message); - this.setState({[user._id]:message}); - if(onupdate) { onupdate(user, updateObj) }; + this.setState({[user._id]:message}) return updateObj; } } @@ -995,17 +700,6 @@ export class SessionsService extends Service { return true; } - userUpdateLoop = { //this node loop will run separately from the one below it - __operator:this.userUpdateCheck, - __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O - } - - sessionLoop = { - __operator:this.sessionUpdateCheck, - __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O - } - - //more general object streaming //more rudimentary object streaming than the above sessions @@ -1188,7 +882,7 @@ export class SessionsService extends Service { //can remove a whole stream or just a key from a stream if supplied removeStream = (streamName,key) => { - if(streamName && this.streamSettings[streamName] && !key) { + if(streamName && !key) { if(this.streamSettings[streamName].onclose) (this.streamSettings[streamName] as any).onclose(this.streamSettings[streamName]); this.unsubscribe(streamName); //remove the subscriptions to this stream @@ -1246,6 +940,16 @@ export class SessionsService extends Service { __node:{loop:10} } + userUpdateLoop = { //this node loop will run separately from the one below it + __operator:this.userUpdateCheck, + __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O + } + + sessionLoop = { + __operator:this.sessionUpdateCheck, + __node:{loop:10}//this will set state each iteration so we can trigger subscriptions on session updates :O + } + } \ No newline at end of file diff --git a/src/services/sse/SSE.browser.ts b/services/sse/SSE.browser.ts similarity index 84% rename from src/services/sse/SSE.browser.ts rename to services/sse/SSE.browser.ts index cdd35c15..04de465c 100644 --- a/src/services/sse/SSE.browser.ts +++ b/services/sse/SSE.browser.ts @@ -27,7 +27,7 @@ export type EventSourceInfo = { request:(message:any, method?:string)=>Promise, post:(route:any, args?:any)=>void, run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number)=>Promise, terminate:() => void, graph:SSEfrontend @@ -47,7 +47,7 @@ export class SSEfrontend extends Service { constructor(options?:ServiceOptions) { super(options); - this.load(this); + this.setTree(this); } openSSE = ( @@ -64,36 +64,26 @@ export class SSEfrontend extends Service { if(!('keepState' in options)) options.keepState = true; //default true if(!options.events) options.events = {}; - let close; if(options.events.close) { - close = options.events.close; + let close = options.events.close; + options.events.close = (ev) => { if(sse.onclose) sse.onclose(ev,sse); close(ev,sse); }; } - options.events.close = (ev) => { - if(sse.onclose) sse.onclose(ev, sse); - if(close) close(ev,sse); - delete this.eventsources[options.url]; - }; - - let open; if(options.events.open) { - open = options.events.open; + let open = options.events.open; + options.events.open = (ev) => { if(sse.onopen) sse.onopen(ev,sse); open(ev,sse); }; } - options.events.open = (ev) => { if(sse.onopen) sse.onopen(ev,sse); if(open) open(ev,sse); }; - - let error; if(options.events.error) { - error = options.events.error; + let error = options.events.error; + options.events.error = (ev) => { if(sse.onerror) sse.onerror(ev,sse); error(ev,sse); }; } - options.events.error = (ev) => { if(sse.onerror) sse.onerror(ev,sse); if(error) error(ev,sse); }; - - let message; if(options.events.message) { - message = options.events.message; + let message = options.events.message; + options.events.message = (ev) => { if(sse.onmessage) sse.onmessage(ev,sse); message(ev,sse); }; } - if(!sse.onmessage) { - //default hook - sse.onmessage = (ev, sse) => { + if(!options.events.message) { + options.events.message = (ev, sse) => { + let data = ev.data; if(data) if(typeof data === 'string') { @@ -103,7 +93,7 @@ export class SSEfrontend extends Service { if(data[0] === '"') { data = data.substring(1,data.length-1)}; //console.log(message) data = JSON.parse(data); //parse stringified objects - + if(data.route === 'setId' && sse) { sse._id = data.args; options.events.message = (e, sse) => { //clear extra logic after id is set @@ -113,18 +103,11 @@ export class SSEfrontend extends Service { } } } - + const result = this.receive(ev.data,sse); - if(options.keepState) this.setState({[options.url]:data}); + if(options.keepState) this.setState({[options.url]:data}); } } - - options.events.message = (ev) => { - if(sse.onmessage) sse.onmessage(ev,sse); - if(message) message(ev,sse); - }; - - if(!options.events.error) options.events.error = (ev, sse) => { this.terminate(sse as any); delete this.eventsources[options.url]; @@ -151,7 +134,7 @@ export class SSEfrontend extends Service { } let request = (message:ServiceMessage|any, method?:string, sessionId?:string) => { - return this.request(message, options.url, method, sessionId); + return this.request(message, options.url, sessionId, method); } let post = (route:any, args?:any, method?:string) => { @@ -169,8 +152,8 @@ export class SSEfrontend extends Service { return this.request({route,args}, options.url, method, sessionId); } - let subscribe = (route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean):Promise => { - return this.subscribeToSSE(route, options.url, callback, args, key, subInput, sse._id); + let subscribe = (route:any, callback?:((res:any)=>void)|string):Promise => { + return this.subscribeToSSE(route, options.url, callback, sse._id); } let unsubscribe = (route:any, sub:number):Promise => { @@ -204,7 +187,7 @@ export class SSEfrontend extends Service { type:XMLHttpRequestResponseType='', mimeType?:string|undefined ) => { - if(typeof message === 'number' || (typeof message === 'object' && !message.byteLength && (type === 'json' || type === 'text' || !type))) { + if(typeof message === 'object' && (type === 'json' || type === 'text' || !type)) { message = JSON.stringify(message); } @@ -285,22 +268,15 @@ export class SSEfrontend extends Service { return res; } - subscribeSSE = ( - route:string, - url:string, - args?:any[], - key?:string, - subInput?:boolean - ) => { - if(this.restrict?.[route]) return undefined; + subscribeSSE = (route:string,url:string,key?:string,subInput?:boolean) => { return this.subscribe(route,(res) => { this.POST(res,url,'json'); - },args,key,subInput) + },key,subInput) } - subscribeToSSE = (route:string, url:string, callback?:string|((res:any)=>void), args?:any[], key?:string, subInput?:boolean, sessionId?:string) => { + subscribeToSSE = (route:string, url:string, callback?:string|((res:any)=>void), sessionId?:string, key?:string, subInput?:boolean) => { if(url) { - this.__node.state.subscribeEvent(url,(res) => { + this.__node.state.subscribeTrigger(url,(res) => { let msg = JSON.parse(res); if(msg?.callbackId === route) { if(!callback) this.setState({[url]:msg.args}); //just set state @@ -311,7 +287,7 @@ export class SSEfrontend extends Service { } }); - return this.eventsources[url].run('subscribeSSE',[route,url,args,key,subInput,sessionId]); + return this.eventsources[url].run('subscribeSSE',[route,url,sessionId,key,subInput]); } } diff --git a/src/services/sse/SSE.node.ts b/services/sse/SSE.node.ts similarity index 89% rename from src/services/sse/SSE.node.ts rename to services/sse/SSE.node.ts index f4a26ce5..bf038f9f 100644 --- a/src/services/sse/SSE.node.ts +++ b/services/sse/SSE.node.ts @@ -1,5 +1,5 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import {createSession, createChannel, Session, Channel} from 'better-sse'; //third party lib. SSEs really just push notifications to an http endpoint but it's minimal overhead +import {createSession, createChannel, Session, SessionState, Channel} from 'better-sse'; //third party lib. SSEs really just push notifications to an http endpoint but it's minimal overhead import http from 'http' import https from 'https' import { Readable } from "node:stream"; @@ -21,14 +21,14 @@ export type SSEProps = { export type SSEChannelInfo = { channel: Channel>, sessions:{ - [key:string]:Session + [key:string]:Session }, requests:{[key:string]:Function}, //outstanding request promises send:(message:any, eventName?:string, sessionId?:string)=>any, request:(message:any, method?:string, sessionId?:string, eventName?:string)=>Promise|Promise[], post:(route:any, args?:any, method?:string, sessionId?:string, eventName?:string)=>void, run:(route:any, args?:any, method?:string, sessionId?:string, eventName?:string)=>Promise|Promise[], - subscribe:(route:any, callback?:((res:any)=>void)|string,args?:any[],key?:string,subInput?:boolean,sessionId?:string,eventName?:string)=>Promise|Promise[]|undefined, + subscribe:(route:any, callback?:((res:any)=>void)|string, sessionId?:string)=>Promise|Promise[]|undefined, unsubscribe:(route:any, sub:number, sessionId?:string, eventName?:string)=>Promise|Promise[], terminate:() => boolean, _id:string, @@ -37,14 +37,13 @@ export type SSEChannelInfo = { export type SSEClientInfo = { _id:string, - session:Session, + session:Session, served:SSEChannelInfo, send:(message:any, eventName?:string)=>any, request:(message:any, method?:string, eventName?:string)=>Promise, post:(route:any, args?:any, method?:string, eventName?:string)=>void, run:(route:any, args?:any, method?:string, eventName?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, - args?:any[],key?:string,subInput?:boolean,sessionId?:string,eventName?:string)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number, eventName?:string)=>Promise, terminate:() => boolean, onclose?:(session:any,sseinfo:any,_id:string,req:http.IncomingMessage,res:http.ServerResponse)=>void, @@ -72,10 +71,10 @@ export class SSEbackend extends Service { constructor(options?:ServiceOptions) { super(options) - this.load(this); + this.setTree(this); } - openSSE = (options:SSEProps) => { + setupSSE = (options:SSEProps) => { const server = options.server; let path = options.path; @@ -98,7 +97,9 @@ export class SSEbackend extends Service { sse._id = options._id ? options._id : path; - + if(!sse.onconnectionclose) sse.onconnectionclose = (session,sse,id,req,res) => { + delete sse.sessions[id]; + } const send = ( message:any, //the data you want to send @@ -146,10 +147,8 @@ export class SSEbackend extends Service { return this.request(r, path, method, sessionId, eventName) } - let subscribe = (route:any, callback?:((res:any)=>void)|string, - args?:any[],key?:string,subInput?:boolean, - sessionId?:string, eventName?:string):Promise|Promise[]|undefined => { - return this.subscribeToSSE(route, options.url, callback, args, key, subInput, sessionId, eventName); + let subscribe = (route:any, callback?:((res:any)=>void)|string, sessionId?:string):Promise|Promise[]|undefined => { + return this.subscribeToSSE(route, options.url, callback, sessionId); } let unsubscribe = (route:any, sub:number, sessionId?:string, eventName?:string):Promise|Promise[] => { @@ -194,7 +193,7 @@ export class SSEbackend extends Service { return run(route,args,method,_id,eventName); }, subscribe:(route,callback?)=>{ - return subscribe(route,callback,undefined,_id); + return subscribe(route,callback,_id); }, unsubscribe:(route,sub,eventName?)=>{ return unsubscribe(route,sub,_id,eventName); @@ -204,22 +203,12 @@ export class SSEbackend extends Service { delete sse.sessions[_id]; return true; }, - onclose:(session,sse,_id,req,res)=>{ - if(sse.onconnectionclose) sse.onconnectionclose(session,sse,_id,req,res); - }, + onclose:()=>options.onconnectionclose, graph:this } as SSEClientInfo; session.push(JSON.stringify({route:'setId',args:_id})); //associate this user's connection with a server generated id - session.on('close',()=>{ - let obj = this.eventsources[_id]; - let onclose = obj.onclose; - - delete this.eventsources[_id]; - - if(onclose) - (obj as any).onclose(session,sse,_id,req,response); - }) + session.on('close',()=>{if(this.eventsources[_id].onclose) (this.eventsources[_id] as any).onclose(session,sse,_id,req,response)}) if(sse.onconnection) {sse.onconnection(session,sse,_id,req,response);} }); @@ -249,7 +238,7 @@ export class SSEbackend extends Service { if(typeof body.route === 'string') { if(body.route.includes('/') && body.route.length > 1) body.route = body.route.split('/').pop(); - route = this.__node.roots?.[body.route]; + route = this.__node.tree[body.route]; } } @@ -295,7 +284,7 @@ export class SSEbackend extends Service { } - open = this.openSSE; + open = this.setupSSE; streamIterable = ( path:string, @@ -347,8 +336,8 @@ export class SSEbackend extends Service { eventName?:string, //event name? default is 'message' sessionId?:string //particular client? ) => { - if(!path && ((typeof data === 'object' && !data.byteLength) || typeof data === 'number')) { - if(data?.route) { + if(!path && typeof data === 'object') { + if(data.route) { let keys = Object.keys(this.servers) if(keys.length > 0) { @@ -454,15 +443,13 @@ export class SSEbackend extends Service { subscribeSSE = ( route:string, path:string, - args?:any[],key?:string,subInput?:boolean, sessionId?:string, eventName?:string ) => { - if(this.restrict?.[route]) return undefined; if(this.servers[path]) { return this.subscribe(route, (res) => { this.servers[path].send({args:res, callbackId:route}, eventName, sessionId); - }, args, key, subInput); + }) } } @@ -470,12 +457,11 @@ export class SSEbackend extends Service { route:string, path:string, callback?:string|((res:any)=>void), - args?:any[],key?:string,subInput?:boolean, sessionId?:string, eventName?:string ) => { if(this.servers[path]) { - this.__node.state.subscribeEvent(path,(res) => { + this.__node.state.subscribeTrigger(path,(res) => { if(res?.callbackId === route) { if(!callback) this.setState({[path]:res.args}); //just set state else if(typeof callback === 'string') { //run a local node @@ -489,7 +475,7 @@ export class SSEbackend extends Service { if(this.servers[path].sessions[sessionId]) { return this.eventsources[sessionId].run( 'subscribeSSE', - {route:'subscribeSSE',args:[route,path,args,key,subInput]}, + {route:'subscribeSSE',args:[route,path]}, undefined, eventName ) as Promise @@ -500,7 +486,7 @@ export class SSEbackend extends Service { promises.push( this.eventsources[k].run( 'subscribeSSE', - {route:'subscribeSSE',args:[route,path,args,key,subInput]}, + {route:'subscribeSSE',args:[route,path]}, undefined, eventName ) as Promise diff --git a/src/services/todo/BLE.service.ts b/services/todo/BLE.service.ts similarity index 100% rename from src/services/todo/BLE.service.ts rename to services/todo/BLE.service.ts diff --git a/src/services/todo/FS.browser.ts b/services/todo/FS.browser.ts similarity index 100% rename from src/services/todo/FS.browser.ts rename to services/todo/FS.browser.ts diff --git a/src/services/todo/FS.node.ts b/services/todo/FS.node.ts similarity index 100% rename from src/services/todo/FS.node.ts rename to services/todo/FS.node.ts diff --git a/src/services/todo/README.txt b/services/todo/README.txt similarity index 100% rename from src/services/todo/README.txt rename to services/todo/README.txt diff --git a/src/services/todo/Serial.service.ts b/services/todo/Serial.service.ts similarity index 100% rename from src/services/todo/Serial.service.ts rename to services/todo/Serial.service.ts diff --git a/services/unsafe/Unsafe.service.ts b/services/unsafe/Unsafe.service.ts new file mode 100644 index 00000000..2d3e5f27 --- /dev/null +++ b/services/unsafe/Unsafe.service.ts @@ -0,0 +1,151 @@ +import { parseFunctionFromText } from "../utils" +import { Graph } from "../../Graph" +import { Service } from "../Service"; + +//Contains evals and other things you probably don't want wide open on an API +export const unsafeRoutes = { + + //add a route and parse it from text + setRoute:function(fn:string|((...args:[])=>any),fnName?:string){ + //console.log(fn, fnName) + //if(fnName === 'setupChart') console.log(fn); + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //if(fnName === 'setupChart') console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + if(this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__setOperator(fn); //overwrite operator + } + else { + let node = (this.__node.graph as Graph).add({__node:{tag:fnName},__operator:fn}); + } + return true; + } + return false; + }, + setNode:function(fn:string|((...args:[])=>any),fnName?:string){ + //console.log(fn, fnName) + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + if(this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__setOperator(fn); //overwrite operator + } + else (this.__node.graph as Graph).add({__node:{tag:fnName},__operator:fn}); + //console.log(this) + return true; + } + return false; + }, + setMethod:function(route:string,fn:string|((...args:[])=>any),fnName?:string){ //set a method on a route + //console.log(fn, fnName) + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + if(this.__node.graph.get(route)) { + this.__node.graph.get(route)[fnName] = fn; //overwrite method + } + else (this.__node.graph as Graph).add({__node:{tag:fnName,[fnName]:fn}}); + //console.log(this) + return true; + } + return false; + }, + assignRoute:function(route:string,source:{[key:string]:any}) { //set values on a route + //console.log(fn, fnName) + if(this.__node.graph.get(route) && typeof source === 'object') { + Object.assign(this.__node.graph.get(route),source); + } + }, + transferClass:(classObj:any, className?:string)=>{ //send a class over a remote service + if(typeof classObj === 'object') { + let str = classObj.toString();//needs to be a class prototype + let message = {route:'receiveClass',args:[str,className]}; + + return message; + } + return false; + }, + receiveClass:function(stringified:string, className?:string){ //eval a class string and set it as a key on the local graph by class name, so this.__node.graph.method exists + if(typeof stringified === 'string') { + //console.log(stringified) + if(stringified.indexOf('class') === 0) { + let cls = (0,eval)('('+stringified+')'); + let name = className; + + if(!name) + name = cls.name; //get classname + this.__node.graph[name] = cls; + + return true; + } + } + return false; + }, + setGlobal:(key:string, value:any) => { //set a value on the globalThis scope + globalThis[key] = value; + return true; + }, + assignGlobalObject:(target:string, source:{[key:string]:any}) => { //assign a value on an object on the globalThis scope + if(!globalThis[target]) return false; + if(typeof source === 'object') Object.assign(globalThis[target],source); + return true; + }, + setValue:function(key:string, value:any) { //set a value on the graph scope + this.__node.graph[key] = value; + return true; + }, + assignObject:function(target:string, source:{[key:string]:any}){ //assign a value on an object on the globalThis scope + if(!this.__node.graph[target]) return false; + if(typeof source === 'object') Object.assign( this.__node.graph[target],source); + return true; + }, + setGlobalFunction:(fn:any, fnName?:string) => { //set a value on the globalThis scope + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + globalThis[fnName] = fn; + //console.log(this) + return true; + } + return false; + }, + assignFunctionToGlobalObject:function (globalObjectName:string, fn:any, fnName:any) { //assign a value on an object on the globalThis scope + if(! globalThis[globalObjectName]) return false; + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + this.__node.graph[globalObjectName][fnName] = fn; + //console.log(this) + return true; + } + return false; + }, + setFunction:function(fn:any, fnName?:string){ //set a value on the globalThis scope + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + this.__node.graph[fnName] = fn; + //console.log(this) + return true; + } + return false; + }, + assignFunctionToObject:function(objectName:string, fn:any, fnName:any) { //assign a value on an object on the globalThis scope + if(! this.__node.graph[objectName]) return false; + if(typeof fn === 'string') fn = parseFunctionFromText(fn); + //console.log(fn); + if(typeof fn === 'function') { + if(!fnName) fnName = fn.name; + this.__node.graph[objectName][fnName] = fn; + //console.log(this) + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/services/utils.ts b/services/utils.ts similarity index 70% rename from src/services/utils.ts rename to services/utils.ts index 17cad895..253d8874 100644 --- a/src/services/utils.ts +++ b/services/utils.ts @@ -1,56 +1,37 @@ - - -export let recursivelyStringifyFunctions = (obj:{[key:string]:any}) => { - let cpy = {}; - for(const key in obj) { - if(typeof obj[key] === 'object') { - cpy[key] = recursivelyStringifyFunctions(obj[key]); - } - else if (typeof obj[key] === 'function') { - cpy[key] = obj[key].toString(); - } else cpy[key] = obj[key]; - } - return cpy; -} - -export function getFnParamNames(fn){ - if(typeof fn !== 'string') fn = fn.toString(); - const arrowMatch = fn.match(/\(?[^]*?\)?\s*=>/) - if (arrowMatch) return arrowMatch[0].replace(/[()\s]/gi,'').replace('=>','').split(',') - const match = fn.match(/\([^]*?\)/) - return match ? match[0].replace(/[()\s]/gi,'').split(',') : [] -} - -export let getFunctionHead = (methodString) => { - let startindex = methodString.indexOf('=>')+1; - if(startindex <= 0) { - startindex = methodString.indexOf('){'); - } - if(startindex <= 0) { - startindex = methodString.indexOf(') {'); - } - return methodString.slice(0, methodString.indexOf('{',startindex) + 1); -} - export function parseFunctionFromText(method='') { //Get the text inside of a function (regular or arrow); let getFunctionBody = (methodString) => { return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '$2$3$4'); } + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf('=>')+1; + if(startindex <= 0) { + startindex = methodString.indexOf('){'); + } + if(startindex <= 0) { + startindex = methodString.indexOf(') {'); + } + return methodString.slice(0, methodString.indexOf('{',startindex) + 1); + } + let newFuncHead = getFunctionHead(method); let newFuncBody = getFunctionBody(method); + let newFunc; if (newFuncHead.includes('function')) { - let varName = newFuncHead.substring(newFuncHead.indexOf('(')+1,newFuncHead.lastIndexOf(')')); + let varName = newFuncHead.split('(')[1].split(')')[0] newFunc = new Function(varName, newFuncBody); } else { - if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { - let varName = newFuncHead.substring(newFuncHead.indexOf('(')+1,newFuncHead.lastIndexOf(')')); - newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf('{') + 1, newFuncBody.length - 1)); - } else { - try { newFunc = (0, eval)(method); } catch { } // Just evaluate the method + if(newFuncHead.substring(0,6) === newFuncBody.substring(0,6)) { + //newFuncBody = newFuncBody.substring(newFuncHead.length); + let varName = newFuncHead.split('(')[1].split(')')[0] + //console.log(varName, newFuncHead ,newFuncBody); + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf('{')+1,newFuncBody.length-1)); + } + else { + try {newFunc = (0,eval)(newFuncHead + newFuncBody + "}");} catch {} } } @@ -128,11 +109,11 @@ export const stringifyWithCircularRefs = (function() { if (key) { updateParents(key, value); } let other = refs.get(value); - if (other) { - return '[Circular Reference]' + other; - } else { - refs.set(value, path.join('.')); - } + if (other) { + return '[Circular Reference]' + other; + } else { + refs.set(value, path.join('.')); + } } } return value; @@ -153,75 +134,6 @@ if((JSON as any).stringifyWithCircularRefs === undefined) { (JSON as any).stringifyWithCircularRefs = stringifyWithCircularRefs; } - -export const stringifyWithFunctionsAndCircularRefs = (function() { - const refs = new Map(); - const parents:any[] = []; - const path = ["this"]; - - function clear() { - refs.clear(); - parents.length = 0; - path.length = 1; - } - - function updateParents(key, value) { - var idx = parents.length - 1; - var prev = parents[idx]; - if(typeof prev === 'object') { - if (prev[key] === value || idx === 0) { - path.push(key); - parents.push(value.pushed); - } else { - while (idx-- >= 0) { - prev = parents[idx]; - if(typeof prev === 'object') { - if (prev[key] === value) { - idx += 2; - parents.length = idx; - path.length = idx; - --idx; - parents[idx] = value; - path[idx] = key; - break; - } - } - idx--; - } - } - } - } - - function checkCircular(key, value) { - if (value != null) { - if (typeof value === "object") { - if (key) { updateParents(key, value); } - - let other = refs.get(value); - if (other) { - return '[Circular Reference]' + other; - } else { - refs.set( typeof value === 'function' ? value.toString() : value, path.join('.')); - } - } - } - return typeof value === 'function' ? value.toString() : value; - } - - return function stringifyWithFunctionsAndCircularRefs(obj, space?) { - try { - parents.push(obj); - return JSON.stringify(obj, checkCircular, space); - } finally { - clear(); - } - } -})(); - -if((JSON as any).stringifyWithFunctionsAndCircularRefs === undefined) { - //Workaround for objects containing DOM nodes, which can't be stringified with JSON. From: https://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json - (JSON as any).stringifyWithFunctionsAndCircularRefs = stringifyWithFunctionsAndCircularRefs; -} //partial stringification for objects and removing circular references. This allows MUCH faster object equivalency comparison with three-tier depth checking export const stringifyFast = (function() { const refs = new Map(); @@ -364,4 +276,3 @@ if((JSON as any).stringifyFast === undefined) { //Workaround for objects containing DOM nodes, which can't be stringified with JSON. From: https://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json (JSON as any).stringifyFast = stringifyFast; } - diff --git a/services/webrtc/WebRTC.browser.ts b/services/webrtc/WebRTC.browser.ts new file mode 100644 index 00000000..9ca33d2d --- /dev/null +++ b/services/webrtc/WebRTC.browser.ts @@ -0,0 +1,535 @@ +import { GraphOptions } from "../../Graph"; +import { Service, ServiceMessage, ServiceOptions } from "../Service"; + +export type WebRTCProps = { + _id?:string, + channels?:{ + [key:string]:(true|RTCDataChannelInit|RTCDataChannel) + }, + config?:RTCConfiguration, + hostdescription?:RTCSessionDescriptionInit|string, + peerdescription?:RTCSessionDescriptionInit|string, + offer?:RTCOfferOptions, + hostcandidates?:{[key:string]:RTCIceCandidate}, + peercandidates?:{[key:string]:RTCIceCandidate}, + answer?:RTCAnswerOptions, + ontrack?:(ev:RTCTrackEvent)=>void, + onicecandidate?:(ev:RTCPeerConnectionIceEvent)=>void, + onicecandidateerror?:(ev:Event)=>void, + onnegotiationneeded?:(ev:Event)=>void, + ondatachannel?:(ev:RTCDataChannelEvent)=>void, + ondata?:(ev:MessageEvent, channel:RTCDataChannel, room)=>void, + onconnectionstatechange?:(ev:Event)=>void, + oniceconnectionstatechange?:(ev:Event)=>void, + onclose?:(rtc:WebRTCInfo)=>void //custom callback +} + +export type WebRTCInfo = { + _id:string, + rtc:RTCPeerConnection, + send:(message:any)=>void, //these callbacks work on the first available data channel to call to other webrtc services + request:(message:any, method?:string)=>Promise, + post:(route:any, args?:any)=>void, + run:(route:any, args?:any, method?:string)=>Promise, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>Promise, + unsubscribe:(route:any, sub:number)=>Promise, + terminate:()=>boolean, + graph:WebRTCfrontend +} & WebRTCProps + +//webrtc establishes secure P2P contexts between two users directly. +// However, we need a backend as a way to list available connections. +export class WebRTCfrontend extends Service { + + name='webrtc' + + rtc:{ + [key:string]:WebRTCInfo + } = {} + + iceServers:{urls:string[]}[] = [ + { urls: ['stun:stun.l.google.com:19302'] }, + { urls: ['stun:stun1.l.google.com:19302'] }, + { urls: ['stun:stun2.l.google.com:19302'] }, + { urls: ['stun:stun3.l.google.com:19302'] }, + { urls: ['stun:stun4.l.google.com:19302'] } + ]; + + connections = { //higher level reference for router + rtc:this.rtc + } + + constructor( + options?:ServiceOptions, + iceServers?:{urls:string[]}[] + ) { + super(options); + this.setTree(this); + + if(iceServers) this.iceServers = iceServers; + } + + createStream = ( //use navigator.mediaDevices.getUserMedia({audio:true,video:true}) for audio/video streams + options:{ + [key:string]:{ + track:MediaStreamTrack|MediaTrackConstraints, + onended:(ev)=>void, + onmute:(ev)=>void, + onunmute:(ev)=>void + } + } + ) => { + let stream = new MediaStream(); + for(const key in options) { + let track = options[key].track; + if(!(track instanceof MediaStreamTrack) && typeof track === 'object') { + track = new MediaStreamTrack(); + track.applyConstraints(options[key].track as MediaTrackConstraints) + stream.addTrack(track); + } + + if(track instanceof MediaStreamTrack) { + stream.addTrack(track as MediaStreamTrack); + track.onmute = options[key].onmute; + track.onunmute = options[key].onunmute; + track.onended = options[key].onended; + + } + } + return stream; + } + + openRTC = async ( + options?:WebRTCProps + ):Promise => { + if(!options) options = {}; + if(!options._id) options._id = `rtc${Math.floor(Math.random()*1000000000000000)}`; + if(!options.config) options.config = {iceServers:this.iceServers}; + + let rtc = new RTCPeerConnection(options.config); + + + if(!this.rtc[options._id]) { + + if(!options.channels) options.channels = { 'data':true }; //need one channel at least for the default service stuff to work + + let firstChannel; + for(const key in options.channels) { + firstChannel = key; + break; + } + + let send = (message:any) => { + //console.log('sent', message) + return this.transmit(message,options._id,options.channels[firstChannel] as RTCDataChannel); + } + + let post = (route:any,args?:any, method?:string) => { + //console.log('sent', message) + let message:any = { + route, + args + }; + if(method) message.method = method; + + return this.transmit(message,options._id,options.channels[firstChannel] as RTCDataChannel); + } + + let run = (route:any,args?:any, method?:string):Promise => { + return new Promise ((res,rej) => { + let callbackId = Math.random(); + let req = {route:'runRequest', args:[{route, args}, options._id, callbackId]} as any; + //console.log(req) + if(method) req.args[0].method = method; + + let sub; + let ondata = (data:any)=>{ + if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(data); + if(typeof data === 'object') { + if(data.callbackId === callbackId) { + //(options.channels[firstChannel] as RTCDataChannel).removeEventListener('message',onmessage); + this.unsubscribe(options._id,sub); + res(data.args); //resolve the request with the corresponding message + } + } + } + + sub = this.subscribe(options._id,ondata); + + //(options.channels[firstChannel] as RTCDataChannel).addEventListener('message',onmessage) + this.transmit(req, options._id,options.channels[firstChannel] as RTCDataChannel); + }); + } + + let request = (message:ServiceMessage|any, method?:string):Promise => { + return new Promise ((res,rej) => { + let callbackId = Math.random(); + let req = {route:'runRequest', args:[message,options._id,callbackId]} as any; + //console.log(req) + if(method) req.method = method; + + let sub; + let ondata = (data:any)=>{ + if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(data); + if(typeof data === 'object') { + if(data.callbackId === callbackId) { + //(options.channels[firstChannel] as RTCDataChannel).removeEventListener('message',onmessage); + this.unsubscribe(options._id,sub); + res(data.args); //resolve the request with the corresponding message + } + } + } + + sub = this.subscribe(options._id,ondata); + this.transmit(req, options._id,options.channels[firstChannel] as RTCDataChannel); + }); + } + + let subscribe = (route:any, callback?:((res:any)=>void)|string) => { + return this.subscribeToRTC(route, options._id, firstChannel, callback); + } + + let unsubscribe = (route:any, sub:number) => { + return run('unsubscribe',[route,sub]); + } + + let terminate = () => { + return this.terminate(options._id); + } + + this.rtc[options._id] = { + rtc, + _id:options._id, + request, + run, + post, + send, + subscribe, + unsubscribe, + terminate, + graph:this, + ...options + } + + //console.log('opening webrtc channel',this.rtc) + if(!options.ondatachannel) options.ondatachannel = (ev:RTCDataChannelEvent) => { + this.rtc[options._id].channels[ev.channel.label] = ev.channel; + if(!options.ondata) { + ev.channel.addEventListener('message', (mev) => { + //console.log('message on data channel', mev); + this.receive(mev.data, ev.channel, this.rtc[options._id]); + this.setState({[options._id]:mev.data}); + }); + } + else ev.channel.addEventListener('message', (mev) => { options.ondata(mev.data, ev.channel, this.rtc[options._id]); }); + + } + + if(options.channels) { + for(const channel in options.channels) { + if(options.channels[channel] instanceof RTCDataChannel) { + //OK + } + else if( typeof options.channels[channel] === 'object') { + options.channels[channel] = this.addDataChannel(rtc,channel,(options.channels)[channel] as any); + } else { + options.channels[channel] = this.addDataChannel(rtc,channel); + } + + (options.channels[channel] as RTCDataChannel).addEventListener('message', (mev) => { + //console.log('message on data channel', mev); + this.receive(mev.data, channel, this.rtc[options._id]); + this.setState({[options._id]:mev.data}); + }); + } + } + + + rtc.ontrack = options.ontrack; + rtc.onicecandidate = options.onicecandidate; + rtc.onicecandidateerror = options.onicecandidateerror; + rtc.ondatachannel = options.ondatachannel; + rtc.onnegotiationneeded = options.onnegotiationneeded; + rtc.oniceconnectionstatechange = options.oniceconnectionstatechange; + rtc.onconnectionstatechange = options.onconnectionstatechange; + rtc.addEventListener('connectionstatechange', (ev) => { + if(rtc.connectionState === 'closed' || rtc.connectionState === 'failed') { + if(this.rtc[options._id].onclose) { + this.rtc[options._id].onclose(this.rtc[options._id]); + } + } + }) + + } else { + Object.assign(this.rtc[options._id],options); + } + + if(options.hostdescription && !options.peerdescription) { + if(!options.onicecandidate) options.onicecandidate = (ev:RTCPeerConnectionIceEvent) => { + if(ev.candidate) { + let icecandidate = ev.candidate; + + if(!this.rtc[options._id].peercandidates) this.rtc[options._id].peercandidates = {}; + this.rtc[options._id].peercandidates[`peercandidate${Math.floor(Math.random()*1000000000000000)}`] = icecandidate; + + } + } + + // console.log(options.hostdescription) + return await new Promise((res,rej) => { + //console.log('desc', options.hostdescription) + if(typeof options.hostdescription === 'string') { + options.hostdescription = JSON.parse(decodeURIComponent(options.hostdescription)); + } + const description = new RTCSessionDescription(options.hostdescription as RTCSessionDescriptionInit); + //console.log('desc2', description) + + options.hostdescription = description + rtc.setRemoteDescription(description).then(()=>{ + if(options.hostcandidates) { + for(const prop in options.hostcandidates) { + const candidate = new RTCIceCandidate(options.hostcandidates[prop]) + rtc.addIceCandidate(candidate).catch(console.error); + } + } + rtc.createAnswer(options.answer) + .then((answer)=> rtc.setLocalDescription(answer)) + .then(()=>{ + this.rtc[options._id].peerdescription = encodeURIComponent(JSON.stringify(rtc.localDescription)); + res(this.rtc[options._id]); + }); + }).catch(rej); //we can now receive data + }); + } + + if(options.peerdescription) { + this.answerPeer(rtc,options); + } + + if(!options.onicecandidate && !this.rtc[options._id]?.onicecandidate) options.onicecandidate = (ev:RTCPeerConnectionIceEvent) => { + if(ev.candidate) { + let icecandidate = ev.candidate; + + if(!this.rtc[options._id].hostcandidates) this.rtc[options._id].hostcandidates = {}; + this.rtc[options._id].hostcandidates[`hostcandidate${Math.floor(Math.random()*1000000000000000)}`] = icecandidate; + + } + } + + return await new Promise((res,rej) => { + rtc.createOffer(options.offer) + .then((offer) => rtc.setLocalDescription(offer)) + .then(()=>{ + this.rtc[options._id].hostdescription = encodeURIComponent(JSON.stringify(rtc.localDescription)); + res(this.rtc[options._id]); //this is to be transmitted to the user + }); + }); + + } + + addIceCandidate(rtc:RTCPeerConnection, candidate:RTCIceCandidate) { + return rtc.addIceCandidate(candidate); + } + + //use the + answerPeer(rtc:RTCPeerConnection,options:WebRTCProps) { + return new Promise((res,rej) => { + if(typeof options.peerdescription === 'string') { + options.peerdescription = JSON.parse(decodeURIComponent(options.peerdescription)); + } + const description = new RTCSessionDescription(options.peerdescription as RTCSessionDescriptionInit); + options.peerdescription = description; + + if(this.rtc[options._id]) this.rtc[options._id].peerdescription = description; + rtc.setRemoteDescription(description).then(()=>{ + if(options.peercandidates) { + for(const prop in options.peercandidates) { + const candidate = new RTCIceCandidate(options.peercandidates[prop]) + if(this.rtc[options._id]) this.rtc[options._id].peercandidates[prop] = options.peercandidates[prop]; + rtc.addIceCandidate(candidate).catch(console.error); + } + } + res(this.rtc[options._id] ? this.rtc[options._id] : rtc); + }).catch(rej); //we can now receive data + }); + } + + addUserMedia = ( + rtc:RTCPeerConnection, + options:MediaStreamConstraints={ + audio:false, + video:{ + optional:[ + {minWidth: 320}, + {minWidth: 640}, + {minWidth: 1024}, + {minWidth: 1280}, + {minWidth: 1920}, + {minWidth: 2560}, + ] + } as MediaTrackConstraints + } + ) => { + let senders:any[] = []; + navigator.mediaDevices.getUserMedia(options) + .then((stream) => { + let tracks = stream.getTracks() + tracks.forEach((track) => { + senders.push(rtc.addTrack(track,stream)); + }); + } + ) + return senders; + } + + //add media streams to the dat channel + addTrack = (rtc:RTCPeerConnection, track:MediaStreamTrack, stream:MediaStream) => { + rtc.addTrack(track,stream); + return true; + } + + removeTrack = (rtc:RTCPeerConnection,sender:RTCRtpSender) => { + rtc.removeTrack(sender); //e.g. remove the senders removed by addUserMedia + return true; + } + + addDataChannel = ( //send arbitrary strings + rtc:RTCPeerConnection, + name:string, + options?:RTCDataChannelInit//{ negotiated: false } + ) => { + return rtc.createDataChannel(name,options); + } + + //send data on a data channel + transmit = (data:ServiceMessage|any, id?:string, channel?:string|RTCDataChannel ) => { + if(typeof data === 'object' || typeof data === 'number') + data = JSON.stringify(data); //we need strings + + if(!channel && id) { //select first channel + let keys = Object.keys(this.rtc[id].channels); + if(keys[0]) + channel = this.rtc[id].channels[keys[0]] as RTCDataChannel; + } + + if(typeof channel === 'string') { + if(id) { + channel = this.rtc[id].channels[channel] as RTCDataChannel; + } else { //send on all channels on all rooms + for(const id in this.rtc) { + if(this.rtc[id].channels[channel] instanceof RTCDataChannel) + (this.rtc[id].channels[channel] as RTCDataChannel).send(data); + } + } + } + + if(channel instanceof RTCDataChannel) + channel.send(data); + + //console.log('sending',channel,data) + + return true; + } + + //close a channel + terminate = (rtc:RTCPeerConnection|WebRTCInfo|string) => { + let tx; + if(typeof rtc === 'string') { + let room = this.rtc[rtc]; + delete this.rtc[rtc]; + if(room) { + tx = room.rtc; + } + } + else if (typeof rtc === 'object') { + tx = (rtc as WebRTCInfo).rtc; + } + + if(rtc instanceof RTCPeerConnection) { + rtc.close(); + } else if(tx) { + if(tx) tx.close(); + } + + return true; + } + + request = (message:ServiceMessage|any, channel:RTCDataChannel, _id:string,method?:string) => { //return a promise which can resolve with a server route result through the socket + let callbackId = `${Math.random()}`; + let req:any = {route:'runRequest', args:[message,_id,callbackId]}; + if(method) req.method = method; + return new Promise((res,rej) => { + let onmessage = (ev:any) => { + let data = ev.data; + if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(ev.data); + if(typeof data === 'object') if(data.callbackId === callbackId) { + channel.removeEventListener('message',onmessage); + res(data.args); + } + } + + channel.addEventListener('message',onmessage); + channel.send(JSON.stringify(req)); + }); + } + + runRequest = (message:any, channel:RTCDataChannel|string, callbackId:string|number) => { //send result back + let res = this.receive(message); + if(channel) { + if(typeof channel === 'string') { + for(const key in this.rtc) { + if(key === channel) {channel = this.rtc[key].channels.data as RTCDataChannel; break;} + } + } + if(res instanceof Promise) + res.then((v) => { + res = {args:v, callbackId}; + if(channel instanceof RTCDataChannel) channel.send(JSON.stringify(res)); + + return res; + }) + else { + res = {args:res, callbackId}; + if(channel instanceof RTCDataChannel) channel.send(JSON.stringify(res)); + } + } + return res; + } + + subscribeRTC = (route:string, rtcId:string, channel:string|RTCDataChannel) => { + if(typeof channel === 'string' && this.rtc[rtcId]) { + channel = this.rtc[rtcId].channels[channel] as RTCDataChannel; + } + return this.subscribe(route, (res:any) => { + //console.log('running request', message, 'for worker', worker, 'callback', callbackId) + if(res instanceof Promise) { + res.then((r) => { + (channel as RTCDataChannel).send(JSON.stringify({args:r, callbackId:route})); + }); + } else { + (channel as RTCDataChannel).send(JSON.stringify({args:res, callbackId:route})); + } + }); + } + + subscribeToRTC = (route:string, rtcId:string, channelId:string, callback?:string|((res:any)=>void)) => { + if(typeof channelId === 'string' && this.rtc[rtcId]) { + let c = this.rtc[rtcId]; + let channel = c.channels[channelId]; + + if(channel) { + this.__node.state.subscribeTrigger(rtcId, (res) => { + if(res?.callbackId === route) { + if(!callback) this.setState({[rtcId]:res.args}); //just set state + else if(typeof callback === 'string') { //run a local node + this.run(callback,res.args); + } + else callback(res.args); + } + }); + return c.request({route:'subscribeRTC', args:[route,channelId]}); + } + } + } + +} \ No newline at end of file diff --git a/src/services/worker/ProxyListener.ts b/services/worker/ProxyListener.ts similarity index 69% rename from src/services/worker/ProxyListener.ts rename to services/worker/ProxyListener.ts index c3ca33ae..af89123a 100644 --- a/src/services/worker/ProxyListener.ts +++ b/services/worker/ProxyListener.ts @@ -6,111 +6,76 @@ declare var WorkerGlobalScope; const mouseEventHandler = makeSendPropertiesHandler([ 'ctrlKey', 'metaKey', - 'altKey', 'shiftKey', 'button', - 'which', 'pointerType', 'clientX', 'clientY', 'pageX', 'pageY', - 'movementX', - 'movementY', - 'x', - 'y', - 'which', - 'timeStamp' ]); - -const wheelEventHandlerImpl = makeSendPropertiesHandler([ - 'deltaX', - 'deltaY', -]); - -const keydownEventHandler = makeSendPropertiesHandler([ - 'ctrlKey', - 'metaKey', - 'shiftKey', - 'altKey', - 'isComposing', - 'keyCode', - 'key', - 'code', - 'repeat', - 'timeStamp' -]); - -function focusEventHandler(event, sendFn) { - const data = { type:event.type } as any; - data.isTrusted = event.isTrusted; - data.bubbles = event.bubbles; - data.cancelBubble = event.cancelBubble; - data.cancelable = event.cancelable; - data.composed = event.composed; - data.defaultPrevent = event.defaultPrevented; - data.eventPhase = event.eventPhase; - data.returnValue = event.returnValue; - - data.currentTarget = event.currentTarget.id ? event.currentTarget.id : event.currentTarget.constructor.name; - data.target = data.currentTarget; - data.srcElement = data.currentTarget; - - sendFn(data); -} - -function wheelEventHandler(event, sendFn, preventDefault) { - if(preventDefault && event.preventDefault) event.preventDefault(); - wheelEventHandlerImpl(event, sendFn); -} - -function preventDefaultHandler(event, sendFn, preventDefault) { - if(preventDefault && event.preventDefault) event.preventDefault(); -} - -function copyProperties(src, properties, dst) { - for (const name of properties) { - dst[name] = src[name]; + const wheelEventHandlerImpl = makeSendPropertiesHandler([ + 'deltaX', + 'deltaY', + ]); + const keydownEventHandler = makeSendPropertiesHandler([ + 'ctrlKey', + 'metaKey', + 'shiftKey', + 'keyCode', + ]); + + function wheelEventHandler(event, sendFn) { + event.preventDefault(); + wheelEventHandlerImpl(event, sendFn); } -} - -function makeSendPropertiesHandler(properties) { - return function sendProperties(event, sendFn) { - const data = {type: event.type}; - copyProperties(event, properties, data); + + function preventDefaultHandler(event) { + event.preventDefault(); + } + + function copyProperties(src, properties, dst) { + for (const name of properties) { + dst[name] = src[name]; + } + } + + function makeSendPropertiesHandler(properties) { + return function sendProperties(event, sendFn) { + const data = {type: event.type}; + copyProperties(event, properties, data); + sendFn(data); + }; + } + + function touchEventHandler(event, sendFn) { + const touches = []; + const data = {type: event.type, touches}; + for (let i = 0; i < event.touches.length; ++i) { + const touch = event.touches[i]; + touches.push({ + pageX: touch.pageX, + pageY: touch.pageY, + }); + } sendFn(data); - }; -} - -function touchEventHandler(event, sendFn, preventDefault) { - if(preventDefault && event.preventDefault) event.preventDefault(); - const touches = []; - const data = {type: event.type, touches}; - for (let i = 0; i < event.touches.length; ++i) { - const touch = event.touches[i]; - touches.push({ - pageX: touch.pageX, - pageY: touch.pageY, - }); } - sendFn(data); -} - -let i = 1; -let keys = {}; -while(i < 222) { //proxy all key events - keys[i] = true; //avoid F keys - i++; -} - + + // The four arrow keys + const orbitKeys = { + '37': true, // left + '38': true, // up + '39': true, // right + '40': true, // down + }; -function filteredKeydownEventHandler(event, sendFn, preventDefault) { - let {keyCode} = event; - if (keys[keyCode]) { - if(preventDefault && event.preventDefault && (keyCode < 110 || keyCode > 123)) event.preventDefault(); - keydownEventHandler(event, sendFn); + function filteredKeydownEventHandler(event, sendFn) { + const {keyCode} = event; + if (orbitKeys[keyCode]) { + event.preventDefault(); + keydownEventHandler(event, sendFn); + } } -} export const eventHandlers = { //you can register more event handlers in this object contextmenu: preventDefaultHandler, @@ -120,21 +85,15 @@ export const eventHandlers = { //you can register more event handlers in this ob pointerdown: mouseEventHandler, pointermove: mouseEventHandler, pointerup: mouseEventHandler, - pointerlockchange: mouseEventHandler, - webkitpointerlockchange: mouseEventHandler, - focus: focusEventHandler, - blur: focusEventHandler, - pointerout: mouseEventHandler, touchstart: touchEventHandler, touchmove: touchEventHandler, touchend: touchEventHandler, wheel: wheelEventHandler, keydown: filteredKeydownEventHandler, - keyup: filteredKeydownEventHandler }; //do this on main thread -export function initProxyElement(element, worker, id, preventDefault?:boolean) { +export function initProxyElement(element, worker, id) { if( !id ) id = 'proxy'+Math.floor(Math.random()*1000000000000000); @@ -151,34 +110,10 @@ export function initProxyElement(element, worker, id, preventDefault?:boolean) { for (const [eventName, handler] of entries) { element.addEventListener(eventName, function(event) { //add all of the event listeners we care about - handler(event, sendEvent, preventDefault); + handler(event, sendEvent); }); } - if(eventHandlers.keydown) { - globalThis.addEventListener('keydown', function(ev) { - eventHandlers.keydown(ev, sendEvent, preventDefault); - }) - } - - if(eventHandlers.keyup) { - globalThis.addEventListener('keyup', function(ev) { - eventHandlers.keyup(ev, sendEvent, preventDefault); - }) - } - - // if(eventHandlers.focus) { - // globalThis.addEventListener('focus', function(ev) { - // eventHandlers.focus(ev, sendEvent); - // }) - // } - - // if(eventHandlers.blur) { - // globalThis.addEventListener('blur', function(ev) { - // eventHandlers.blur(ev, sendEvent); - // }) - // } - const sendSize = () => { const rect = element.getBoundingClientRect(); @@ -209,7 +144,6 @@ export class EventDispatcher { addEventListener( type, listener ) { - //console.log(type,listener); if ( this.__listeners === undefined ) this.__listeners = {}; const listeners = this.__listeners; if ( listeners[ type ] === undefined ) { @@ -254,12 +188,13 @@ export class EventDispatcher { for ( let i = 0, l = array.length; i < l; i ++ ) { array[ i ].call( this, event ); } - //event.target = null; + event.target = null; } } } -function noop() {}; +function noop() { +}; /////////////https://threejsfundamentals.org/threejs/lessons/threejs-offscreencanvas.html export class ElementProxyReceiver extends EventDispatcher { @@ -320,8 +255,6 @@ export class ElementProxyReceiver extends EventDispatcher { focus() {} - blur() {} - } /////////////https://threejsfundamentals.org/threejs/lessons/threejs-offscreencanvas.html @@ -330,11 +263,7 @@ export class ProxyManager { targets:any={}; constructor() { - if(!globalThis.document) globalThis.document = { - elementFromPoint:(...args:any[])=>{ //hax - return this.targets[Object.keys(this.targets)[0]].proxied; - } - } as any; //threejs hack for workers + if(!globalThis.document) globalThis.document = {} as any; //threejs hack for workers } makeProxy = (id, addTo=undefined) => { //addTo installs the desirable functions to the object you want @@ -371,7 +300,6 @@ export class ProxyManager { addTo.handleEvent = proxy.handleEvent.bind(proxy); addTo.dispatchEvent = proxy.dispatchEvent.bind(proxy); addTo.focus = proxy.focus.bind(proxy); - addTo.blur = proxy.blur.bind(proxy); } } diff --git a/_old/Subprocess.ts b/services/worker/Subprocess.ts similarity index 97% rename from _old/Subprocess.ts rename to services/worker/Subprocess.ts index b13fcadd..72ea8655 100644 --- a/_old/Subprocess.ts +++ b/services/worker/Subprocess.ts @@ -1,11 +1,8 @@ -import { parseFunctionFromText } from '../src/services/utils'; -import { WorkerInfo, WorkerService } from '../src/services/worker/Worker.service'; -import { remoteGraphRoutes } from '../src/services/remote/remote.routes'; -import { Graph, GraphNodeProperties } from '../src/core/Graph'; -import {methodstrings} from '../src/loaders/methodstrings' -export type Subprocess = (context:SubprocessContext,data:{[key:string]:any}|any)=>{[key:string]:any}|undefined +import { parseFunctionFromText } from '../utils'; +import { WorkerInfo, WorkerService } from './Worker.service'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; -//deprecated, just use remoteRoutes and normal node routines +export type Subprocess = (context:SubprocessContext,data:{[key:string]:any}|any)=>{[key:string]:any}|undefined export type SubprocessContextProps = { ondata:Subprocess, @@ -104,10 +101,11 @@ let recursivelyAssign = (target,obj) => { } + export const subprocessRoutes = { - ...remoteGraphRoutes, + ...unsafeRoutes, loadAlgorithms:loadAlgorithms, - 'initSubprocesses':async function initSubprocesses( //requires remoteGraphRoutes + 'initSubprocesses':async function initSubprocesses( //requires unsafeRoutes subprocesses:{ //use secondary workers to run processes and report results back to the main thread or other [key:string]:SubprocessWorkerProps }, @@ -347,7 +345,7 @@ export const subprocessRoutes = { if(typeof options?.ondata === 'function') ctx = createSubprocess(options,inputs); if(ctx) this.__node.graph.ALGORITHMS[ctx._id] = ctx; - //console.log(ctx,options); + console.log(ctx,options); if(ctx) return ctx._id; } @@ -358,7 +356,6 @@ export const subprocessRoutes = { data:{[key:string]:any}, _id?:string ){ - //console.log(data); if(!this.__node.graph.ALGORITHMS) this.__node.graph.ALGORITHMS = {}; if(!_id) _id = Object.keys(this.__node.graph.ALGORITHMS)[0]; //run the first key if none specified diff --git a/src/services/worker/Worker.service.ts b/services/worker/Worker.service.ts similarity index 79% rename from src/services/worker/Worker.service.ts rename to services/worker/Worker.service.ts index d1e42aa9..7b24a179 100644 --- a/src/services/worker/Worker.service.ts +++ b/services/worker/Worker.service.ts @@ -1,12 +1,13 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; import Worker from 'web-worker' //cross platform for node and browser -import { Graph, GraphNode, GraphNodeProperties } from "../../core/Graph"; +import { Graph, GraphNode, GraphNodeProperties } from "../../Graph"; declare var WorkerGlobalScope; export type WorkerRoute = { worker?:WorkerInfo workerUrl?: string|URL|Blob, + workerId?: string, transferFunctions?:{[key:string]:Function}, transferClasses?:{[key:string]:Function}, parentRoute?:string, //if a child of a worker node, subscribe to a route on a parent worker? @@ -33,16 +34,16 @@ export type WorkerProps = { export type WorkerInfo = { worker:Worker|MessagePort, send:(message:any,transfer?:any)=>void, - request:(message:any, method?:string,transfer?:any)=>Promise, - post:(route:any, args?:any, method?:string, transfer?:any)=>void, - run:(route:any, args?:any, method?:string,transfer?:any)=>Promise - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean, blocking?:boolean)=>Promise, + request:(message:any, transfer?:any, method?:string)=>Promise, + post:(route:any, args?:any, transfer?:any)=>void, + run:(route:any, args?:any, transfer?:any, method?:string)=>Promise + subscribe:(route:any, callback?:((res:any)=>void)|string, blocking?:boolean)=>Promise, unsubscribe:(route:any, sub:number)=>Promise, start:(route?:any, portId?:string, callback?:((res:any)=>void)|string, blocking?:boolean)=>Promise, stop:(route?:string, portId?:string)=>Promise, workerSubs:{[key:string]:{sub:number|false, route:string, portId:string, callback?:((res:any)=>void)|string, blocking?:boolean}}, terminate:()=>boolean, - postMessage:(message:any,transfer?:any[])=>void, //original worker post message + postMessage:(message:any,transfer:any[])=>void, //original worker post message graph:WorkerService, _id:string } & WorkerProps & WorkerRoute @@ -68,8 +69,10 @@ export class WorkerService extends Service { } if(options?.services) this.addServices(options.services); - this.load(this); + + this.setTree(this); this.setLoaders(this.workerloader); //add a custom route loader for the worker logic + if(options) this.init(options); if(typeof WorkerGlobalScope !== 'undefined' && globalThis instanceof WorkerGlobalScope) { @@ -77,60 +80,58 @@ export class WorkerService extends Service { } } - loadWorkerRoute = (node:WorkerRoute & GraphNode, routeKey:string) => { - if(node.workerUrl) node.url = node.workerUrl; - if(node._id) node.__node.tag = node._id; - if(!node.__node.tag) node.__node.tag = routeKey; - node._id = node.__node.tag; + loadWorkerRoute = (rt:WorkerRoute & GraphNode,routeKey:string) => { + if(rt.workerUrl) rt.url = rt.workerUrl; + if(rt.workerId) rt.__node.tag = rt.workerId; + if(!rt.__node.tag) rt.__node.tag = routeKey; + rt._id = rt.__node.tag; let worker:WorkerInfo; - if(this.workers[node._id]) worker = this.workers[node._id]; - else if (node.worker) worker = node.worker; + if(this.workers[rt._id]) worker = this.workers[rt._id]; + else if (rt.worker) worker = rt.worker; if(!worker) { - worker = this.addWorker(node); - } - - node.worker = worker; + worker = this.addWorker(rt); - if(!node.__ondisconnected) { let ondelete = (rt) => { //removing the original route will trigger ondelete rt.worker?.terminate(); } - node.__addOndisconnected(ondelete); + rt.__addOndisconnected(ondelete); } + + rt.worker = worker; //console.log(rt); - //requires remoteGraphRoutes on the worker (enabled on the default worker) - if(node.transferFunctions) { - for(const prop in node.transferFunctions) { - this.transferFunction(worker,node.transferFunctions[prop],prop) + //requires unsafeRoutes on the worker (enabled on the default worker) + if(rt.transferFunctions) { + for(const prop in rt.transferFunctions) { + this.transferFunction(worker,rt.transferFunctions[prop],prop) } } - if(node.transferClasses) { - for(const prop in node.transferClasses) { - this.transferClass(worker,node.transferClasses[prop],prop) + if(rt.transferClasses) { + for(const prop in rt.transferClasses) { + this.transferClass(worker,rt.transferClasses[prop],prop) } } if(worker) { - if(!node.__operator) { - node.__operator = (...args) => { + if(!rt.__operator) { + rt.__operator = (...args) => { //console.log('operator', args) - if(node.callback) { - if(!this.__node.nodes.get(node.__node.tag)?.__children) worker.post(node.callback,args); - else return worker.run(node.callback,args); + if(rt.callback) { + if(!this.__node.nodes.get(rt.__node.tag)?.__children) worker.post(rt.callback,args); + else return worker.run(rt.callback,args); } else { - if(!this.__node.nodes.get(node.__node.tag)?.__children) worker.send(args); + if(!this.__node.nodes.get(rt.__node.tag)?.__children) worker.send(args); else return worker.request(args); } } } - if(node.init) { //requires remoteGraphRoutes - worker.run(node.init,node.initArgs,undefined,node.initTransfer); + if(rt.init) { //requires unsafeRoutes + worker.run(rt.init,rt.initArgs,rt.initTransfer); } - // //need remoteGraphRoutes loaded + // //need unsafeRoutes loaded // worker.run('setValue',[rt.callback+'_routeProxy', rt.callback]); // this.transferFunction( @@ -158,14 +159,13 @@ export class WorkerService extends Service { } } - workerloader:any = { //todo: clean this up and extrapolate to other services - 'workers':(node: WorkerRoute & GraphNode, parent:WorkerRoute & GraphNode, graph:Graph, roots:any) => { + workerloader:any = { + 'workers':(node: WorkerRoute & GraphNode, parent:WorkerRoute & GraphNode, graph:Graph, tree:any) => { let rt = node as WorkerRoute; if(!node.parentRoute && (parent?.callback && parent?.worker)) node.parentRoute = parent?.callback; - if(rt?.worker || (rt?._id && this.workers[rt._id]) || (rt as WorkerRoute)?.workerUrl) { //each set of props with a worker will instantiate a new worker, else you can use the same worker elsewhere by passing the corresponding tag + if(rt?.worker || rt?.workerId || (rt as WorkerRoute)?.workerUrl) { //each set of props with a worker will instantiate a new worker, else you can use the same worker elsewhere by passing the corresponding tag let worker = this.loadWorkerRoute(rt as any, rt.__node.tag); - if(worker) { if(!rt.parentRoute && (rt.__parent as any)?.callback) rt.parentRoute = (rt.__parent as any).callback; if(rt.__parent && !rt.portId){ @@ -173,19 +173,19 @@ export class WorkerService extends Service { if(rt.__node.tag !== rt.__parent && worker._id !== rt.__parent) rt.portId = this.establishMessageChannel(worker, rt.__parent) as string; } - else if(rt.__node.tag !== rt.__parent?.__node?.tag && worker._id !== rt.__parent?.tag) { + else if(rt.__node.tag !== rt.__parent?.__node?.tag && worker._id !== rt.__parent.tag) { rt.portId = this.establishMessageChannel(worker, (rt.__parent as any).worker) as string; } }; if(rt.parentRoute) { if(!rt.stopped) { if(typeof rt.__parent === 'string' && rt.__parent === worker._id) { - worker.run('subscribe', [rt.parentRoute, undefined, undefined, rt.callback]); + worker.run('subscribe', [rt.parentRoute, undefined, rt.callback]); } else if(rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag) { - worker.run('subscribe', [rt.parentRoute, undefined, undefined, rt.callback]); + worker.run('subscribe', [rt.parentRoute, undefined, rt.callback]); } - else worker.run('subscribeToWorker', [rt.parentRoute, rt.portId, undefined, rt.callback, undefined, undefined, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId + else worker.run('subscribeToWorker', [rt.parentRoute, rt.portId, rt.callback, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId worker.workerSubs[rt.parentRoute+rt.portId].sub = sub; }); } @@ -197,7 +197,7 @@ export class WorkerService extends Service { if(rt.__parent === worker._id) { worker.run('subscribe', [rt.__parent, undefined, rt.callback]); } - else worker.run('subscribeToWorker', [rt.__parent, rt.portId, undefined, rt.callback, undefined, undefined, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId + else worker.run('subscribeToWorker', [rt.__parent, rt.portId, rt.callback, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId worker.workerSubs[rt.__parent+rt.portId].sub = sub; }); } @@ -208,9 +208,9 @@ export class WorkerService extends Service { //console.log(rt); if(!rt.stopped) { if(rt.__node.tag === rt.__parent.__node.tag || worker._id === rt.__parent.__node.tag) { - worker.run('subscribe', [rt.__parent.__node.tag, undefined, undefined, rt.callback]); + worker.run('subscribe', [rt.__parent.__node.tag, undefined, rt.callback]); } - else worker.run('subscribeToWorker', [rt.__parent.__node.tag, rt.portId, undefined, rt.callback, undefined, undefined, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId + else worker.run('subscribeToWorker', [rt.__parent.__node.tag, rt.portId, rt.callback, rt.blocking]).then((sub)=>{ //if no callback specified it will simply setState on the receiving thread according to the portId worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub = sub; }); } @@ -221,10 +221,10 @@ export class WorkerService extends Service { } } else if(rt.__parent && rt.parentRoute) { - if(typeof rt.__parent === 'string' && (roots[rt.__parent] as any)?.worker) { - ((roots[rt.__parent] as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, undefined, undefined, undefined, rt.blocking); + if(typeof rt.__parent === 'string' && (tree[rt.__parent] as any)?.worker) { + ((tree[rt.__parent] as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, rt.blocking); } else if((rt.__parent as any)?.worker) { - ((rt.__parent as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, undefined, undefined, undefined, rt.blocking); + ((rt.__parent as any).worker as WorkerInfo).subscribe(rt.parentRoute, rt.__operator, rt.blocking); } } //console.log(rt); @@ -238,7 +238,6 @@ export class WorkerService extends Service { let result = this.receive(ev.data); //this will handle graph logic and can run requests for the window or messsage ports etc etc. //console.log(JSON.stringify(ev.data), JSON.stringify(result),JSON.stringify(Array.from((self as any).SERVICE.nodes.keys()))) //console.log(result); - if(this.__node.keepState) this.setState({[this.name]:result}); //subscribe to all outputs } //this will work for iframes too } @@ -281,7 +280,7 @@ export class WorkerService extends Service { return this.transmit(message,worker,transfer); } - let post = (route:any,args?:any,method?:string, transfer?:any) => { + let post = (route:any,args?:any,transfer?:any, method?:string) => { //console.log('sent', message) let message:any = { route, @@ -292,7 +291,7 @@ export class WorkerService extends Service { return this.transmit(message,worker,transfer); } - let run = (route:any, args?:any, method?:string, transfer?:any) => { + let run = (route:any,args?:any, transfer?:any, method?:string) => { return new Promise ((res,rej) => { let callbackId = Math.random(); let req = {route:'runRequest', args:[{route, args}, options._id, callbackId]} as any; @@ -312,7 +311,7 @@ export class WorkerService extends Service { }); } - let request = (message:ServiceMessage|any, method?:string, transfer?:any) => { + let request = (message:ServiceMessage|any, transfer?:any, method?:string) => { return new Promise ((res,rej) => { let callbackId = Math.random(); let req = {route:'runRequest', args:[message,options._id,callbackId]} as any; @@ -334,8 +333,8 @@ export class WorkerService extends Service { let workerSubs = {}; //subscribe to this worker from the thread running this function - let subscribe = (route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean, blocking?:boolean) => { - return this.subscribeToWorker(route, options._id, callback, args, key, subInput, blocking); + let subscribe = (route:any, callback?:((res:any)=>void)|string, blocking?:boolean) => { + return this.subscribeToWorker(route, options._id, callback, blocking); } let unsubscribe = (route:any, sub:number):Promise => { @@ -345,16 +344,14 @@ export class WorkerService extends Service { //start a subscription to another worker/main thread on this worker let start = async (route?:string, portId?:string, callback?:string, blocking?:boolean) => { if(route) - await run('subscribeToWorker',[route, portId, undefined, callback, blocking]).then((sub) => { + await run('subscribeToWorker',[route, portId, callback, blocking]).then((sub) => { if(sub) workerSubs[route+portId] = {sub, route, portId, callback, blocking}; }); else for(const key in workerSubs) { - if(typeof workerSubs[key].sub !== 'number') - await run('subscribeToWorker', [workerSubs[key].route, workerSubs[key].portId, undefined, workerSubs[key].callback, undefined, workerSubs[key].blocking]).then((sub) => { + if(typeof workerSubs[key].sub !== 'number') + await run('subscribeToWorker', [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].callback, workerSubs[key].blocking]).then((sub) => { workerSubs[key].sub = sub; }); - - console.log(JSON.stringify(workerSubs)); } return true; } @@ -367,9 +364,8 @@ export class WorkerService extends Service { } else { for(const key in workerSubs) { if(typeof workerSubs[key].sub === 'number') { - await run('unpipeWorkers', [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]).then(console.log); + await run('unpipeWorkers',[workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]) } workerSubs[key].sub = false; - } } return true; @@ -378,7 +374,7 @@ export class WorkerService extends Service { let terminate = () => { for(const key in workerSubs) { if(typeof workerSubs[key].sub === 'number') { - run('unpipeWorkers', [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]); + run('unpipeWorkers',[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]) } workerSubs[key].sub = false; } return this.terminate(options._id); @@ -397,11 +393,9 @@ export class WorkerService extends Service { worker.onmessage = options.onmessage; (worker as Worker).onerror = options.onerror; - - let workersettings = { + this.workers[options._id] = { worker:(worker as any), - __node:{tag:options._id}, send, post, run, @@ -417,21 +411,9 @@ export class WorkerService extends Service { ...options } as WorkerInfo; - let node = this.add(workersettings); - - this.workers[options._id] = node as GraphNode & WorkerInfo; - - node.__addOndisconnected(function() { terminate(); }); - return this.workers[options._id]; } - open = this.addWorker; //for the router - - close = () => { - globalThis.close(); //workers can terminate themselves - } - //new Worker(urlFromString) toObjectURL = (scriptTemplate:string) => { let blob = new Blob([scriptTemplate],{type:'text/javascript'}); @@ -533,34 +515,24 @@ export class WorkerService extends Service { return message; } - terminate = (worker:Worker|MessagePort|string|WorkerInfo) => { + terminate = (worker:Worker|MessagePort|string) => { let onclose; - - let str; if(typeof worker === 'string') { - str = worker; let obj = this.workers[worker]; if(obj) { delete this.workers[worker]; worker = obj.worker; if(obj.onclose) onclose = obj.onclose; } - } else if (typeof worker === 'object') { - if((worker as WorkerInfo)?._id) { - worker = (worker as WorkerInfo).worker; - delete this.workers[(worker as WorkerInfo)?._id]; - } } if(worker instanceof Worker) { worker.terminate(); if(onclose) onclose(worker); - if(str && this.get(str)) this.remove(str); return true; } if(worker instanceof MessagePort) { worker.close(); if(onclose) onclose(worker); - if(str && this.get(str)) this.remove(str); return true; } return false; @@ -630,28 +602,24 @@ export class WorkerService extends Service { }); } - runRequest = (message:ServiceMessage|any, worker:undefined|string|Worker|MessagePort, callbackId:string|number, getTransferable=true) => { - + runRequest = (message:ServiceMessage|any, worker:undefined|string|Worker|MessagePort, callbackId:string|number) => { let res = this.receive(message); - if(typeof worker === 'string' && this.workers[worker]) { if(this.workers[worker].port) worker = this.workers[worker].port; else worker = this.workers[worker].worker; } if(res instanceof Promise) { res.then((r) => { - let transfer = getTransferable ? this.getTransferable(r) : undefined; if(worker instanceof Worker || worker instanceof MessagePort) - worker.postMessage({args:r,callbackId}, transfer) + worker.postMessage({args:r,callbackId}) else if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) - globalThis.postMessage({args:r,callbackId},transfer); + globalThis.postMessage({args:r,callbackId}); }); } else { - let transfer = getTransferable ? this.getTransferable(res) : undefined; if(worker instanceof Worker || worker instanceof MessagePort) - worker.postMessage({args:res,callbackId}, transfer) + worker.postMessage({args:res,callbackId}) else if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) - globalThis.postMessage({args:res,callbackId}, transfer); + globalThis.postMessage({args:res,callbackId}); } return res; @@ -660,13 +628,10 @@ export class WorkerService extends Service { subscribeWorker = ( route:string, worker:WorkerInfo|Worker|string|MessagePort, - args?:any[], - key?:string, - subInput?:boolean, blocking?:boolean, //requires a WorkerInfo object - getTransferable:boolean=true + key?:string, + subInput?:boolean ) => { - if(this.restrict?.[route]) return undefined; let callback:(res:any) => void; @@ -703,23 +668,20 @@ export class WorkerService extends Service { } else { callback = (res:any) => { + //console.log('subscription triggered for', route, 'to', worker instanceof Worker ? worker : 'window', 'result:', res); if(res instanceof Promise) { res.then((r) => { - let transfer = getTransferable ? this.getTransferable(r) : undefined; - //console.log(transfer); - if((worker as Worker)?.postMessage) - (worker as Worker).postMessage({args:r,callbackId:route}, transfer) + if((worker as any)?.postMessage) + (worker as any).postMessage({args:r,callbackId:route}) else if(globalThis.postMessage) - globalThis.postMessage({args:r,callbackId:route}, transfer); + globalThis.postMessage({args:r,callbackId:route}); }); } else { - let transfer = getTransferable ? this.getTransferable(res) : undefined; - //console.log(transfer); - if((worker as Worker)?.postMessage) - (worker as Worker).postMessage({args:res,callbackId:route}, transfer) + if((worker as any)?.postMessage) + (worker as any).postMessage({args:res,callbackId:route}) else if(globalThis.postMessage) - globalThis.postMessage({args:res,callbackId:route}, transfer); + globalThis.postMessage({args:res,callbackId:route}); } } } @@ -736,22 +698,20 @@ export class WorkerService extends Service { else worker = this.workers[worker].worker; } //else we are subscribing to window - return this.subscribe(route, callback, args, key, subInput); + return this.subscribe(route,callback,key,subInput); } subscribeToWorker = ( route:string, workerId:string, callback?:((res:any)=>void)|string, - args?:any[], + blocking?:boolean, key?:string, - subInput?:boolean, - blocking?:boolean, //blocking subscriptions won't return if the subscribing thread hasn't finished with the result - getTransferable = true //auto process transfer arrays (default true) + subInput?:boolean ) => { if(typeof workerId === 'string' && this.workers[workerId]) { - this.__node.state.subscribeEvent(workerId, (res) => { + this.__node.state.subscribeTrigger(workerId, (res) => { if(res?.callbackId === route) { if(!callback) this.setState({[workerId]:res.args}); //just set state else if(typeof callback === 'string') { //run a local node @@ -760,7 +720,7 @@ export class WorkerService extends Service { else callback(res.args); } }); - return this.workers[workerId].run('subscribeWorker', [route, workerId, args, key, subInput, blocking, getTransferable]); + return this.workers[workerId].run('subscribeWorker', [route, workerId, blocking, key, subInput]); } } @@ -781,18 +741,14 @@ export class WorkerService extends Service { sourceRoute:string, listenerRoute:string, portId?:string, - args?:any[], - key?:any, - subInput?:boolean, - blocking?:boolean, - getTransferable?:boolean + blocking?:boolean ) => { if(typeof sourceWorker === 'string') sourceWorker = this.workers[sourceWorker]; if(typeof listenerWorker === 'string') listenerWorker = this.workers[listenerWorker]; if(!portId) { portId = this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker) as string; } - return listenerWorker.run('subscribeToWorker',[sourceRoute,portId,listenerRoute,args,key,subInput,blocking,getTransferable]) as Promise; //just run .unsubscribe on worker2. + return listenerWorker.run('subscribeToWorker',[sourceRoute,portId,listenerRoute,blocking]) as Promise; //just run .unsubscribe on worker2. } unpipeWorkers = ( @@ -801,10 +757,32 @@ export class WorkerService extends Service { sub?:number ) => { if(typeof sourceWorker === 'string') sourceWorker = this.workers[sourceWorker]; - if(typeof sourceWorker === 'object') { - //console.log(sourceWorker,sourceRoute); + if(sourceWorker) return sourceWorker.run('unsubscribe',[sourceRoute,sub]); - } + } + + //requires unsafe service to load on other end + transferFunction(worker:WorkerInfo, fn:Function, fnName?:string) { + if(!fnName) fnName = fn.name; + return worker.request({ + route:'setRoute', + args:[ + fn.toString(), + fnName + ] + } as ServiceMessage); + } + + //requires unsafe service to load on other end + transferClass(worker:WorkerInfo, cls:Function, className?:string) { + if(!className) className = cls.name; + return worker.request({ + route:'receiveClass', + args:[ + cls.toString(), + className + ] + } as ServiceMessage); } } \ No newline at end of file diff --git a/src/services/worker/Worker.ts b/services/worker/Worker.ts similarity index 84% rename from src/services/worker/Worker.ts rename to services/worker/Worker.ts index 97210ada..ab5c9559 100644 --- a/src/services/worker/Worker.ts +++ b/services/worker/Worker.ts @@ -2,7 +2,7 @@ import { WorkerService } from './Worker.service'; //import { GPUService } from '../gpu/GPU.service'; import { workerCanvasRoutes } from './WorkerCanvas'; -import { remoteGraphRoutes } from '../remote/remote.routes'; +import { unsafeRoutes } from '../unsafe/Unsafe.service'; import { Math2 } from 'brainsatplay-math'; //wonder if we can have a scheme to dynamic import within the services? e.g. to bring in node-only or browser-only services without additional workers @@ -13,7 +13,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope (self as any).SERVICE = new WorkerService({ services:{ workerCanvasRoutes, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading Math, Math2 } diff --git a/src/services/worker/WorkerCanvas.ts b/services/worker/WorkerCanvas.ts similarity index 65% rename from src/services/worker/WorkerCanvas.ts rename to services/worker/WorkerCanvas.ts index e023b800..43b36fa9 100644 --- a/src/services/worker/WorkerCanvas.ts +++ b/services/worker/WorkerCanvas.ts @@ -1,6 +1,4 @@ //provide routes for applying canvases to workers - -import worker from './canvas.worker' import { proxyElementWorkerRoutes, initProxyElement } from './ProxyListener'; declare var WorkerGlobalScope; @@ -21,7 +19,7 @@ export type WorkerCanvasTransferProps = { //defined in main thread to send to wo export type CanvasProps = { //defined in worker thread canvas:any, //offscreen canvas context?:string|CanvasRenderingContext2D|WebGL2RenderingContext|WebGLRenderingContext, - _id:string, + _id?:string, width?:number, height?:number, draw?:string|((self:any,canvas:any,context:any)=>void), @@ -29,19 +27,18 @@ export type CanvasProps = { //defined in worker thread init?:string|((self,canvas:any,context:any)=>void), clear?:string|((self,canvas:any,context:any)=>void), animating?:boolean, - preventDefault?:boolean, //we can generically prevent defaults on key events (except F1-12 for debug reasons) [key:string]:any } export type CanvasControls = { _id:string, - draw:(props?:any,transfer?:any)=>void, //if you set props they will be available on "self" or "this" in the draw functions - update:(props:{[key:string]:any},transfer?:any)=>void, + draw:(props?:any)=>void, + update:(props:{[key:string]:any})=>void, clear:()=>void, init:()=>void, stop:()=>void, start:()=>void, - set:(newDrawProps:CanvasProps,transfer?:any)=>void + set:(newDrawProps:CanvasProps)=>void } export type WorkerCanvasControls = { @@ -58,23 +55,14 @@ export type WorkerCanvas = { //this is the object stored on the worker to track update?:((self:WorkerCanvas,canvas:WorkerCanvas['canvas'],context:WorkerCanvas['context'],input:any)=>void), init?:((self:WorkerCanvas,canvas:WorkerCanvas['canvas'],context:WorkerCanvas['context'])=>void), clear?:((self:WorkerCanvas,canvas:WorkerCanvas['canvas'],context:WorkerCanvas['context'])=>void), - stop:()=>void, - start:()=>void, - set:(newDrawProps:CanvasProps,transfer?:any)=>void, - terminate:()=>void, animating:boolean, //animation will start automatically, else you can call draw conditionally [key:string]:any //any transferrable props you want to use in your animation } export function Renderer( - options:CanvasProps & { - worker?:Worker|string|Blob|MessagePort|true, - route?:string - } + options:CanvasProps & {worker?:Worker|string|Blob|MessagePort, route?:string} ) { - if(options.worker === true) { - options.worker = worker - } + if(options.worker) { let worker = options.worker; let route = options.route; @@ -85,10 +73,10 @@ export function Renderer( delete options.worker; delete options.route; - return transferCanvas(worker as any, options as WorkerCanvasTransferProps, route); + return transferCanvas(worker, options as WorkerCanvasTransferProps, route); } else { - initProxyElement(options.canvas,undefined,options._id, options.preventDefault); + initProxyElement(options.canvas,undefined,options._id); return setupCanvas(options); } } @@ -100,12 +88,11 @@ export function transferCanvas( route?:string //we can reroute from the default 'setupCanvas' e.g. for other rendering init processes like in threejs ) { - //console.log(options); if(!options) return undefined; if(!options._id) options._id = `canvas${Math.floor(Math.random()*1000000000000000)}`; - let offscreen = options.canvas instanceof OffscreenCanvas ? options.canvas : (options.canvas as any).transferControlToOffscreen(); + let offscreen = (options.canvas as any).transferControlToOffscreen(); if(!options.width) options.width = options.canvas.clientWidth; if(!options.height) options.height = options.canvas.clientHeight; @@ -114,9 +101,8 @@ export function transferCanvas( canvas:offscreen, }}; - let proxy; - if(this?.__node?.graph) proxy = this.__node.graph.run('initProxyElement', options.canvas, worker, options._id, options.preventDefault); //initiate an element proxy - else proxy = initProxyElement(options.canvas,worker,options._id, options.preventDefault); + if(this?.__node?.graph) this.__node.graph.run('initProxyElement', options.canvas, worker, options._id); //initiate an element proxy + else initProxyElement(options.canvas,worker,options._id); if(options.draw) { if(typeof options.draw === 'function') message.args.draw = options.draw.toString() @@ -135,15 +121,15 @@ export function transferCanvas( else message.args.clear = options.clear; } - let tr = [offscreen]; + let transfer = [offscreen]; if(options.transfer) { - tr.push(...options.transfer); + transfer.push(...options.transfer); delete options.transfer; } //console.log(worker,message); - worker.postMessage(message,tr); + worker.postMessage(message,transfer); //lets add some utilities to make it easy to update the thread const canvascontrols = { @@ -151,11 +137,11 @@ export function transferCanvas( width:options.width, height:options.height, worker, - draw:(props?:any,transfer?:any)=>{ - worker.postMessage({route:'drawFrame',args:[props,options._id]},transfer); + draw:(props?:any)=>{ + worker.postMessage({route:'drawFrame',args:[props,options._id]}); }, - update:(props:{[key:string]:any},transfer?:any)=>{ - worker.postMessage({route:'updateCanvas',args:[props,options._id]}, transfer); + update:(props:{[key:string]:any})=>{ + worker.postMessage({route:'updateCanvas',args:[props,options._id]}) }, clear:()=>{ worker.postMessage({route:'clearCanvas',args:options._id}) @@ -170,11 +156,10 @@ export function transferCanvas( start:()=>{ worker.postMessage({route:'startAnim',args:options._id}) }, - set:(newDrawProps:CanvasProps,transfer?:any)=>{ - worker.postMessage({route:'setDraw',args:[newDrawProps,options._id]},transfer); + set:(newDrawProps:CanvasProps)=>{ + worker.postMessage({route:'setDraw',args:[newDrawProps,options._id]}); }, terminate:()=>{ - if(proxy) proxy.terminate(); (worker as Worker).terminate(); } } @@ -201,13 +186,10 @@ export function setDraw( if(settings.canvas) { canvasopts.canvas = settings.canvas; - if(canvasopts.proxy) canvasopts.proxy.terminate(); - let proxy; //create an element proxy to add event listener functionality - if(this?.__node?.graph) proxy = this.__node.graph.run('makeProxy', canvasopts._id, canvasopts.canvas); - else proxy = proxyElementWorkerRoutes.makeProxy(canvasopts._id, canvasopts.canvas); + if(this?.__node?.graph) this.__node.graph.run('makeProxy', canvasopts._id, canvasopts.canvas); + else proxyElementWorkerRoutes.makeProxy(canvasopts._id, canvasopts.canvas); - canvasopts.proxy = proxy; //now the canvas can handle mouse and resize events, more can be implemented } if(typeof settings.context === 'string') canvasopts.context = canvasopts.canvas.getContext(settings.context); @@ -217,19 +199,19 @@ export function setDraw( if(settings.height) canvasopts.canvas.height = settings.height; if(typeof settings.draw === 'string') settings.draw = parseFunctionFromText(settings.draw); if(typeof settings.draw === 'function') { - canvasopts.draw = settings.draw.bind(settings); + canvasopts.draw = settings.draw; } if(typeof settings.update === 'string') settings.update = parseFunctionFromText(settings.update); if(typeof settings.update === 'function') { - canvasopts.update = settings.update.bind(settings); + canvasopts.update = settings.update; } if(typeof settings.init === 'string') settings.init = parseFunctionFromText(settings.init); if(typeof settings.init === 'function') { - canvasopts.init = settings.init.bind(settings); + canvasopts.init = settings.init; } if(typeof settings.clear === 'string') settings.clear = parseFunctionFromText(settings.clear); if(typeof settings.clear === 'function') { - canvasopts.clear = settings.clear.bind(settings); + canvasopts.clear = settings.clear; } return settings._id; } @@ -251,29 +233,19 @@ export function setupCanvas( typeof options.context === 'string' ? canvasOptions.context = options.canvas.getContext(options.context) : canvasOptions.context = options.context; //get the rendering context based on string passed ('animating' in options) ? canvasOptions.animating = options.animating : canvasOptions.animating = true; - let proxy; if(this?.__node?.graph?.CANVASES[canvasOptions._id]) { this.__node.graph.run('setDraw',canvasOptions); } else if(globalThis.CANVASES?.[canvasOptions._id]) { setDraw(canvasOptions); } else { - if(this?.__node?.graph) { - canvasOptions.graph = this.__node.graph; - if(!canvasOptions.__node) {canvasOptions.__node = {}} - if(!canvasOptions.__node.tag) canvasOptions.__node.tag = canvasOptions._id; - canvasOptions = this.__node.graph.add(canvasOptions); //replace with node - canvasOptions.__addOndisconnected = () => { - canvasOptions.stop(); - delete this.__node.graph.CANVASES[canvasOptions._id]; - } - } + if(this?.__node?.graph) canvasOptions.graph = this.__node.graph; if(this?.__node?.graph) this.__node.graph.CANVASES[canvasOptions._id] = canvasOptions; else globalThis.CANVASES[canvasOptions._id] = canvasOptions; //create an element proxy to add event listener functionality - if(this?.__node?.graph) proxy = this.__node.graph.run('makeProxy', canvasOptions._id, canvasOptions.canvas); - else proxy = proxyElementWorkerRoutes.makeProxy(canvasOptions._id, canvasOptions.canvas); + if(this?.__node?.graph) this.__node.graph.run('makeProxy', canvasOptions._id, canvasOptions.canvas); + else proxyElementWorkerRoutes.makeProxy(canvasOptions._id, canvasOptions.canvas); //now the canvas can handle mouse and resize events, more can be implemented if(options.width) canvasOptions.canvas.width = options.width; @@ -282,120 +254,97 @@ export function setupCanvas( if(typeof canvasOptions.draw === 'string') { canvasOptions.draw = parseFunctionFromText(canvasOptions.draw); } else if(typeof canvasOptions.draw === 'function') { - canvasOptions.draw = canvasOptions.draw.bind(canvasOptions); + canvasOptions.draw = canvasOptions.draw; } if(typeof canvasOptions.update === 'string') { canvasOptions.update = parseFunctionFromText(canvasOptions.update); } else if(typeof canvasOptions.update === 'function') { - canvasOptions.update = canvasOptions.update.bind(canvasOptions); + canvasOptions.update = canvasOptions.update; } if(typeof canvasOptions.init === 'string') { canvasOptions.init = parseFunctionFromText(canvasOptions.init); } else if(typeof canvasOptions.init === 'function') { - canvasOptions.init = canvasOptions.init.bind(canvasOptions); + canvasOptions.init = canvasOptions.init; } if(typeof canvasOptions.clear === 'string') { canvasOptions.clear = parseFunctionFromText(canvasOptions.clear); } else if(typeof canvasOptions.clear === 'function') { - canvasOptions.clear = canvasOptions.clear.bind(canvasOptions); + canvasOptions.clear = canvasOptions.clear; } - - const finishSetup = () => { - canvasOptions.stop = () => {stopAnim(canvasOptions._id);}; - canvasOptions.start = (draw?:any) => {startAnim(canvasOptions._id,draw);}; - canvasOptions.set = (settings:any) => {setDraw(settings,canvasOptions._id);} - - if(typeof canvasOptions.draw === 'function' && canvasOptions.animating) { - let draw = (s,canvas,context) => { - if(s.animating) { - let res = s.draw(s,canvas,context); - if(res?.then) { - res.then(() => { - requestAnimationFrame(()=>{ - draw(s,canvas,context); - }); - }) - } - else requestAnimationFrame(()=>{ - draw(s,canvas,context); - }); - } - } - - draw(canvasOptions, canvasOptions.canvas,canvasOptions.context); - - } + if(typeof canvasOptions.init === 'function') + (canvasOptions.init as any)(canvasOptions, canvasOptions.canvas,canvasOptions.context); - if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) - return canvasOptions._id as string; - else { - //lets add some utilities to make it easy to update the thread - const canvascontrols = { - _id:options._id, - width:options.width, - height:options.height, - proxy, - draw:(props?:any)=>{ - drawFrame(props,options._id); - }, - update:(props:{[key:string]:any})=>{ - updateCanvas(props,options._id); - }, - clear:()=>{ - clearCanvas(options._id); - }, - init:()=>{ - //console.log('Posting init') - initCanvas(options._id); - }, - stop:()=>{ - stopAnim(options._id); - }, - start:()=>{ - startAnim(options._id); - }, - set:(newDrawProps:CanvasProps)=>{ - setDraw(newDrawProps,options._id); - }, - terminate:()=>{ - if(canvascontrols.proxy) { - canvascontrols.proxy.terminate(); - } - if(this.__node?.graph) this.__node.graph.remove(options._id); - else { - stopAnim(options._id); - if(this?.__node?.graph) delete this.__node.graph.CANVASES[canvasOptions._id]; - else delete globalThis.CANVASES[canvasOptions._id]; - } - } - } + canvasOptions.stop = () => {stopAnim(canvasOptions._id);}; + canvasOptions.start = (draw?:any) => {startAnim(canvasOptions._id,draw);}; + canvasOptions.set = (settings:any) => {setDraw(settings,canvasOptions._id);} - return canvascontrols as CanvasControls; + if(typeof canvasOptions.draw === 'function' && canvasOptions.animating) { + let draw = (s,canvas,context) => { + if(s.animating) { + s.draw(s,canvas,context); + requestAnimationFrame(()=>{ + draw(s,canvas,context); + }); + } } + + draw(canvasOptions, canvasOptions.canvas,canvasOptions.context); + } + } - if(typeof canvasOptions.init === 'function') { - let res = (canvasOptions.init as any)(canvasOptions, canvasOptions.canvas,canvasOptions.context); - if(res?.then) { - return new Promise((resolve) => { - res.then(()=>{ - resolve(finishSetup()) - }); - }) as Promise; - } - } - return finishSetup(); + if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) + return canvasOptions._id as string; + else { + //lets add some utilities to make it easy to update the thread + const canvascontrols = { + _id:options._id, + width:options.width, + height:options.height, + draw:(props?:any)=>{ + drawFrame(props,options._id); + }, + update:(props:{[key:string]:any})=>{ + updateCanvas(props,options._id); + }, + clear:()=>{ + clearCanvas(options._id); + }, + init:()=>{ + //console.log('Posting init') + initCanvas(options._id); + }, + stop:()=>{ + stopAnim(options._id); + }, + start:()=>{ + startAnim(options._id); + }, + set:(newDrawProps:CanvasProps)=>{ + setDraw(newDrawProps,options._id); + }, + terminate:()=>{ + stopAnim(options._id); + } + } + return canvascontrols as CanvasControls; } } //local function copy, same thing but returns the whole canvas object export function drawFrame(props?:{[key:string]:any},_id?:string) { //can update props when calling draw - - let canvasopts = getCanvas.call(this, _id); + let canvasopts; + if(this?.__node?.graph) { + if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else canvasopts = globalThis.CANVASES?.[_id]; + } if(canvasopts) { if(props) Object.assign(canvasopts,props); if(canvasopts.draw) { @@ -408,8 +357,14 @@ export function drawFrame(props?:{[key:string]:any},_id?:string) { //can update export function clearCanvas(_id?:string) { - - let canvasopts = getCanvas.call(this, _id); + let canvasopts; + if(this?.__node?.graph) { + if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else canvasopts = globalThis.CANVASES?.[_id]; + } if(canvasopts?.clear) { canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context); @@ -419,8 +374,14 @@ export function clearCanvas(_id?:string) { } export function initCanvas(_id?:string){ - - let canvasopts = getCanvas.call(this, _id); + let canvasopts; + if(this?.__node?.graph) { + if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else canvasopts = globalThis.CANVASES?.[_id]; + } if(canvasopts?.init) { canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context); @@ -430,9 +391,14 @@ export function initCanvas(_id?:string){ } export function updateCanvas(input?:any,_id?:string){ - - let canvasopts = getCanvas.call(this, _id); - + let canvasopts; + if(this?.__node?.graph) { + if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else canvasopts = globalThis.CANVASES?.[_id]; + } if(canvasopts?.update) { canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input); return _id; @@ -440,11 +406,16 @@ export function updateCanvas(input?:any,_id?:string){ return undefined; } -export function setProps(props?:{[key:string]:any},_id?:string){ //update animation props, e.g. the radius or color of a circle you are drawing with a stored value - - let canvasopts = getCanvas.call(this, _id); - - if(canvasopts && props) { +export function setProps(props?:{[key:string]:any},_id?:string,){ //update animation props, e.g. the radius or color of a circle you are drawing with a stored value + let canvasopts; + if(this?.__node?.graph) { + if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else canvasopts = globalThis.CANVASES?.[_id]; + } + if(canvasopts) { Object.assign(canvasopts,props); if(props.width) canvasopts.canvas.width = props.width; if(props.height) canvasopts.canvas.height = props.height; @@ -455,8 +426,14 @@ export function setProps(props?:{[key:string]:any},_id?:string){ //update animat export function startAnim(_id?:string, draw?:string|((this:any,canvas:any,context:any)=>void)){ //run the draw function applied to the animation or provide a new one - let canvasopts = getCanvas.call(this, _id); - + let canvasopts; + if(this?.__node?.graph) { + if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else canvasopts = globalThis.CANVASES?.[_id]; + } canvasopts.animating = true; if(canvasopts && draw) { if(typeof draw === 'string') draw = parseFunctionFromText(draw); @@ -485,20 +462,7 @@ export function startAnim(_id?:string, draw?:string|((this:any,canvas:any,contex return undefined; } -export function stopAnim(_id:string){ - - let canvasopts = getCanvas.call(this, _id); - - if(canvasopts) { - canvasopts.animating = false; - if(typeof canvasopts.clear === 'function') - requestAnimationFrame(canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context)); - return _id; - } - return undefined; -} - -export function getCanvas (_id?:string) { +export function stopAnim(_id?:string){ let canvasopts; if(this?.__node?.graph) { if(!_id) canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; @@ -507,7 +471,12 @@ export function getCanvas (_id?:string) { if(!_id) canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; else canvasopts = globalThis.CANVASES?.[_id]; } - return canvasopts; + if(canvasopts) { + canvasopts.animating = false; + if(typeof canvasopts.clear === 'function') canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return undefined; } //load on front and backend @@ -523,8 +492,7 @@ export const workerCanvasRoutes = { updateCanvas:updateCanvas, setProps:setProps, startAnim:startAnim, - stopAnim:stopAnim, - getCanvas:getCanvas + stopAnim:stopAnim }; function parseFunctionFromText(method='') { @@ -566,7 +534,4 @@ function parseFunctionFromText(method='') { return newFunc; -} - - - +} \ No newline at end of file diff --git a/services/worker/canvas.worker.ts b/services/worker/canvas.worker.ts new file mode 100644 index 00000000..bed0d6cd --- /dev/null +++ b/services/worker/canvas.worker.ts @@ -0,0 +1,19 @@ +import { workerCanvasRoutes } from './WorkerCanvas'; +//minimal web worker for running offscreen canvases, +//no graphscript required + +const routes = { + ...workerCanvasRoutes + //add more compatible routes that don't require graphscript +}; + +self.onmessage = (ev) => { + if(ev.data.route) { + if(Array.isArray(ev.data.args)) { + routes[ev.data.route](...ev.data.args); + } else routes[ev.data.route](ev.data.args); + } //that's it! The functions handle worker communication internally + +} + +export default self as any; \ No newline at end of file diff --git a/services/wss/WSS.browser.ts b/services/wss/WSS.browser.ts new file mode 100644 index 00000000..882c9210 --- /dev/null +++ b/services/wss/WSS.browser.ts @@ -0,0 +1,336 @@ + +import { Service, ServiceMessage, ServiceOptions } from "../Service"; + +export type WebSocketProps = { + host:string, + port:number, + path?:string, + onmessage?:(data:string | ArrayBufferLike | Blob | ArrayBufferView, ws:WebSocket, wsinfo:WebSocketInfo)=>void, //will use this.receive as default + onopen?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, + onclose?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, + onerror?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void + protocol?:'ws'|'wss', + keepState?:boolean, + type?:'socket', + _id?:string, + [key:string]:any +} + +export type WebSocketInfo = { + socket:WebSocket, + address:string, + send:(message:any)=>void, + request:(message:any, method?:string)=>Promise, + post:(route:any, args?:any)=>void, + run:(route:any, args?:any, method?:string)=>Promise, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, + unsubscribe:(route:any, sub:number)=>Promise, + terminate:()=>boolean, + _id?:string, + graph:WSSfrontend +} & WebSocketProps + +//browser side websockets +export class WSSfrontend extends Service { + + name='wss' + + sockets:{ + [key:string]:WebSocketInfo + } = { } + + connections = { //higher level reference for Router + sockets:this.sockets + } + + + constructor(options?:ServiceOptions) { + super(options) + // this.setTree(this); + } + + openWS = ( + options:WebSocketProps = { + host:'localhost', + port:7000, + path:undefined, + protocol:'ws', + onclose:(ev:any,socket:WebSocket,wsinfo:WebSocketInfo)=>{ + if(ev.target.url) delete this.sockets[ev.target.url]; + } + } + ) => { + let protocol = options.protocol; + if(!protocol) protocol = 'ws'; + let address = `${protocol}://${options.host}`; + + if(!('keepState' in options)) options.keepState = true; + if(options.port) address+= ':'+options.port; + if(options.path && !options.path?.startsWith('/')) address += '/'; + if(options.path) address += options.path; + + if(this.sockets[address]?.socket) + if(this.sockets[address].socket.readyState === this.sockets[address].socket.OPEN) + this.sockets[address].socket.close(); //we'll try refresh the socket + + const socket = new WebSocket(address); + + if(!options.onmessage) { + if(!options._id){ + options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { + if(data) if(typeof data === 'string') { + let substr = data.substring(0,8); + if(substr.includes('{') || substr.includes('[')) { + if(substr.includes('\\')) data = data.replace(/\\/g,""); + if(data[0] === '"') { data = data.substring(1,data.length-1)}; + //console.log(message) + data = JSON.parse(data); //parse stringified objects + + if(data.route === 'setId') { + this.sockets[address]._id = data.args; + options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { //clear extra logic after id is set + this.receive(data); + if(options.keepState) { + this.setState({[address as string]:data}); + } + } + } + } + } + + let res = this.receive(data); + if(options.keepState) this.setState({[address]:data}); + } //default onmessage + } + else { + options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo)=> { + this.receive(data,socket,this.sockets[address]); + if(options.keepState) { + this.setState({[address]:data}); + } + }; //clear this extra logic after id is set + } + } + + if((options as any).onmessage) { + socket.addEventListener('message',(ev)=>{ + (this.sockets[address] as any).onmessage(ev.data, socket, this.sockets[address]); + }); + } + socket.addEventListener('open',(ev)=>{if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(ev,socket, this.sockets[address]);}); + socket.addEventListener('close',(ev)=>{if(this.sockets[address].onclose) (this.sockets[address] as any).onclose(ev,socket, this.sockets[address]);}); + socket.addEventListener('error',(ev)=>{if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(ev,socket, this.sockets[address]);}); + + + let send = (message:ServiceMessage|any) => { + //console.log('sent', message) + return this.transmit(message,socket); + } + + let post = (route:any,args?:any, method?:string) => { + //console.log('sent', message) + let message:any = { + route, + args + }; + if(method) message.method = method; + + return this.transmit(message,socket); + } + + let run = (route:any,args?:any,method?:string) => { + return new Promise ((res,rej) => { + let callbackId = Math.random(); + let req = {route:'runRequest', args:[{route, args}, options._id, callbackId]} as any; + //console.log(req) + if(method) req.args[0].method = method; + let onmessage = (ev)=>{ + if(typeof ev.data === 'string' && ev.data.indexOf('{') > -1) ev.data = JSON.parse(ev.data); + if(typeof ev.data === 'object') { + if(ev.data.callbackId === callbackId) { + socket.removeEventListener('message',onmessage); + res(ev.data.args); //resolve the request with the corresponding message + } + } + } + socket.addEventListener('message',onmessage) + this.transmit(req, socket); + }); + } + + let request = (message:ServiceMessage|any, method?:string) => { + return new Promise ((res,rej) => { + let callbackId = Math.random(); + let req = {route:'runRequest', args:[message,options._id,callbackId]} as any; + //console.log(req) + if(method) req.method = method; + let onmessage = (ev)=>{ + if(typeof ev.data === 'string' && ev.data.indexOf('{') > -1) ev.data = JSON.parse(ev.data); + if(typeof ev.data === 'object') { + if(ev.data.callbackId === callbackId) { + socket.removeEventListener('message',onmessage); + res(ev.data.args); //resolve the request with the corresponding message + } + } + } + socket.addEventListener('message',onmessage) + this.transmit(req, socket); + }); + } + + let subscribe = (route:any, callback?:((res:any)=>void)|string):Promise => { + return this.subscribeToSocket(route, options._id, callback); + } + + let unsubscribe = (route:any, sub:number):Promise => { + return run('unsubscribe',[route,sub]); + } + + let terminate = () => { + return this.terminate(options._id); + } + + this.sockets[address] = { + type:'socket', + socket, + address, + send, + post, + run, + request, + subscribe, + unsubscribe, + terminate, + graph:this, + ...options + }; + + return this.sockets[address]; + } + + open = this.openWS; + + transmit = ( + data:string | ArrayBufferLike | Blob | ArrayBufferView | ServiceMessage, + ws:WebSocket + ) => { + if(typeof data === 'object') data = JSON.stringify(data); + if(!ws) { + let s = this.sockets[Object.keys(this.sockets)[0]]; + if(s) ws = s.socket; + } + + if(ws instanceof WebSocket && ws?.readyState === 1) ws.send(data); + + return true; + } + + terminate = (ws:WebSocket|string) => { + if(!ws) { + let key = Object.keys(this.sockets)[0] + if(key) ws = this.sockets[key].socket; + } + else if(typeof ws === 'string') { + for(const k in this.sockets) { + if(k.includes(ws)) { + ws = this.sockets[k].socket; + break; + } + } + } + + if(ws instanceof WebSocket) + if(ws.readyState === ws.OPEN) + ws.close(); + + return true; + } + + request = ( + message:ServiceMessage|any, + ws:WebSocket, + _id:string, + method?:string + ) => { //return a promise which can resolve with a server route result through the socket + let callbackId = `${Math.random()}`; + let req:any = {route:'runRequest', args:[message,_id,callbackId]}; + if(method) req.method = method; + return new Promise((res,rej) => { + let onmessage = (ev:any) => { + let data = ev.data; + if(typeof data === 'string') if(data.includes('callbackId')) data = JSON.parse(data); + if(typeof data === 'object') if(data.callbackId === callbackId) { + ws.removeEventListener('message',onmessage); + res(data.args); + } + } + + ws.addEventListener('message',onmessage); + ws.send(JSON.stringify(req)); + }) + } + + runRequest = ( + message:any, + ws:WebSocket|string, + callbackId:string|number + ) => { //send result back + let res = this.receive(message); + if(typeof ws === 'string') { + for(const s in this.sockets) { + if(s === ws) {ws = this.sockets[s].socket; break;} + } + } + if(ws) { + if(res instanceof Promise) { + res.then((v) => { + res = {args:v, callbackId}; + if(ws instanceof WebSocket) ws.send(JSON.stringify(res)); + }) + } + else { + res = {args:res, callbackId}; + if(ws instanceof WebSocket) ws.send(JSON.stringify(res)); + } + } + + return res; + } + + subscribeSocket = (route:string, socket:WebSocket|string, key?:string, subInput?:boolean) => { + if(typeof socket === 'string' && this.sockets[socket]) { + socket = this.sockets[socket].socket; + } + + if(typeof socket === 'object') + return this.subscribe(route, (res:any) => { + //console.log('running request', message, 'for worker', worker, 'callback', callbackId) + if((socket as WebSocket).readyState === (socket as WebSocket).OPEN) { + if(res instanceof Promise) { + res.then((r) => { + (socket as WebSocket).send(JSON.stringify({args:r, callbackId:route})); + }); + } else { + (socket as WebSocket).send(JSON.stringify({args:res, callbackId:route})); + } + } + },key,subInput); + } + + subscribeToSocket = (route:string, socketId:string, callback?:((res:any)=>void)|string, key?:string, subInput?:boolean) => { + if(typeof socketId === 'string' && this.sockets[socketId]) { + this.__node.state.subscribeTrigger(socketId, (res) => { + let msg = JSON.parse(res); + if(msg?.callbackId === route) { + if(!callback) this.setState({[socketId]:msg.args}); //just set state + else if(typeof callback === 'string') { //run a local node + this.run(callback,msg.args); + } + else callback(msg.args); + } + }); + return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId,key,subInput]}); + } + } + +} diff --git a/src/services/wss/WSS.node.ts b/services/wss/WSS.node.ts similarity index 68% rename from src/services/wss/WSS.node.ts rename to services/wss/WSS.node.ts index 544732e4..54ea35fa 100644 --- a/src/services/wss/WSS.node.ts +++ b/services/wss/WSS.node.ts @@ -1,17 +1,14 @@ import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import WebSocket, { PerMessageDeflateOptions, WebSocketServer } from 'ws'; //third party lib. //createWebSocketStream <-- use this for cross-node instance communication +import WebSocket, { WebSocketServer } from 'ws'; //third party lib. //createWebSocketStream <-- use this for cross-node instance communication import http from 'http' import https from 'https' -import { GraphNodeProperties } from "../../core/Graph"; //import { GraphNode } from "../Graph"; export type SocketServerProps = { - server?:http.Server|https.Server|true, //set to true to indicate you want a wss when using the open() command if not providing a server... - port?:7000|number, - path?:'wss'|'hotreload'|'python'|string, - noServer?:boolean, - host?:'localhost'|'127.0.0.1'|string, //for matching upgrade urls - perMessageDeflate?:PerMessageDeflateOptions, + server:http.Server|https.Server, + host:'localhost'|'127.0.0.1'|string, + port:7000|number, + path:'wss'|'hotreload'|'python'|string, onmessage?:(data:any, ws:WebSocket, serverinfo:SocketServerInfo)=>void, onclose?:(wss:WebSocketServer, serverinfo:SocketServerInfo)=>void, onconnection?:(ws:WebSocket,request:http.IncomingMessage, serverinfo:SocketServerInfo, clientId:string)=>void, @@ -20,10 +17,8 @@ export type SocketServerProps = { onupgrade?:(ws:WebSocket, serverinfo:SocketServerInfo, request:http.IncomingMessage, socket:any, head:Buffer)=>void, //after handleUpgrade is called keepState?:boolean, type?:'wss', - debug?:boolean - serverOptions?:WebSocket.ServerOptions, [key:string]:any -} & GraphNodeProperties +} export type SocketServerInfo = { wss:WebSocketServer, @@ -45,7 +40,6 @@ export type SocketProps = { path?:string, socket?:WebSocket, address?:string, - debug?:boolean, serverOptions?:WebSocket.ServerOptions onmessage?:(data:string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[], ws:WebSocket,wsinfo:SocketProps)=>void, //will use this.receive as default onopen?:(ws:WebSocket,wsinfo:SocketProps)=>void, @@ -55,7 +49,7 @@ export type SocketProps = { type?:'socket', _id?:string, keepState?:boolean -} & GraphNodeProperties +} export type SocketInfo = { socket:WebSocket, @@ -64,7 +58,7 @@ export type SocketInfo = { request:(message:any, method?:string)=>Promise, post:(route:any, args?:any, method?:string)=>void, run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?:any[], key?:string, subInput?:boolean)=>any, + subscribe:(route:any, callback?:((res:any)=>void)|string)=>any, unsubscribe:(route:any, sub:number)=>Promise, terminate:()=>void, graph:WSSbackend @@ -93,7 +87,7 @@ export class WSSbackend extends Service { constructor(options?:ServiceOptions) { super(options) - this.load(this); + this.setTree(this); } open = (options:SocketServerProps | SocketProps) => { @@ -106,35 +100,25 @@ export class WSSbackend extends Service { options:SocketServerProps, ) => { - let port = options.port; + const host = options.host; + const port = options.port; let path = options.path; - const server = typeof options.server === 'object' ? options.server : undefined; - let host = options.host; + const server = options.server; delete (options as any).server if(!('keepState' in options)) options.keepState = true; - let opts = {} as any; - if(options.noServer) opts.noServer = true; - else if(port) { - if(port) opts.port = port; - } - else if(server) opts.server = server; - if(options.perMessageDeflate) opts.perMessageDeflate = options.perMessageDeflate; + let opts = { + host, + port + }; - if(typeof options.serverOptions) Object.assign(opts,options.serverOptions); + if(typeof options.serverOptions) Object.assign(opts,options.serverOptions) const wss = new WebSocketServer(opts); - let address = ''; - if(!host && server) { - let addr = server.address() as any; - if(!port) port = addr.port; - address = addr.address; - - } else if(host) address = host; - if(port) address += ':'+port; + let address = `${host}:${port}/`; if(path) { - if(!path.startsWith('/')) path = '/'+path; + if(path.startsWith('/')) path = path.substring(1); address += path; } @@ -148,10 +132,6 @@ export class WSSbackend extends Service { if(!options.onmessage) options.onmessage = (data) => { //default onmessage if(data instanceof Buffer) data = data.toString(); - - if(options.debug) { - console.log(data); - } //console.log(data); const result = this.receive(data, wss, this.servers[address]); //console.log(result) @@ -159,7 +139,7 @@ export class WSSbackend extends Service { } - wss.addListener('connection',(ws,request) => { + wss.on('connection',(ws,request) => { if(this.debug) console.log(`New socket connection on ${address}`); let clientId = `socket${Math.floor(Math.random()*1000000000000)}`; @@ -167,28 +147,20 @@ export class WSSbackend extends Service { ws.send(JSON.stringify({ route:'setId', args:clientId })); - this.openWS({ + let info = this.openWS({ socket:ws, address:clientId, - _id:clientId, - debug:options.debug, - onclose:(code,reason) => { - if(this.servers[address].onconnectionclosed) - (this.servers[address] as any).onconnectionclosed(code, reason, ws, this.servers[address], clientId); - - delete this.servers[address].clients[clientId]; //delete by default onclose (memory saving) - } + _id:clientId }); //add send/receive etc functionality - if(options.debug) { - let time = getHoursAndMinutes(new Date()); - console.log(time, ' | ', clientId, ' | Number of live sockets: ', Object.keys(this.servers[address].clients).length); - } - if((this.servers[address] as any).onconnection) (this.servers[address] as any).onconnection(ws,request,this.servers[address], clientId);//can overwrite the default onmesssage response - + + if((this.servers[address] as any).onconnectionclosed) + ws.on('close',(code,reason)=>{ + if(this.servers[address].onconnectionclosed) (this.servers[address] as any).onconnectionclosed(code,reason,ws, this.servers[address], clientId); + }); }); wss.on('error',(err) => { @@ -197,46 +169,32 @@ export class WSSbackend extends Service { else console.error(err); }) - let onUpgrade = (request:http.IncomingMessage, socket:any, head:Buffer) => { //https://github.com/websockets/ws + let onUpgrade = (request:http.IncomingMessage,socket:any,head:Buffer) => { //https://github.com/websockets/ws if(request.headers && request.url) { if(this.debug) console.log("Upgrade request at: ", request.url); - let pass = false; - - if(path && request.url === path) pass = true; - else { - let addr = (request as any).headers.host.split(':')[0]; - if(port) addr += ':'+port; - if(addr === address) pass = true; - else { - addr += request.url.split('?')[0]; - if(addr === address) pass = true; - } - } - - if(pass && this.servers[address]) { - this.servers[address].wss.handleUpgrade(request,socket,head, (ws) => { - if((this.servers[address] as any).onupgrade) - (this.servers[address] as any).onupgrade(ws, this.servers[address], request, socket, head); - this.servers[address].wss.emit('connection', ws, request); + let addr = (request as any).headers.host.split(':')[0]; + addr += ':'+port; + addr += request.url.split('?')[0]; + + if(addr === address && this.servers[addr]) { + this.servers[addr].wss.handleUpgrade(request,socket,head, (ws) => { + if((this.servers[address] as any).onupgrade) (this.servers[address] as any).onupgrade(ws, this.servers[address], request, socket, head); + this.servers[addr].wss.emit('connection',ws,request); }); } } } - if(server) - server.addListener('upgrade', onUpgrade); + server.addListener('upgrade',onUpgrade); - wss.addListener('close',()=> { - if(server) server.removeListener('upgrade',onUpgrade); + wss.on('close',()=> { + server.removeListener('upgrade',onUpgrade); if((this.servers[address] as any).onclose) (this.servers[address] as any).onclose(wss, this.servers[address]); else console.log(`wss closed: ${address}`); - - delete this.servers[address]; }); let send = (message:any, socketId?:string) => { - if(typeof message === 'object') message = JSON.stringify(message); if(!socketId) { for(const key in this.servers[address].clients) { this.sockets[key].send(message); @@ -272,14 +230,14 @@ export class WSSbackend extends Service { } else return this.sockets[socketId].run(route,args, method); }; - let subscribe = (route:any, callback?:((res:any)=>void)|string,socketId?:string, args?:any[], key?:string, subInput?:boolean) => { + let subscribe = (route:any, callback?:((res:any)=>void)|string,socketId?:string) => { if(!socketId) { let promises:any=[] - for(const k in this.servers[address].clients) { - promises.push(this.sockets[k].subscribe(route,callback,args,key,subInput)); + for(const key in this.servers[address].clients) { + promises.push(this.sockets[key].subscribe(route,callback)); } return promises; - } else this.sockets[socketId].subscribe(route,callback,args,key,subInput); + } else this.sockets[socketId].subscribe(route,callback); }; let unsubscribe = (route:any, sub:number,socketId?:string) => { @@ -330,28 +288,11 @@ export class WSSbackend extends Service { if(!('keepState' in options)) options.keepState = true; - if(options.onmessage) { - socket.on( - 'message', - (data)=>{( - this.sockets[address] as any).onmessage( - data, - socket, - this.sockets[address] - ); - } - ); - } - + if(options.onmessage) socket.on('message',(data)=>{(this.sockets[address] as any).onmessage(data,socket,this.sockets[address]);}); else if (options._id) { - socket.addListener('message', (data:any)=> { + socket.on('message', (data:any)=> { if(ArrayBuffer.isView(data)) data = data.toString(); - - if(options.debug) { - console.log("Message from ",options._id, ": ", data); - } - - this.receive(data,socket, this.sockets[address]); + this.receive(data,socket,this.sockets[address]); //console.log('socket received',data,Array.from(this.__node.nodes.keys())); if(options.keepState) { this.setState({[address]:data}); @@ -362,9 +303,6 @@ export class WSSbackend extends Service { let socketonmessage = (data:any)=>{ if(ArrayBuffer.isView(data)) data = data.toString(); if(data) { - if(options.debug) { - console.log("Message from ",address, ": ", data); - } if(typeof data === 'string') { //pulling this out of receive to check if setId was called let substr = data.substring(0,8); if(substr.includes('{') || substr.includes('[')) { @@ -375,16 +313,9 @@ export class WSSbackend extends Service { if(data.route === 'setId') { this.sockets[address]._id = data.args; - socket.removeEventListener( - 'message', - socketonmessage - ); - + socket.removeEventListener('message',socketonmessage); socket.on('message', (data:any)=> { if(ArrayBuffer.isView(data)) data = data.toString(); - if(options.debug) { - console.log("Message from ",this.sockets[address]._id, ": ", data); - } this.receive(data,socket,this.sockets[address]); if(options.keepState) { this.setState({[address]:data}); @@ -398,27 +329,13 @@ export class WSSbackend extends Service { this.receive(data,socket,this.sockets[address]); if(options.keepState) this.setState({[address]:data}); } - socket.addListener('message',socketonmessage); //add default callback if none specified + socket.on('message',socketonmessage); //add default callback if none specified options.onmessage = socketonmessage; } - - socket.addListener('open',()=>{ - if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(socket,this.sockets[address]); - }); - - socket.addListener('close',(code,reason)=>{ - let obj = this.sockets[address]; - let onclose = obj.onclose; - - delete this.sockets[address]; //delete by default onclose (memory saving) - - if(onclose) onclose(code,reason,socket,obj); - }); - - - socket.on('error',(er)=>{ - if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(er,socket,this.sockets[address]); - }); + socket.on('open',()=>{if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(socket,this.sockets[address]);}); + socket.on('close',(code,reason)=>{ + if(this.sockets[address].onclose) (this.sockets[address] as any).onclose(code,reason,socket,this.sockets[address]);}); + socket.on('error',(er)=>{if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(er,socket,this.sockets[address]);}); let send = (message:any) => { //console.log('sent', message) @@ -439,16 +356,15 @@ export class WSSbackend extends Service { let run = (route:any,args?:any, method?:string):Promise => { return new Promise ((res,rej) => { let callbackId = Math.random(); - let req = {route:'runRequest', args:[{route, args}, this.sockets[address]._id, callbackId]} as any; + let req = {route:'runRequest', args:[{route, args}, address, callbackId]} as any; + //console.log(req) if(method) req.args[0].method = method; let onmessage = (ev)=>{ - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) - data = JSON.parse(data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { + if(typeof ev.data === 'string' && ev.data.indexOf('{') > -1) ev.data = JSON.parse(ev.data); + if(typeof ev.data === 'object') { + if(ev.data.callbackId === callbackId) { socket.removeEventListener('message',onmessage); - res(data.args); //resolve the request with the corresponding message + res(ev.data.args); //resolve the request with the corresponding message } } } @@ -458,11 +374,11 @@ export class WSSbackend extends Service { } let request = (message:ServiceMessage|any, method?:string):Promise => { - return this.request(message,socket, this.sockets[address]._id as string, method); + return this.request(message,socket, address, method); } let subscribe = (route:any, callback?:((res:any)=>void)|string) => { - return this.subscribeToSocket(route, this.sockets[address]._id as string, callback); + return this.subscribeToSocket(route, address, callback); } let unsubscribe = (route:any, sub:number):Promise => { @@ -470,7 +386,7 @@ export class WSSbackend extends Service { } let terminate = () => { - this.terminate(this.sockets[address]._id as string); + this.terminate(address); } this.sockets[address] = { @@ -484,7 +400,6 @@ export class WSSbackend extends Service { unsubscribe, terminate, graph:this, - __node:{tag:address}, ...options } @@ -495,14 +410,7 @@ export class WSSbackend extends Service { message:string | ArrayBufferLike | Blob | ArrayBufferView | Buffer[] | ServiceMessage, ws:WebSocketServer|WebSocket, ) => { - if( - (typeof message === 'object' && - (((message as ServiceMessage)?.route || ((message as ServiceMessage)?.node)) || ( - typeof (message as Blob).arrayBuffer !== 'function' && - typeof (message as ArrayBufferLike).byteLength !== 'number' && - typeof (message as Buffer[])[0]?.byteLength !== 'number' - ))) || typeof message === 'number' - ) message = JSON.stringify(message); + if(typeof message === 'object') message = JSON.stringify(message); if(!ws) { @@ -514,9 +422,9 @@ export class WSSbackend extends Service { }; } if(ws instanceof WebSocketServer) { //broadcast to all clients - ws.clients.forEach((c:WebSocket) => {c.send(message as string)}) + ws.clients.forEach((c:WebSocket) => {c.send(message)}) } - else if(ws instanceof WebSocket) ws.send(message as string); + else if(ws instanceof WebSocket) ws.send(message); } closeWS = (ws:WebSocket|string) => { @@ -542,22 +450,13 @@ export class WSSbackend extends Service { } terminate = (ws:WebSocketServer|WebSocket|string) => { - - let str; if(!ws) { - let served = Object.keys(this.servers); - for(const key in served) { - this.terminate(key); - } - let sockets = Object.keys(this.sockets); - for(const key in sockets) { - this.terminate(key) - } + let served = this.servers[Object.keys(this.servers)[0]]; + if(served) ws = served.wss; //select first websocket server to transmit to all clients } else if(typeof ws === 'string') { - str = ws; for(const k in this.servers) { - if(k.includes(ws) || this.servers[k]._id === ws) { + if(k.includes(ws)) { ws = this.servers[k].wss; for(const key in this.servers[k].clients) { this.closeWS(this.servers[k].clients[key]); @@ -568,25 +467,21 @@ export class WSSbackend extends Service { } if(!ws) { for(const k in this.sockets) { - if(k.includes(ws as string) || this.sockets[k]._id === ws) { + if(k.includes(ws as string)) { ws = this.sockets[k].socket; delete this.sockets[k]; break; } } } - } if(ws instanceof WebSocketServer) { ws.close((er) => {if(er) console.error(er);}); } - else if(ws instanceof WebSocket) { + else if(ws instanceof WebSocket) if(ws.readyState === ws.OPEN) ws.close(); - - if(this.get(str ? str : ws.url)) this.remove(str ? str : ws.url); - } return true; } @@ -620,7 +515,7 @@ export class WSSbackend extends Service { ws:WebSocket|string, callbackId:string|number ) => { //send result back - let res = this.receive(message); + let res = this.receive(message); if(ws) { if(typeof ws === 'string') { for(const key in this.servers) { @@ -633,7 +528,7 @@ export class WSSbackend extends Service { if(s === ws) {ws = this.sockets[s].socket; break;} } } - } + } if(res instanceof Promise) { res.then((v) => { @@ -652,8 +547,7 @@ export class WSSbackend extends Service { return res; } - subscribeSocket = (route:string, socket:WebSocket|string, args?:any[], key?:string, subInput?:boolean) => { - if(this.restrict?.[route]) return undefined; + subscribeSocket = (route:string, socket:WebSocket|string, key?:string, subInput?:boolean) => { if(typeof socket === 'string') { if(this.sockets[socket]) socket = this.sockets[socket].socket; else { @@ -664,7 +558,7 @@ export class WSSbackend extends Service { } } - if(typeof socket === 'object') { + if(typeof socket === 'object') return this.subscribe(route, (res:any) => { //console.log('running request', message, 'for worker', worker, 'callback', callbackId) if((socket as WebSocket).readyState === (socket as WebSocket).OPEN) { @@ -676,13 +570,12 @@ export class WSSbackend extends Service { (socket as WebSocket).send(JSON.stringify({args:res, callbackId:route})); } } - },args,key,subInput); - } + },key,subInput); } - subscribeToSocket = (route:string, socketId:string, callback?:string|((res:any)=>void), args?:any[], key?:string, subInput?:boolean) => { + subscribeToSocket = (route:string, socketId:string, callback?:string|((res:any)=>void), key?:string, subInput?:boolean) => { if(typeof socketId === 'string' && this.sockets[socketId]) { - this.__node.state.subscribeEvent(socketId, (res) => { + this.__node.state.subscribeTrigger(socketId, (res) => { if(res?.callbackId === route) { if(!callback) this.setState({[socketId]:res.args}); else if(typeof callback === 'string') { //just set state @@ -691,26 +584,8 @@ export class WSSbackend extends Service { else callback(res.args); } }) - return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId,args,key,subInput]}); + return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId,key,subInput]}); } } -} - - - - - - - - -function getHoursAndMinutes(date) { - let hours = date.getHours(); - let minutes = date.getMinutes(); - - // Convert the hours and minutes to two digits - hours = hours < 10 ? '0' + hours : hours; - minutes = minutes < 10 ? '0' + minutes : minutes; - - return `${hours}:${minutes}`; } \ No newline at end of file diff --git a/src/core/EventHandler.ts b/src/core/EventHandler.ts deleted file mode 100644 index 1ba81a51..00000000 --- a/src/core/EventHandler.ts +++ /dev/null @@ -1,129 +0,0 @@ -//mini state event handler for arbitrary data event callback handling - -//a graph representing a callstack of nodes which can be arranged arbitrarily with forward and backprop or propagation to wherever -export class EventHandler { - - data={} as {[key:string]:any} - triggers={} as {[key:string]:{sub:number,onchange:Function,[key:string]:any}[]} - ctr = 0; //sub counter, always ensures unique values - - constructor(data?:{[key:string]:any}) { if(typeof data === 'object') this.data = data; } - - setState = (updateObj:{[key:string]:any}) => { - Object.assign(this.data, updateObj); - - let props = Object.getOwnPropertyNames(updateObj) - for (const prop of props) { - this.triggerEvent(prop, this.data[prop]); - } - if(this.triggers[statesubKey]) { - let run = (fn) => { fn(updateObj); } - const l = this.triggers[statesubKey].length; - for (let i = l - 1; i >= 0; i--) { - run(this.triggers[statesubKey][i].onchange); //go in reverse in case a trigger pops - } - } - - return this.data; - } - setValue = (key, value) => { - this.data[key] = value; - this.triggerEvent(key,value); - } - triggerEvent = (key, value) => { - if(this.triggers[key]) { - let fn = (obj) => { obj.onchange(value); }; - const l = this.triggers[key].length; - for (let i = l - 1; i >= 0; i--) { - fn(this.triggers[key][i]); //go in reverse in case a trigger pops - } - } - } - subscribeState = (onchange:(res:any)=>void) => { - return this.subscribeEvent(statesubKey, onchange); - } - unsubscribeState = (sub:number) => { - return this.unsubscribeEvent(statesubKey, sub); - } - subscribeEvent = (key:string,onchange:(res:any)=>void, refObject?:{[key:string]:any}, refKey?:string) => { - if(key) { - if(refObject && refKey && !this.triggers[key]) { - //this acts more like an observer rather than needing to hard copy stuff - Object.defineProperty(this.data,key,{ - get:()=>{ - return refObject[refKey]; - }, - set:(value) => { - refObject[refKey] = value; - }, - enumerable:true, - configurable:true - }); - } - - if(!this.triggers[key]) { - this.triggers[key] = []; - } - - let l = this.ctr; - this.ctr++; - - this.triggers[key].push({sub:l, onchange}); - return l; - } else return undefined; - } - unsubscribeEvent = (key:string,sub?:number) => { - let triggers = this.triggers[key]; - if (triggers){ - if(sub === undefined) { - delete this.triggers[key]; - delete this.data[key]; //garbage collect useless data - } - else { - let idx = undefined; - let obj = triggers.find((o,i)=>{ - if(o.sub===sub) { - idx = i; - return true; - } - }); - - if(obj) triggers.splice(idx,1); - if(Object.keys(triggers).length === 0) { - delete this.triggers[key]; - delete this.data[key]; //garbage collect useless data - } - - if(this.onRemoved) this.onRemoved(obj); - return true; - } - } - } - subscribeEventOnce = (key:string, onchange:(res:any)=>void) => { - let sub; - - let changed = (value) => { - onchange(value); - this.unsubscribeEvent(key, sub); - } - sub = this.subscribeEvent(key,changed); - - return sub; - } - getEvent = (key,sub?) => { - if(typeof sub !== 'number') return this.triggers[key]; - for(const s in this.triggers[key]) { - if(this.triggers[key][s].sub === sub) return this.triggers[key][s]; - } - } - getSnapshot = () => { //shallow copies the current state - const snapshot = {}; - for(const key in this.data) { - snapshot[key] = this.data[key]; //runs getters etc if data not set explicitly in state but passed by reference from a source object - } - } - onRemoved:(trigger:{sub:number, onchange:Function})=>void; -} - -let statesubKey = '*s'; - diff --git a/src/core/Graph.ts b/src/core/Graph.ts deleted file mode 100644 index a9b071ac..00000000 --- a/src/core/Graph.ts +++ /dev/null @@ -1,1526 +0,0 @@ -//graphnodes but we are going to define graph nodes as scopes and graphs as instances of scopes, -// then the execution behaviors will be made plugins to recognize settings on the objects optionally. This is more generic - -import { EventHandler } from "./EventHandler"; - -export const state = new EventHandler(); //default shared global state - - -export type GraphNodeProperties = { - __props?:Function|{[key:string]:any}|GraphNodeProperties|GraphNode, //Proxy objects or from a class constructor function (calls 'new x()') or an object we want to proxy all of the methods on this node. E.g. an html element gains 'this' access through operators and listeners on this node. - __operator?:((...args:any[])=>any)|string, //The 'main' function of the graph node, children will call this function if triggered by a parent. Functions passed as graphnodeproperties become the operator which can set state. - __children?:{[key:string]:any}, //child nodes belonging to this node, e.g. for propagating results - __listeners?:{[key:string]:true|string|((result)=>void)|{__callback:string|((result)=>void)|true, subInput?:boolean,[key:string]:any}}|{[key:string]:((result)=>void)|true|string}, //subscribe by tag to nodes or their specific properties and method outputs - __onconnected?:((node)=>void|((node)=>void)[]), //what happens once the node is created? - __ondisconnected?:((node)=>void|((node)=>void)[]), //what happens when the node is deleted? - __node?:{ //node specific properties, can contain a lot more things - tag?:string, - state?:EventHandler, //by default has a global shared state - [key:string]:any - }, - __args?:any[], //can structure input arguments, include '__result' when generically calling operators for where to pass the original input in in a set of arguments - __callable?:boolean, //we can have the graphnode return itself as a callable function with private properties - [key:string]:any -} - -export type Loader = ( - node:GraphNode, - parent:Graph|GraphNode, - graph:Graph, - roots:any, - properties:GraphNodeProperties, - key:string -)=>void; - -export type Roots = { - [key:string]:any -} //node definitions - -export type GraphOptions = { - roots?:Roots, //node definitions - loaders?:{ - [key:string]:Loader|{ - init?:Loader, - connected?:(node)=>void, - disconnected?:(node)=>void} - }, - state?:EventHandler, - mapGraphs?:false, //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? - [key:string]:any -} - -export type argObject = { - __input?:string|((...args)=>any), __callback:string|((...args)=>any), //interchangeable - __args?:any[], //can use this instead of __output in general. - __output?:string|argObject|((...args)=>any) //another way to pass args from the input/callback results -} - -export type Listener = { - __callback?:string, //prototype callback - __args?:(argObject|Function|string)[], //prototype arguments - sub:number, - node:GraphNode, //owning node (source node) - graph:Graph, //owning graph - source?:string, //source node (owning node) - key?:string, //source key - target?:string, //target node - tkey?:string, //target key - arguments?:Function[] //wrapped arguments, hot swappable - subInput?:boolean, - onchange:Function //internal function called by the event handler, wrapped by graphscript -} - - -//Call node __operators like so: let node = graph.get('abc'); let result = node(input); -export class Callable extends Function { - - __bound:Callable; - __call:((...args:any[])=>any); - [key:string]:any; - - constructor() { - super('return this.__bound.__call.apply(this.__bound, arguments)') - this.__bound = this.bind(this) - return this.__bound; - } - -} - -//this is a scope -export class GraphNode { - - __node:{ - tag:string, - unique:string, - state:EventHandler, - [key:string]:any - } = { //GraphNode-specific properties - tag:`node${Math.floor(Math.random()*1000000000000000)}`, - unique:`${Math.floor(Math.random()*1000000000000000)}`, - state, - // graph: undefined as any, - // localState: undefined as any, - // source:undefined as any// source graph if a graph is passed as properties - } - - __children?:{[key:string]:GraphNode}; - __parent?:Graph|GraphNode; - __operator?; - __listeners?; - __props?; - __args:any[] //can structure input arguments, include '__result' when generically calling operators for where to pass the original input in in a set of arguments - // __onconnected:undefined as any, //function or array of functions - // __ondisconnected:undefined as any, //function or array of functions - [key:string]:any - - //pass GraphNodeProperties, functions, or tags of other nodes - constructor(properties:GraphNodeProperties, parent?:{[key:string]:any}, graph?:Graph) { - //super(); - this.__setProperties(properties,parent,graph); - - // Check if the properties are a function or denote the GraphNode to be callable (but all properties private!!) - if (typeof properties === 'function' || properties?.__callable) { //assuming operator is defined - const callableInstance = new Callable(); - callableInstance.__call = (...args) => this.__operator(...args); - - // Create a proxy to delegate function calls to callableInstance and properties to this - const proxy = new Proxy(callableInstance, { //experimental - get: (target, prop, receiver) => { - if (Reflect.has(this, prop)) { - return Reflect.get(this, prop, receiver); - } - return Reflect.get(target, prop, receiver); - }, - set: (target, prop, value, receiver) => { - if (Reflect.has(this, prop)) { - return Reflect.set(this, prop, value, receiver); - } - return Reflect.set(target, prop, value, receiver); - } - }); - Object.setPrototypeOf(proxy,this); //pass instanceof checks - - //@ts-ignore - return proxy; - } - } - - //slightly more convenient than doing this.__node.graph - get __graph() { - return this.__node?.graph; - } - - set __graph(graph) { - this.__node.graph = graph; - } - - __setProperties = (properties, parent, graph) => { - - let enforceProperties = () => { - let orig = properties; - if(typeof properties === 'function') { - if(isNativeClass(properties)) { //works on custom classes - //console.log(properties); - properties = new properties(); //this is a class that returns a node definition - } else properties = { - __operator:properties, - __node:{ - forward:true, //propagate operator results to children - tag:properties.name - } - }; - } else if (typeof properties === 'string') { - if(graph?.get(properties)) { - properties = graph.get(properties); - } - } - if(!('__node' in properties)) properties.__node = {}; - if(!properties.__node.initial) properties.__node.initial = orig; //original object or function - } - - enforceProperties(); - - if(typeof properties === 'object') { - - let assignState = () => { - if(properties.__node?.state) this.__node.state = properties.__node.state; //make sure we're subscribing to the right state if we're passing a custom one in - else if(graph) { - properties.__node.state = graph.__node.state; //make sure the node has the graph's state - } - } - - let setProps = () => { - if(properties.__props) { //e.g. some generic javascript object or class constructor that we want to proxy. Functions passed here are treated as constructors. E.g. pass an HTML canvas element for the node then set this.width on the node to set the canvas width - if (typeof properties.__props === 'function') properties.__props = new properties.__props(); - if (typeof properties.__props === 'object') { - this.__proxyObject(properties.__props); - } - } - } - - let setTag = () => { - if(!properties.__node.tag) { - if(properties.__operator?.name) - properties.__node.tag = properties.__operator.name; - else - properties.__node.tag = `node${Math.floor(Math.random()*1000000000000000)}`; - } - } - - - let setNode = () => { - if (typeof properties.__node === 'string') { - //copy - if(graph?.get(properties.__node.tag)) { - properties = graph.get(properties.__node.tag); - } else properties.__node = {} - } else if(!properties.__node) properties.__node = {}; - if(graph) { - properties.__node.graph = graph; - } - if(properties instanceof Graph) properties.__node.source = properties; //keep tabs on source graphs passed to make nodes - } - - - let setParent = () => { - //child/branch nodes get their parent tags prepended in their tag - if(!properties.__parent && parent) properties.__parent = parent; - if(parent?.__node && (!(parent instanceof Graph || properties instanceof Graph))) - properties.__node.tag = parent.__node.tag + '.' + properties.__node.tag; //load parents first - if(parent instanceof Graph && properties instanceof Graph) { - if(properties.__node.loaders) Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); //let the parent graph adopt the child graph's loaders - if(parent.__node.mapGraphs) { - //do we still want to register the child graph's nodes on the parent graph with unique tags for navigation? Need to add cleanup in this case - properties.__node.nodes.forEach((n) => {parent.set(properties.__node.tag+'.'+n.__node.tag,n)}); - let ondelete = () => { properties.__node.nodes.forEach((n) => {parent.__node.nodes.delete(properties.__node.tag+'.'+n.__node.tag)}); } - this.__addOndisconnected(ondelete); - } - } - } - - let setOp = () => { - if(typeof properties.default === 'function' && !properties.__operator) { - properties.__operator = properties.default; - } //handle a default export treated as an operator - if(properties.__operator) { - if (typeof properties.__operator === 'string') { - if(graph) { - let n = graph.get(properties.__operator); - if(n) properties.__operator = n.__operator; - if(!properties.__node.tag && (properties.__operator as Function).name) - properties.__node.tag = (properties.__operator as Function).name; - } - } - if(typeof properties.__operator === 'function') - properties.__operator = this.__setOperator(properties.__operator); - if(properties.default) properties.default = properties.__operator; - } - } - - let assignProps = () => { - properties.__node = Object.assign(this.__node,properties.__node); - let keys = Object.getOwnPropertyNames(properties).filter((v)=>{if(!objProps[v]) return true;}); - for(const key of keys) { if(key in properties && key !== 'name') this[key] = properties[key]; } - - } - - let bindCallbacks = () => { - if(this.__onconnected) { - if(typeof this.__onconnected === 'function') { - this.__onconnected = this.__onconnected.bind(this); - } else if (Array.isArray(this.__onconnected)) { - this.__onconnected = this.__onconnected.map((f) => { return f.bind(this); }) - } - if(typeof this.__ondisconnected === 'function') { - this.__ondisconnected = this.__ondisconnected.bind(this); - } else if (Array.isArray(this.__ondisconnected)) { - this.__ondisconnected = this.__ondisconnected.map((f) => { return f.bind(this); }) - } - } - } - - - //specific load order!! - assignState(); - setTag(); - setProps(); - setNode(); - setParent(); - assignProps(); - bindCallbacks(); - setOp(); - - } - } - - //subscribe an output or input with an arbitrary callback - __subscribe = (callback:string|GraphNode|((res)=>void), key?:string, subInput?:boolean, target?:string, tkey?:string, args?:any[], callbackStr?:string) => { - - //console.log('subbing', this.__node.tag, key) - const subscribeToFunction = (k, setTarget = (callback, target?) => (target ? target : callback), triggerCallback=callback as (res: any) => void) => { - - let wrappedArgs; - if(args) { - let wrapped = wrapArgs(triggerCallback, args, this.__node.graph); - triggerCallback = wrapped.__callback; - wrappedArgs = wrapped.__args; - } - let sub = this.__node.state.subscribeEvent(k, triggerCallback, this, key); - - // Add details to trigger - let trigger = this.__node.state.getEvent(k,sub) as any as Listener; - if(!this.__listeners) this.__listeners = {}; - this.__listeners[k] = this.__node.state.triggers[k]; - - - if(!trigger) return sub; - trigger.source = this.__node.tag; //source being subscribed too - if(key) trigger.key = key; //source key being subscribed to - trigger.target = setTarget(callback, target); // target is node subscribing to source - if(tkey) trigger.tkey = tkey; //e.g. function or variable on the target receiving the subscription output - if(subInput) trigger.subInput = subInput; - if(args) { - trigger.arguments = wrappedArgs; //wrapped argument functions, hot swappable - trigger.__args = args; //prototype args - } - if(callbackStr) trigger.__callback = callbackStr; - - trigger.node = this; - trigger.graph = this.__node.graph; - - return sub; - } - - const getCallbackFromGraph = (callback) => { - let fn = this.__node.graph.get(callback); - if(!fn && callback.includes('.')) { - target = callback.substring(0,callback.lastIndexOf('.')); - let n = this.__node.graph.get(callback.substring(0,target)); - tkey = callback.lastIndexOf('.')+1; - if(n && typeof n[key] === 'function') callback = (...args) => { return n[tkey](...args); }; - //console.log(n, fn); - } else if (fn.__operator) { - callback = fn.__operator; - tkey = '__operator'; - } - return callback; - } - - if(key) { - // console.log(key,this.__node.tag, 'callback:', callback); - if(!this.__node.localState || !this.__node.localState[key]) { - this.__addLocalState(this, key); - } - - if(typeof callback === 'string') { - callbackStr = this.__node.tag+'.'+callback; - tkey = callback; - if(target) { - if(this.__node.graph?.get(target)) { - let n = this.__node.graph?.get(target); - if(typeof n[callback] === 'function') { - let fn = n[callback]; - callback = (...inp) => { fn(...inp); }; - } else { - let k = callback; - let setter = (inp) => { - n[k] = inp; //this callback is now a setter for a property on the target node - } - callback = setter; - } - } - } - else if(typeof this[callback] === 'function') { - let fn = this[callback]; - callback = (...inp) => {fn(...inp);}; - } else if(this.__node.graph?.get(callback)) callback = getCallbackFromGraph(callback); - if(typeof callback !== 'function') return undefined; - } - - let sub; - - let k = subInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key; - if(typeof callback === 'function' && !(callback as any)?.__node) - sub = subscribeToFunction(k, (callback, target) => (target ? target : callback), callback as (...res:any)=>void) - else if((callback as GraphNode)?.__node) sub = subscribeToFunction(k, - (callback, target) => (target ? target : (callback as GraphNode).__node.unique), - (...inp:any)=>{ if((callback as any).__operator) (callback as any).__operator(...inp); } - ) - - return sub; - } - else { - - // Get node based on the graph - if(typeof callback === 'string') { - callbackStr = callback; - if(!target) target = callback as string; - if(this.__node.graph.get(callback)) callback = this.__node.graph.get(callback); - tkey = '__operator'; - if(typeof callback !== 'object') return undefined; - } - - let sub; - - let k = subInput ? this.__node.unique+'input' : this.__node.unique; - - if(typeof callback === 'function' && !(callback as any)?.__node) sub = subscribeToFunction(k, (callback, target) => (target ? target : callback), callback as (...res:any)=>void) - else if((callback as GraphNode)?.__node) { - sub = subscribeToFunction(k, - (callback, target) => target ? target : (callback as GraphNode).__node.unique, - (...inp:any)=>{ if((callback as any).__operator) (callback as any).__operator(...inp); } - ); - } - - return sub; - } - } - - //unsub the callback - __unsubscribe = (sub?:number, key?:string, unsubInput?:boolean) => { - - //console.log('unsubbing', this.__node.tag, sub, key) - if(key) { - return this.__node.state.unsubscribeEvent( - unsubInput ? this.__node.unique+'.'+key+'input' : this.__node.unique+'.'+key, - sub - ); - } - else - return this.__node.state.unsubscribeEvent( - unsubInput ? this.__node.unique+'input' : this.__node.unique, sub - ); - } - - __setOperator = (fn:(...args:any[])=>any) => { - fn = fn.bind(this); - if(this.__args && this.__node.graph) { fn = wrapArgs(fn, this.__args, this.__node.graph).__callback; } - let inpstr = `${this.__node.unique}input`; - this.__operator = (...args) => { - if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,args); - let result = fn(...args); - if(this.__node.state.triggers[this.__node.unique]) { //don't set state (i.e. copy the result) if no subscriptions - if(typeof result?.then === 'function') { - result.then((res)=>{ if(res !== undefined) this.__node.state.setValue( this.__node.unique,res ) }).catch(console.error); - } else if(result !== undefined) this.__node.state.setValue(this.__node.unique, result); - } - return result; - } - - if(this.__parent instanceof GraphNode && !this.__subscribedToParent) { //for child nodes - if(this.__parent.__operator) { - let sub = this.__parent.__subscribe(this); - let ondelete = () => { this.__parent?.__unsubscribe(sub); delete this.__subscribedToParent;} - this.__addOndisconnected(ondelete); - this.__subscribedToParent = true; - } - } - - return this.__operator; - } - - __addLocalState = (props?:{[key:string]:any}, key?:string) => { //add easy state functionality to properties on this node using getters/setters or function wrappers - if(!props) return; - if(!this.__node.localState) { - this.__node.localState = {}; - } - const localState = this.__node.localState; - const initState = (props,k) => { - let str = this.__node.unique+'.'+k; - let inpstr = `${str}input`; //for input tracking - let get:()=>any, set:(v)=>void; - let obj, descriptor; - if(typeof props[k] === 'function' && k !== '__operator') { - if(this.__props?.[k]) { - obj = this.__props; - } - else { - obj = localState; - } - - get = () => { - return obj[k]; - } - set = (fn:Function) => { - if(!this.__props?.[k]) fn = fn.bind(this); //make sure function remains bound to node if not for a proxy - obj[k] = (...args) => { - if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,args); - let result = fn(...args); - if(this.__node.state.triggers[str]) { - if(typeof result?.then === 'function') { //assume promise (faster than instanceof) - result.then((res)=>{ this.__node.state.triggerEvent( str, res ) }).catch(console.error); - } else this.__node.state.triggerEvent(str,result); - } - - return result; - } - } - - localState[k] = props[k].bind(this) as Function; - - descriptor = { - get, set, - enumerable: true, - configurable: true - }; - - } else if (k !== '__graph') { - let get:()=>any, set:(v)=>void; - let obj; - if(this.__props?.[k]) { - obj = this.__props; - } else { - obj = localState; - } - - get = () => { - return obj[k]; - }; - - set = (v) => { - //if(this.__node.state.triggers[inpstr]) this.__node.state.setValue(inpstr,v); - obj[k] = v; - if(this.__node.state.triggers[str]) this.__node.state.triggerEvent(str,v); //this will update localState and trigger local key subscriptions - }; - - localState[k] = props[k]; - //console.log(k, localState[k]); - - descriptor = { - get, set, - enumerable: true, - configurable: true - }; - } - - - Object.defineProperty(props, k, descriptor); - - if(typeof this.__node.initial === 'object') { - let dec = Object.getOwnPropertyDescriptor(this.__node.initial,k); - if(dec === undefined || dec?.configurable) { - Object.defineProperty(this.__node.initial, k, descriptor); - } - } - } - - if(key) initState(props,key); - else { - for (let k in props) {initState(props,k);} - } - } - - //we can proxy an original object and function outputs on the node - __proxyObject = (obj) => { - const allProps = getAllProperties(obj); - - for(const k of allProps) { - //if(!(k in this)) { - const descriptor = { - get:()=>{return obj[k]}, - set:(value) => { - obj[k] = value; - }, - enumerable: true, - configurable: true - } - - Object.defineProperty(this, k, descriptor); - - if(typeof this.__node.initial === 'object') { - let dec = Object.getOwnPropertyDescriptor(this.__node.initial,k); - if(dec === undefined || dec?.configurable) { - Object.defineProperty(this.__node.initial, k, descriptor); - } - } - //} - } - } - - __addOnconnected(callback:(node)=>void) { - callback = callback.bind(this); - if(Array.isArray(this.__onconnected)) { this.__onconnected.push(callback); } - else if (typeof this.__onconnected === 'function') { this.__onconnected = [callback,this.__onconnected] } - else this.__onconnected = callback; - } - - __addOndisconnected(callback:(node)=>void) { - callback = callback.bind(this); - if(Array.isArray(this.__ondisconnected)) { this.__ondisconnected.push(callback); } - else if (typeof this.__ondisconnected === 'function') { this.__ondisconnected = [callback,this.__ondisconnected] } - else this.__ondisconnected = callback; - } - - __callConnected(node=this) { - if(typeof this.__onconnected === 'function') { this.__onconnected(this); } - else if (Array.isArray(this.__onconnected)) { - let fn = (o:Function) => { o(this); } - this.__onconnected.forEach(fn) - } - } - - __callDisconnected(node=this) { - if(typeof this.__ondisconnected === 'function') this.__ondisconnected(this); - else if (Array.isArray(this.__ondisconnected)) { - let fn = (o:Function) => {o(this)}; - this.__ondisconnected.forEach(fn); - } - } - -} - -export class Graph { - - [key:string]:any; - - __node:{ - tag:string, - unique:string, - state:EventHandler, - nodes:Map, - roots:{[key:string]:any}, - mapGraphs?:boolean, - [key:string]:any - } = { - tag:`graph${Math.floor(Math.random()*1000000000000000)}`, - unique:`${Math.random()}`, - nodes:new Map(), - state, - roots:{} - // mapGraphs:false //if adding a Graph as a node, do we want to map all the graph's nodes with the parent graph tag denoting it (for uniqueness)? - // roots:undefined as any, - // loaders:undefined as any, - } - - - constructor( - options?:GraphOptions - ) { - this.init(options); - } - - init = (options?:GraphOptions) => { - if(options) { - let cpy = Object.assign({},options); - delete cpy.roots; //prevent overflow - recursivelyAssign(this.__node, cpy); //assign loaders etc - if(options.roots) this.load(options.roots); - } - } - - load = (roots:{[key:string]:any}, overwrite = false) => { - function recursivelyAssignChildren (target, obj, inChildren=true, top=true) { - if(top) { - if(!target) target = {}; - for(const key in obj) { - if(!key.startsWith('__') && obj[key] && typeof obj[key] === 'object') { - //test for node keys - //if(obj[key].__operator || obj[key].__node || obj[key].__props || obj[key].__children || obj[key].__parent) { - target[key] = obj[key]; - if(obj[key]?.__children) { - recursivelyAssignChildren({},obj[key].__children,false,false); - } - //} - } else if(typeof obj[key] === 'function') target[key] = obj[key]; //only copy functions for now - } - recursivelyAssignChildren(target,obj,true,false); - } else { - if(obj?.__children && !inChildren) { - if(obj.__children?.constructor.name === 'Object') { - if(target.__children?.constructor.name === 'Object') - target.__children = recursivelyAssignChildren(target.__children, obj.__children, true, false); - else target.__children = recursivelyAssignChildren({},obj.__children, true, false); - } else { - target.__children = obj.__children; - //if(typeof target[key] === 'function') target[key] = target[key].bind(this); - } - } else if (inChildren) { - for(const key in obj) { - if(!key.startsWith('__') && obj[key] && typeof obj[key] === 'object') { - //test for node keys - //if(obj[key].__operator || obj[key].__node || obj[key].__props || obj[key].__children || obj[key].__parent) { - target[key] = Object.assign({}, obj[key]); - if(obj[key]?.__children) { - target[key].__children = recursivelyAssignChildren({},obj[key].__children,false,false); - } - //} - } else if(typeof obj[key] === 'function') target[key] = obj[key]; //only copy functions for now - } - } - } - - return target; - } - - this.__node.roots = recursivelyAssignChildren(this.__node.roots ? this.__node.roots : {}, roots); - - //console.log('ROOTS',this.__node.roots); - - let cpy = Object.assign({}, roots); - if(cpy.__node) delete cpy.__node; //we can specify __node behaviors on the roots too to specify listeners - - let listeners = this.recursiveSet(cpy,this,undefined,roots,overwrite); - - //make the root a node - if(roots.__node) { - if(!roots.__node.tag) roots.__node._tag = `roots${Math.floor(Math.random()*1000000000000000)}`; - else if (!this.get(roots.__node.tag)) { - let node = new GraphNode(roots,this,this); //blank node essentially for creating listeners - this.set(node.__node.tag,node); - - this.runLoaders(node,this, roots, roots.__node.tag); - if(node.__listeners) { - listeners[node.__node.tag] = node.__listeners; - } //now the roots can specify nodes - } - } else if (roots.__listeners) { - this.setListeners(roots.__listeners) - } - - //now setup event listeners - this.setListeners(listeners); - - return cpy; //should be the node roots - - } - - setLoaders = (loaders:{[key:string]:(node:GraphNode,parent:Graph|GraphNode,graph:Graph,roots:any,props:any,key:string)=>void}, replace?:boolean) => { - if(replace) this.__node.loaders = loaders; - else Object.assign(this.__node.loaders,loaders); - - return this.__node.loaders; - } - - runLoaders = (node, parent, properties, key) => { - for(const l in this.__node.loaders) { - if(typeof this.__node.loaders[l] === 'object') { - if(this.__node.loaders[l].init) this.__node.loaders[l](node, parent, this,this.__node.roots,properties, key); - if(this.__node.loaders[l].connected) node.__addOnconnected(this.__node.loaders[l].connect); - if(this.__node.loaders[l].disconnected) node.__addOndisconnected(this.__node.loaders[l].disconnect); - } else if (typeof this.__node.loaders[l] === 'function') this.__node.loaders[l](node, parent, this, this.__node.roots, properties, key); } //run any passes on the nodes to set things up further - } - - add = (properties:any, parent?:GraphNode|string, overwrite=true):GraphNode => { - - let listeners = {}; //collect listener props declared - if(typeof parent === 'string') parent = this.get(parent); - - let instanced; - if(typeof properties === 'function') { - if(isNativeClass(properties)) { //works on custom classes - if(properties.prototype instanceof GraphNode) { properties = properties.prototype.constructor(properties,parent,this); instanced = true; } //reinstantiate a new node with the old node's props - else properties = new properties(); //this is a class that returns a node definition - } else properties = { __operator:properties, __callable:true }; - } - else if (typeof properties === 'string') { - properties = this.__node.roots[properties]; - } - if(!properties) return; - - if(!instanced) { - let keys = Object.getOwnPropertyNames(properties); //lets us copy e.g. Math - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(properties)); - keys.push(...nonArrowFunctions); - keys = keys.filter(v => !objProps.includes(v) ); - let cpy = {}; - for(const key of keys) { cpy[key] = properties[key]; } //make sure we don't mutate the original object - properties = cpy; - } - - if(!properties.__node) properties.__node = {}; - properties.__node.initial = properties; - - if(typeof properties === 'object' && this.get(properties.__node.tag)) { - if(overwrite) this.remove(properties.__node.tag, true); //clear the previous node and the subscriptions - else return; - } else if(properties.__node.tag && this.get(properties.__node.tag)) return this.get(properties.__node.tag); - - let node; - let root = recursivelyAssign({},properties,2); - if(instanced) node = properties; - else node = new GraphNode(properties, parent as GraphNode, this); - this.set(node.__node.tag,node); - this.runLoaders(node, parent, properties, node.__node.tag); - this.__node.roots[node.__node.tag] = root; //reference the original props by tag in the roots for children - //console.log('old:',properties.__node,'new:',node.__node); - - if(node.__children) { - node.__children = Object.assign({},node.__children); - this.recursiveSet(node.__children, node, listeners,node.__children); - } - - if(node.__listeners) { - listeners[node.__node.tag] = Object.assign({},node.__listeners); - for(const key in node.__listeners) { - let listener = node.__listeners[key]; - if(node[key]) { //subscribe to a key on the node - delete listeners[node.__node.tag][key]; - listeners[node.__node.tag][node.__node.tag+'.'+key] = listener; - } - if (typeof listener === 'string') { - if(node.__children?.[listener]) { - listeners[node.__node.tag][key] = node.__node.tag+'.'+listener; - } else if (parent instanceof GraphNode && (parent.__node.tag === listener || (parent.__node.tag.includes('.') && parent.__node.tag.split('.').pop() === listener))) { - listeners[node.__node.tag][key] = parent.__node.tag; - } - } - - } - } - - //now setup event listeners - this.setListeners(listeners); - - node.__callConnected(); - return node; - - } - - recursiveSet = (originCpy, parent, listeners:any={}, origin, overwrite=false) => { - let keys = Object.getOwnPropertyNames(origin).filter((v) => !objProps.includes(v)); - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter((v) => !objProps.includes(v)); - keys.push(...nonArrowFunctions); //this is weird but it works - - for(const key of keys) { - if(key.includes('__')) continue; - let p = origin[key]; - if(Array.isArray(p)) continue; - let instanced; - if(typeof p === 'function') { - if(isNativeClass(p)) { //works on custom classes - p = new p(); //this is a class that returns a node definition - if(p instanceof GraphNode) { p = p.prototype.constructor(p,parent,this); instanced = true; } //re-instance a new node - } else p = { __operator:p, __callable:true }; - } else if (typeof p === 'string') { - if(this.__node.nodes.get(p)) p = this.__node.nodes.get(p); - else p = this.__node.roots[p]; - } else if (typeof p === 'boolean') { - if(this.__node.nodes.get(key)) p = this.__node.nodes.get(key); - else p = this.__node.roots[key]; - } - - if(p && typeof p === 'object') { - if(!instanced && !(p instanceof GraphNode)) { - let ks = Object.getOwnPropertyNames(p).filter((v) => !objProps.includes(v)); //lets us copy e.g. Math - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter((v) => !objProps.includes(v)); - nonArrowFunctions.splice(nonArrowFunctions.indexOf('constructor'),1); - ks.push(...nonArrowFunctions); - let cpy = {}; - for(const key of ks) { cpy[key] = p[key]; } //make sure we don't mutate the original object - p = cpy; - } - if(!p.__node) p.__node = {}; - if(!p.__node.tag) p.__node.tag = key; - if(!p.__node.initial) p.__node.initial = originCpy[key]; - if(overwrite && this.get(p.__node.tag)) { - this.remove(p.__node.tag, true); //clear the previous node - } - else if(( - ( - this.get(p.__node.tag) && - !(!(parent instanceof Graph) && - parent?.__node) - ) || - ( - parent?.__node && - this.get(parent.__node.tag + '.' + p.__node.tag) - ) - )) continue; //don't duplicate a node we already have in the graph by tag, todo: maybe rethink this a little bit - - let node: GraphNode; - let newnode = false; - let root = recursivelyAssign({},p,2); //preserve an unwrapped prototype, as the initial props will gain the getters/setters of the node if possible - if(instanced || p instanceof GraphNode) { - node = p; - } else { - node = new GraphNode(p, parent as GraphNode, this); - newnode = true; - } - if(!newnode && p instanceof GraphNode && !instanced && parent instanceof GraphNode) { //make sure this node is subscribed to the parent, can use this to subscribe a node multiple times as a child - let sub = this.subscribe(parent.__node.tag, node.__node.tag); - let ondelete = (node) => {this.unsubscribe(parent.__node.tag, sub);} - node.__addOndisconnected(ondelete); //cleanup sub - } else if(node) { //fresh node, run loaders etc. - //console.log(node, instanced, newnode); - this.set(node.__node.tag,node); - this.runLoaders(node, parent, originCpy[key], key); //run any passes on the nodes to set things up further - originCpy[key] = node; //replace child with a graphnode - this.__node.roots[node.__node.tag] = root; //reference the original node props by tag in the root - - if(node.__children) { - node.__children = Object.assign({}, node.__children); - this.recursiveSet(node.__children, node, listeners,node.__children); - } - - if(node.__listeners) { - listeners[node.__node.tag] = Object.assign({},node.__listeners); - for(const key in node.__listeners) { - let listener = node.__listeners[key]; - let k = key; - if(node[key]) { //subscribe to a key on the node - delete listeners[node.__node.tag][key]; - k = node.__node.tag+'.'+key; - listeners[node.__node.tag][k] = listener; - } - if (typeof listener === 'string') { - if(node.__children?.[listener]) { - listeners[node.__node.tag][k] = node.__node.tag+'.'+listener; - } else if (parent instanceof GraphNode && (parent.__node.tag === listener || (parent.__node.tag.includes('.') && parent.__node.tag.split('.').pop() === listener))) { - listeners[node.__node.tag][k] = parent.__node.tag; - } - } - } - } - - node.__callConnected(); - } - } - } - return listeners; - } - - remove = (node:GraphNode|string, clearListeners:boolean=true) => { - - this.unsubscribe(node); - - if(typeof node === 'string') node = this.get(node); - - if(node instanceof GraphNode) { - this.delete(node.__node.tag); - delete this.__node.roots[node.__node.tag]; - - if(clearListeners) { - this.clearListeners(node); - } - - node.__callDisconnected(); - - const recursiveRemove = (t) => { - for(const key in t) { - this.unsubscribe(t[key]); - this.delete(t[key].__node.tag); - delete this.__node.roots[t[key].__node.tag] - this.delete(key); - delete this.__node.roots[key] - - //console.log(key, 'removing child',t[key]); - t[key].__node.tag = t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf('.')+1); - - if(clearListeners) { - this.clearListeners(t[key]); - } - - //console.log(key,t[key].__listeners); - - t[key].__callDisconnected(); - - if(t[key].__children) { - recursiveRemove(t[key].__children); - } - - // console.log('removed!', t[key]) - } - } - - if(node.__children) { - recursiveRemove(node.__children); - } - } - - if((node as GraphNode)?.__node.tag && (node as GraphNode)?.__parent) { - delete (node as GraphNode)?.__parent; - (node as GraphNode).__node.tag = (node as GraphNode).__node.tag.substring((node as GraphNode).__node.tag.indexOf('.')+1); - } - - if((node as GraphNode)?.__node.graph) (node as GraphNode).__node.graph = undefined; - - return node; - } - - run = (node:string|GraphNode, ...args:any[]) => { - - if(typeof node === 'string') { - let nd = this.get(node); - if(!nd && node.includes('.')) { - nd = this.get(node.substring(0,node.lastIndexOf('.'))); - if(typeof nd?.[node.substring(node.lastIndexOf('.')+1)] === 'function') return nd[node.substring(node.lastIndexOf('.')+1)](...args); - } else if(nd?.__operator) return nd.__operator(...args); - } - if((node as GraphNode)?.__operator) { - return (node as GraphNode)?.__operator(...args); - } - } - - -/** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners = (listeners:{[key:string]:{[key:string]:any}}) => { - - /** - * type Listener = { - * source: the source node (if any) - * key: the source key listened to (if any) - * target: the target node (if any), - * tkey: the target method key (if any) - * sub: the number for the subscription in state - * __callback:Function, - * __args:Function[], wrapped argument functions that get iterated over when a trigger is called - * arguments:any[] //the original arguments - * } - */ - - //now setup event listeners - for(const key in listeners) { - let node = this.get(key); - if(typeof listeners[key] === 'object') { - for(const k in listeners[key]) { - let n = this.get(k); - let sub; - if( typeof listeners[key][k] !== 'object' ) - listeners[key][k] = { __callback:listeners[key][k] }; - else if(!listeners[key][k].__callback) { - for(const kk in listeners[key][k]) { - if(typeof listeners[key][k][kk] !== 'object') { - listeners[key][k][kk] = {__callback: listeners[key][k][kk]} - if(node.__operator && - (listeners[key][k][kk].__callback === true || - typeof listeners[key][k][kk].__callback === 'undefined') - ) - listeners[key][k][kk].__callback = node.__operator; - } - let nn = this.get(kk); - - if(!nn) { - let tag = k.substring(0,k.lastIndexOf('.')); - nn = this.get(tag); - if(nn) { - let prop = k.substring(k.lastIndexOf('.')+1); - sub = this.subscribe( - nn, - listeners[key][k][kk].__callback, - listeners[key][k][kk].__args, - prop, - listeners[key][k][kk].subInput, - key //if the key as the target is a node tag, this lets you specify callbacks as keys of that node so e.g. {console:{'Button.onclick':'log'}} - ); - } - } else { - sub = this.subscribe( - nn, - listeners[key][k][kk].__callback, - listeners[key][k][kk].__args, - undefined, - listeners[key][k][kk].subInput, - key - ); - - } - } - } - if('__callback' in listeners[key][k]) { - if(node){ - if(listeners[key][k].__callback === true || typeof listeners[key][k].__callback === 'undefined') listeners[key][k].__callback = node.__operator; - if( typeof listeners[key][k].__callback === 'function') listeners[key][k].__callback = listeners[key][k].__callback.bind(node); - } - if(!n) { - let tag = k.substring(0,k.lastIndexOf('.')); - n = this.get(tag); - if(n) { - sub = this.subscribe( - n, - listeners[key][k].__callback, - listeners[key][k].__args, - k.substring(k.lastIndexOf('.')+1), - listeners[key][k].subInput, - key - ); - - } - } else { - sub = this.subscribe( - n, - listeners[key][k].__callback, - listeners[key][k].__args, - undefined, - listeners[key][k].subInput, - key - ); - - } - } - } - } - } - } - - clearListeners = (node:GraphNode|string, listener?:string) => { - if(typeof node === 'string') node = this.get(node) as GraphNode; - if(node?.__listeners) { - //console.log(node?.__listeners); - for(const key in node.__listeners) { - if(listener && key !== listener) continue; - if(typeof node.__listeners[key]?.sub !== 'number') continue; - let n = this.get(key); - if(!n) { - n = this.get(key.substring(0,key.lastIndexOf('.'))); - //console.log(key.substring(0,key.lastIndexOf('.')),key,n,node.__listeners[key]); - if(n) { - if(typeof node.__listeners[key] === 'object' && !node.__listeners[key]?.__callback) { - for(const k in node.__listeners[key]) { - if(typeof node.__listeners[key][k]?.sub === 'number') { - this.unsubscribe(n,node.__listeners[key][k].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key][k].subInput); - node.__listeners[key][k].sub = undefined; - } - } - } else if(typeof node.__listeners[key]?.sub === 'number') { - this.unsubscribe(n,node.__listeners[key].sub, key.substring(key.lastIndexOf('.')+1), node.__listeners[key].subInput); - node.__listeners[key].sub = undefined; - } - } - } else { - if(typeof !node.__listeners[key]?.__callback === 'number') { - for(const k in node.__listeners[key]) { - if(node.__listeners[key][k]?.sub) { - this.unsubscribe(n,node.__listeners[key][k].sub, undefined, node.__listeners[key][k].subInput); - node.__listeners[key][k].sub = undefined; - } - } - } else if(typeof node.__listeners[key]?.sub === 'number') { - this.unsubscribe(n,node.__listeners[key].sub, undefined, node.__listeners[key].subInput); - node.__listeners[key].sub = undefined; - } - } - } - } - } - - get = (tag:string) => { return this.__node.nodes.get(tag); }; - getByUnique = (unique:string) => { return Array.from(this.__node.nodes.values()).find((node) => { if(node.__node.unique === unique) return true; })} //just in case we want to source a node by state keys - set = (tag:string,node:GraphNode) => { return this.__node.nodes.set(tag, node); }; - delete = (tag:string) => { return this.__node.nodes.delete(tag); } - list = () => { return Array.from(this.__node.nodes.keys()); } //list loaded nodes - getListener = (nodeTag:string,key?:string,sub?:number) => { - let node = this.get(nodeTag); - if(node) { - let k = node.__node.unique; - if(key) { k += '.'+key } - return this.__node.state.getEvent(k,sub) as any as Listener; - } - } - - getProps = (node:GraphNode|string, getInitial?:boolean) => { - if(typeof node === 'string') node = this.get(node); - if(node instanceof GraphNode) { - let cpy; - if(getInitial) cpy = Object.assign({}, this.__node.roots[node.__node.tag]); - else { - cpy = Object.assign({},node) as any; - //remove graphnode methods to return the arbitrary props - for(const key in cpy) { - if(key.includes('__')) delete cpy[key]; //remove node methods - } - } - } - } - - subscribe = ( - nodeEvent:GraphNode|string, - onEvent:string|GraphNode|((...res:any)=>void), - args?:any[], - key?:string|undefined, - subInput?:boolean, - target?:string|GraphNode, - tkey?:string - ) => { - - let nd = nodeEvent; - if(typeof nodeEvent === 'string') { - nd = this.get(nodeEvent); - if(!nd && nodeEvent.includes('.')) { - nd = this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf('.'))) - key = nodeEvent.substring(nodeEvent.lastIndexOf('.')+1); - } - } - - if(target instanceof GraphNode) target = target.__node.tag; - - let callbackStr; - if(typeof onEvent === 'string') { - //console.log(node, callback, this.__node.nodes.keys()); - callbackStr = onEvent; - let setOnEventFromString = (onEvent:any) => { - if(this.get(onEvent)?.__operator) { - let node = this.get(onEvent); - target = onEvent; - onEvent = function(...inp) { return node.__operator(...inp); }; - } else if(onEvent.includes('.')) { - target = onEvent.substring(0,onEvent.lastIndexOf('.')); - let n = this.get(target as string); - let k = onEvent.substring(onEvent.lastIndexOf('.')+1); - tkey = k; - if(typeof n[k] === 'function') { - if(n[k] instanceof GraphNode) onEvent = n[k]; - else onEvent = function(...inp) { return n[k](...inp); }; - } else { - onEvent = function(inp) { n[k] = inp; return n[k]; }; //setter - } - //console.log(n, fn); - } - return onEvent; - } - - if(target) { - let node = this.get(target); - if(typeof node?.[onEvent] === 'function') { - tkey = onEvent; - onEvent = function(...inp) { return node[key](...inp)}; - } else if(node?.[key]) { - tkey = key; - if(node[key] instanceof GraphNode) onEvent = node[key]; - else onEvent = function(inp) { node[key] = inp; return node[key]; } //setter - } else { - onEvent = setOnEventFromString(onEvent); - } - } else { - onEvent = setOnEventFromString(onEvent); - } - } - - let sub:number; - - //TODO: clean up all this samey stuff - - if(nd instanceof GraphNode) { - const doSub = () => { - sub = (nd as GraphNode).__subscribe(onEvent, key, subInput, target as string, tkey, args, callbackStr); - - let ondelete = () => { - if(sub !== undefined) (nd as GraphNode).__unsubscribe(sub, key, subInput); - sub = undefined; - } - - (nd as GraphNode).__addOndisconnected(()=>{ - ondelete(); - (nd as GraphNode).__addOnconnected(() => { //need to update the listener object on the listening node - if(sub === undefined && (nd as GraphNode).__node.graph.__node.tag === this.__node.tag) doSub(); - - //console.log(key,bound,this.get(target as string).__listeners[bound]); - }) - }); - - if(typeof onEvent === 'string' && this.get(onEvent)) onEvent = this.get(onEvent); - if(onEvent instanceof GraphNode) { - onEvent.__addOndisconnected(() => { - ondelete(); - }); - } - } - - doSub(); - - } else if (typeof nodeEvent === 'string') { - let node = this.get(nodeEvent) as GraphNode; - if(node) { - if(onEvent instanceof GraphNode && onEvent.__operator) { - const doSub = () => { - sub = node.__subscribe((onEvent as GraphNode).__operator, key, subInput, target as string, tkey, args, callbackStr); - - let ondelete = () => { - if(sub !== undefined) node.__unsubscribe(sub, key, subInput); - } - - node.__addOndisconnected(()=>{ - ondelete(); - (node as GraphNode).__addOnconnected(() => { //if reconnected - if(sub === undefined && node.__node.graph.__node.tag === this.__node.tag) doSub(); - }); - }); - - (onEvent as GraphNode).__addOndisconnected(ondelete); - } - - doSub(); - } - else if (typeof onEvent === 'function' || typeof onEvent === 'string') { - const doSub = () => { - sub = node.__subscribe(onEvent, key, subInput, target as string, tkey, args, callbackStr); - - let ondelete = () => { - if(sub !== undefined) node.__unsubscribe(sub, key, subInput); - sub = undefined; - } - - node.__addOndisconnected(()=>{ - ondelete(); - //console.log('unsubscribed', key) - (node as GraphNode).__addOnconnected(() => { //if reconnected - if(sub === undefined && node.__node.graph.__node.tag === this.__node.tag) doSub(); - }); - }); - - if(typeof onEvent === 'string' && this.get(onEvent)) this.get(onEvent).__addOndisconnected(ondelete); - - } - - doSub(); - } - } else { - if(typeof onEvent === 'string') onEvent = this.__node.nodes.get(onEvent).__operator; - if(typeof onEvent === 'function' && !(onEvent as any)?.__node) sub = this.__node.state.subscribeEvent(nodeEvent, onEvent as (...res:any)=>void); - } - } - return sub; - } - - unsubscribe = ( node:GraphNode|string, sub?:number, key?:string, subInput?:boolean) => { - - if(node instanceof GraphNode) { - return node.__unsubscribe(sub,key,subInput); - } - else return this.get(node)?.__unsubscribe(sub,key,subInput); - } - - setState = (update:{[key:string]:any}) => { - this.__node.state.setState(update); - } - -} - - -function recursivelyAssign (target,obj, maxDepth=Infinity,curDepth=0) { - for(const key in obj) { - if(obj[key]?.constructor.name === 'Object' && curDepth < maxDepth) { - curDepth++; - if(target[key]?.constructor.name === 'Object') - recursivelyAssign(target[key], obj[key], maxDepth, curDepth); - else target[key] = recursivelyAssign({},obj[key],maxDepth, curDepth); - } else { - target[key] = obj[key]; - //if(typeof target[key] === 'function') target[key] = target[key].bind(this); - } - } - - return target; -} - - -export function getAllProperties(obj){ //https://stackoverflow.com/questions/8024149/is-it-possible-to-get-the-non-enumerable-inherited-property-names-of-an-object - var allProps = [] as any[], curr = obj - do{ - var props = Object.getOwnPropertyNames(curr); - let fn = function(prop){ - if (allProps.indexOf(prop) === -1) - allProps.push(prop) - } - props.forEach(fn) - } while(curr = Object.getPrototypeOf(curr)) - return allProps; -} - -export function instanceObject(obj) { - let props = getAllProperties(obj); //e.g. Math - let instance = {} as any; - for(const key of props) { - instance[key] = obj[key]; - } - - return instance; - //simply copies methods, nested objects will not be instanced to limit recursion, unless someone wants to add circular reference detection >___> ... <___< -} - -export function isNativeClass (thing: any) { - return isFunction(thing) === 'class' -} - -export function isFunction(x: any) { - const res = typeof x === 'function' - ? x.prototype - ? Object.getOwnPropertyDescriptor(x, 'prototype')?.writable - ? 'function' - : 'class' - : x.constructor.name === 'AsyncFunction' - ? 'async' - : 'arrow' - : ''; - - return res -} - -// export default Graph - -//we can provide an argument list to structure inputs into a function from a set of getters for other node properties and functions etc. -//e.g. argOrder = ['__output','nodeA.x','nodeB.z'] - - -export let getCallbackFromString = (a, graph) => { - if(graph.get(a)?.__operator) { - let node = graph.get(a); - return (...inp) => { node.__operator(...inp); }; - } else if(a.includes('.')) { - let split = a.split('.'); - let popped = split.pop() as any; - let joined = split.join('.'); - let node = graph.get(joined); - if(typeof graph.get(joined)?.[popped] === 'function') { - return (...inp) => { return node[popped](...inp); }; - } else return () => { return node[popped]; }; - } else if (graph.get(a)) { //return the node itself (pass by reference :D) - let node = graph.get(a); - return () => { return node; }; - } else { - let arg = a; - return () => { return arg; }; - } -} - -export const wrapArgs = (callback,argOrder,graph) => { - let args = [] as any[]; - //set up getters - - - let forArg = (a,i) => { - if(a === '__output' || a === '__input' || a === '__callback') { - args[i] = {__callback:(inp) => { return inp; }, __args:undefined, idx:i}; - } else if(typeof a === 'string') { - args[i] = {__callback:getCallbackFromString(a, graph), __args:undefined, idx:i}; - } else if (typeof a === 'function') { - let fn = a; - args[i] = {__callback:(...inp) => { return fn(...inp); }, __args:undefined, idx:i} - } else if (typeof a === 'object' && (a.__input || a.__callback)) { - //wrap i/o functions and get methods from nodes, - // recursively set arguments and the last nested - // input will resolve a value - function recursivelyCreateCallback (c:argObject) { - let input = c.__input ? c.__input : c.__callback as any; - if(typeof c.__input === 'string') { - input = {__callback:getCallbackFromString(c.__input, graph), __args:undefined, idx:i}; - //console.log('input',input); - } - if(c.__args) { - let wrapped = wrapArgs(input, c.__args, graph); - input = {__callback:wrapped.__callback, __args:wrapped.__args, idx:i}; - } else { - input = {__callback:input, __args:undefined, idx:i}; - } - if(c.__output) { - let output = c.__output as any; - if(typeof c.__output === 'string') { - output = {__callback:getCallbackFromString(output, graph), __args:undefined, idx:i}; - } else if (typeof a.__output === 'object') { - output = recursivelyCreateCallback(output as argObject); - } - if(typeof output?.__callback === 'function') { - let fn = input.__callback; - let callback = output.__callback; - input = {__callback:(...inp) => { return (callback as Function)((fn as Function)(...inp));}, __args:output.__args, idx:i} - } - } - return input; - } - args[i] = recursivelyCreateCallback(a); - } else { - let arg = a; - args[i] = {__callback:() => { return arg; }, __args: undefined, idx:i}; - } - } - - argOrder.forEach(forArg); - - if(typeof callback === 'string') callback = {__callback:getCallbackFromString(callback,graph), __args:undefined}; - - let fn = typeof callback === 'function' ? callback : callback.__callback; - callback = function (...inp) { - let mapArg = (arg) => { - return arg.__callback(...inp); - }; - const result = fn(...args.map(mapArg)); - return result; - } - - return {__callback:callback, __args:args}; //args enable hot-swapping nested function calls - -} - -let objProps = Object.getOwnPropertyNames(Object.getPrototypeOf({})); - - - - - -// class AnotherCallable extends Callable { -// constructor() { -// super() -// this.person = 'Dean' -// } - -// suffix(arg) { -// return `${this.person} ${arg || ''}` -// } - -// _call(arg) { -// return `${this.person} ${arg || ''}` -// } -// } - - -// var obj1 = new AnotherCallable() - -// // Method and prop access is maintained. -// console.log('Method and prop access is maintained:') -// console.log(obj1.person, obj1.suffix('Venture'), obj1('Venture')) - -// // Inheritance is correctly maintained. -// console.log('\nInheritance is maintained:') -// console.log(obj1 instanceof Function) // true -// console.log(obj1 instanceof Callable) // true -// console.log(obj1 instanceof AnotherCallable) // true - \ No newline at end of file diff --git a/src/extras/README.md b/src/extras/README.md deleted file mode 100644 index 4dc34cc1..00000000 --- a/src/extras/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Keep the bloatware here so it's out of the main NPM dist - -TODO: We still need to break up the dists so the NPM all doesn't have the same files - -Also need to fix types dist \ No newline at end of file diff --git a/src/extras/____package.json b/src/extras/____package.json deleted file mode 100644 index 7de86a76..00000000 --- a/src/extras/____package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "graphscript-services-node", - "version": "0.3.2", - "description": "Extra services for graphscript.", - "main": "dist/index.services.node.js", - "types": "dist/src/extras/index.services.d.ts", - "scripts": { - "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", - "dependencies": { - "brainsatplay-math": "~0.1.0", - "browserfs": "~1.4.3", - "gpujsutils": "~1.0.15", - "web-worker": "~1.2.0", - "webgl-plot-utils": "~0.4.2" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - }, - "devDependencies": { - "@types/node": "~18.7.15" - } -} diff --git a/src/extras/algorithms/beat_detect.ts b/src/extras/algorithms/beat_detect.ts deleted file mode 100644 index 67280e8b..00000000 --- a/src/extras/algorithms/beat_detect.ts +++ /dev/null @@ -1,232 +0,0 @@ -//AlgorithmContext implementation for a basic low-pass peak finding algorithm with some basic error correction -import { Math2 } from 'brainsatplay-math'; -import { Biquad } from './util/BiquadFilters'; -import { GraphNodeProperties } from '../../core/Graph'; - -export const beat_detect = { - refdata:[] as any, - lowpass:undefined, - smoothed:[] as any, - //dsmoothed:[] as any, //slope - timestamp:[] as any, - peaks:[] as any, - valleys:[] as any, - peak_distances:[] as any, - valley_distances:[] as any, - beats:[] as any, - lastPeak:0, - lastValley:0, - sps:100, //set the sample rate, e.g. 100 - maxFreq:4, //the max frequency of peaks we want to detect, we will create a moving average and peak finding interval based on this and the sample rate. //e.g. 4hz for heart rate, or 1/3rd hz for breathing - limit:10, //limit number of last-values stored on the peak/valley/beat arrays to save memory, can just collect externally when a beat is returned - __onconnected:function() { - if(!this.lowpass) { //init lowpass filter with up to date sample rate - let freq = this.maxFreq; - if(!freq) freq = 1; - if(freq > 1) freq *= 0.5; //helps smooth more on faster sine waves, for low freqs this starts to be too smooth - - //lowpass filter constraints - this.lowpass = new Biquad('lowpass', this.maxFreq, this.sps); - - this.peakFinderWindow = Math.floor(this.sps/this.maxFreq) - if(this.peakFinderWindow%2 === 0) this.peakFinderWindow+=1; - if(this.peakFinderWindow < 5) this.peakFinderWindow = 5; - this.midpoint = Math.round(this.peakFinderWindow*.5); - - } - }, - __operator:function( - data:{ - //general use data key - raw?:number|number[], - - //pulse ox or fnirs data - red?:number|number[], //could be any LED really but we are using red and IR predominantly - ir?:number|number[], - heg?:number|number[], //e.g. the Peanut only gives us the HEG in a usable way - - //used for frequency finding - timestamp?:number|number[] - } - ){ - - if(!('red' in data) && !('heg' in data) && !('raw' in data)) return undefined; //invalid data - - let refdata = data.red ? data.red : data.heg? data.heg : data.raw; - - if(!('timestamp' in data)) { //generate timestamps if none, assuming latest data is at time of the ondata callback - if(Array.isArray(refdata)) { //assume timestamp - let now = Date.now(); - let len; - if(refdata) len = (refdata as number[]).length; - let toInterp = [now - (refdata as number[]).length*this.sps*1000, now]; - data.timestamp = Math2.upsample(toInterp,(refdata as number[]).length); - } else { - data.timestamp = Date.now(); - } - } - - let pass = (amplitude, timestamp) => { - if(amplitude) { - this.refdata.push(amplitude); - } - this.timestamp.push(timestamp); - - let beat; - - if(this.refdata.length > this.peakFinderWindow) { //we only need to store enough data in a buffer to run the algorithm (to limit buffer overflow) - this.refdata.shift(); - this.timestamp.shift(); - } - - - this.smoothed.push( - this.lowpass.applyFilter(this.refdata[this.refdata.length - 1]) - ); - - if(this.smoothed.length > this.peakFinderWindow) { - this.smoothed.shift(); - } - - - if(this.smoothed.length === this.peakFinderWindow) { - // context.dsmoothed.push( - // ( context.refdata[context.refdata.length-1] - - // context.refdata[context.refdata.length-2] - // ) / context.timestamp[context.timestamp[context.timestamp.length-1]] - // ); - - //context.smoothed.indexOf(Math.max(...context.smoothed)) === context.midpoint - if(Math2.isExtrema(this.smoothed,'valley')) { - this.valleys.push({ - value:this.smoothed[this.smoothed.length - this.midpoint ? this.midpoint : 1], - timestamp:this.timestamp[this.timestamp.length - this.midpoint ? this.midpoint : 1] - }); - } else if (Math2.isExtrema(this.smoothed,'peak')) { - this.peaks.push({ - value:this.smoothed[this.smoothed.length - this.midpoint ? this.midpoint : 1], - timestamp:this.timestamp[this.timestamp.length - this.midpoint ? this.midpoint : 1] - }); - } - - - if(this.valleys.length > 2 && this.peaks.length > 2) { - - //if we have 3+ peaks or 3+ valleys in front of the previous peak or valley, we need to shave them off as we are looking for a sine wave (1 peak 1 valley). - if(this.valleys[this.valleys.length-1].timestamp < this.peaks[this.peaks.length - 2].timestamp) - this.peaks.splice(this.peaks.length-1); - if(this.peaks[this.peaks.length-1].timestamp < this.valleys[this.valleys.length - 2].timestamp) - this.valleys.splice(this.valleys.length-1); - - this.valley_distances.push({ - distance:this.valleys[this.valleys.length - 1].timestamp - this.valleys[this.valleys.length - 2].timestamp, - timestamp:this.valleys[this.valleys.length - 1].timestamp, - peak0:this.valleys[this.valleys.length - 1].value, - peak1:this.valleys[this.valleys.length - 2].value - }); - - this.peak_distances.push({ - distance:this.peaks[this.peaks.length - 1].timestamp - this.peaks[this.peaks.length - 2].timestamp, - timestamp:this.peaks[this.peaks.length - 1].timestamp, - peak0:this.peaks[this.peaks.length - 1].value, - peak1:this.peaks[this.peaks.length - 2].value - }); - - if(this.peak_distances.length > 1 && this.valley_distances.length > 1) { - if(this.lastPeak < this.peaks[this.peaks.length-1].timestamp && this.lastValley < this.peaks[this.peaks.length-1].timestamp) { - if(this.valley_distances[this.valley_distances.length -1].timestamp > this.peak_distances[this.peak_distances.length-1].timestamp) { - let bpm, change = 0; - if(this.beats.length < 1) { - bpm = 60/(0.0005 * (this.peak_distances[this.peak_distances.length-1].distance + - this.valley_distances[this.valley_distances.length-1].distance)); - - } else if (this.beats[this.beats.length-1].timestamp !== this.peak_distances[this.peak_distances.length-1].timestamp) { - bpm = 60/(0.0005*(this.peak_distances[this.peak_distances.length-1].dt + this.valley_distances[this.valley_distances.length-1].dt)); - change = Math.abs(bpm - this.beats[this.beats.length - 1].bpm); - } - - beat = { - timestamp:this.peak_distances[this.peak_distances.length - 1].timestamp, - change, - bpm, - height0:this.peak_distances[this.peak_distances.length-1].peak0 - - this.valley_distances[this.valley_distances.length-1].peak0, - height1:this.peak_distances[this.peak_distances.length-1].peak1 - - this.valley_distances[this.valley_distances.length-1].peak1 - }; - - this.beats.push(beat); - - this.lastPeak = this.peaks[this.peaks.length-1].timestamp; - this.lastValley = this.peaks[this.peaks.length-1].timestamp; - } else { - let bpm, change = 0; - if(this.beats.length < 2) { - bpm = 60/(0.0005*(this.peak_distances[this.peak_distances.length-2].distance + this.valley_distances[this.valley_distances.length-2].distance)); //(averaged peak + valley distance (msec)) * msec/sec * 60sec/min - } else if(this.beats[this.beats.length-1].timestamp !== this.peak_distances[this.peak_distances.length-2].timestamp) { - bpm = 60/(0.0005*(this.peak_distances[this.peak_distances.length-2].distance + this.valley_distances[this.valley_distances.length-2].distance)); - change = Math.abs(bpm-this.beats[this.beats.length-2].bpm); - } - - beat = { - timestamp:this.peak_distances[this.peak_distances.length-2].timestamp, - change, - bpm, - height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0, - height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1 - }; - if(Array.isArray(beat.timestamp)) beat.timestamp = beat.timestamp[0]; //some kind of bug - - this.beats.push(beat); - - this.lastPeak = this.peaks[this.peaks.length-1].timestamp; - this.lastValley = this.peaks[this.peaks.length-1].timestamp; - } - } - } - - //limits memory usage - if(this.peaks.length > this.limit) { this.peaks.shift(); } - if(this.valleys.length > this.limit) { this.valleys.shift(); } - if(this.peak_distances.length > this.limit) { this.peak_distances.shift(); } - if(this.valley_distances.length > this.limit) { this.valley_distances.shift(); } - if(this.beats.length > this.limit) { this.beats.shift(); } - - } - } - - return beat; - } - - //console.log(context); - - if(data.red) { - if(('ir' in data) && !Array.isArray(data.red)) return pass((data.red as number)+(data.ir as number),data.timestamp); - - let result; - if(data.ir) result = (data.red as number[]).map((v,i) => { - return pass(v+(data as any).ir[i],(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - else result = (data.red as number[]).map((v,i) => { - return pass(v,(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - - return result; //will return an array, defined results will be - - } else if (data.raw) { - if(!Array.isArray(data.raw)) return pass(data.raw,data.timestamp); - let result = data.raw.map((v,i) => { - return pass(v,(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - return result; //will return an array - } else if (Array.isArray(data.heg)) { - if(!Array.isArray(data.heg)) return pass(data.heg,data.timestamp); - let result = data.heg.map((v,i) => { - return pass(v,(data.timestamp as number[])[i]); - }).filter(v => {if(v) return true;}); - return result; //will return an array - - } - //returns a beat when one is detected with the latest data passed in, else returns undefined - } -} as GraphNodeProperties; \ No newline at end of file diff --git a/src/extras/algorithms/blink.ts b/src/extras/algorithms/blink.ts deleted file mode 100644 index bb4d55fc..00000000 --- a/src/extras/algorithms/blink.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -import { Biquad } from './util/BiquadFilters'; -import { Math2 } from 'brainsatplay-math'; - - -export const blink_detect = { - sps:250, - intervals:{}, - watch:['0'], - tolerance:0.2, //e.g. mV - __onconnected:(node) => { - node.watch.forEach((ch) => node.intervals[ch] = { - lowpass:new Biquad('lowpass',20,node.sps), - filtered:[] as number[], - averaged:[] as number[] - }) - }, - __operator:function(data:{ - [key:string]:number|number[] - }) { - let checkCt = 5; - let averageCt = 50; - - let found = {}; - let passed = false; - - - let pass = (key,n) => { - let next = this.intervals[key].lowpass.applyFilter(n) - this.intervals[key].filtered.push(next); - this.intervals[key].averaged.push(next); - if(this.intervals[key].filtered.length > checkCt) { - if(this.intervals[key].averaged.length > averageCt) { - this.intervals[key].averaged.splice(0,checkCt); - let mean = Math2.mean(this.intervals[key].averaged); - if(Math.abs(Math.min(...this.intervals[key].filtered)) > Math.abs(mean) + this.tolerance) { - this.intervals[key].filtered.length = 0; //reset - passed = true; - found[key] = true; - } - } else - this.intervals[key].filtered.shift(); - } - } - - - for(const key in this.intervals) { - if(data[key]) { - if(Array.isArray(data[key])) { - (data[key] as any).forEach((n) => { - pass(key,n); - }); - } else if(typeof data[key] === 'number') pass(key,data[key]); - } - } - - if(passed) return found; - - } -} as GraphNodeProperties \ No newline at end of file diff --git a/src/extras/algorithms/buffering.ts b/src/extras/algorithms/buffering.ts deleted file mode 100644 index 504944a1..00000000 --- a/src/extras/algorithms/buffering.ts +++ /dev/null @@ -1,33 +0,0 @@ -//we need to buffer before doing bulk blocking operations on separate threads sometimes (ffts in our case) so we are splitting this into 2 algos - -import { GraphNodeProperties } from '../../core/Graph'; -import { ByteParser } from './util/ByteParser'; - - -export const circularBuffer2d:GraphNodeProperties = { - bufferSize:250, //e.g. sps * nsec of data to buffer - watch:['0','1','2','3'], - data:{}, - blocking:false, - - __onconnected:function (node) { - for(const key in node.watch) { - node.data[key] = new Array(node.bufferSize).fill(0); - } - }, - __operator:function (data) { - - let buffer2d = [] as number[][]; - - this.watch.forEach((key) => { - if(data[key]) { - ByteParser.circularBuffer(this.data[key], data[key]) - buffer2d.push(this.data[key]) - } - }); - - //console.log('buffered', buffer2d) - - return buffer2d; - } -} \ No newline at end of file diff --git a/src/extras/algorithms/rms.ts b/src/extras/algorithms/rms.ts deleted file mode 100644 index bbe26d21..00000000 --- a/src/extras/algorithms/rms.ts +++ /dev/null @@ -1,44 +0,0 @@ -//root mean square doer thinger - -import { GraphNodeProperties } from "../../core/Graph"; -import { ByteParser } from "./util/ByteParser"; - -export const rms:GraphNodeProperties = { - sps:250, //sample rate of data - nSec:1, //number of seconds of data to buffer - watch:['0','1','2','3'], - data:{}, - rms:{}, - //__onconnected:(node) => { }, - __operator:function (data) { - - this.watch.forEach((key) => { - if(data[key]) { - if(!this.data[key]) { - if(Array.isArray(data[key])) { - this.data[key] = new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0]); - } else this.data[key] = new Array(Math.floor(this.sps*this.nSec)).fill(data[key]); - } - ByteParser.circularBuffer(this.data[key],data[key]); - } - }); - - if(data.timestamp) { - if(Array.isArray(data.timestamp)) { - this.rms.timestamp = data.timestamp[data.timestamp.length - 1]; - } else this.rms.timestamp = data.timestamp; - } else this.rms.timestamp = Date.now(); - - //console.log(ctx.rms,ctx.data); - - return new Promise(async res => { - await Promise.all(this.watch.map(async (key) => { - if(this.data[key]) this.rms[key] = Math.sqrt(Math.abs((this.data[key] as number[]).reduce((p,v,i) => p + v*v )/this.data[key].length)); //root mean square sum - else delete this.rms[key]; - })) - - res(this.rms); - }) - - } -} \ No newline at end of file diff --git a/src/extras/dist/Worker.js b/src/extras/dist/Worker.js deleted file mode 100644 index 2de70544..00000000 --- a/src/extras/dist/Worker.js +++ /dev/null @@ -1 +0,0 @@ -(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browser=__commonJS({"../../node_modules/web-worker/cjs/browser.js"(exports,module){module.exports=Worker}});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers["__state__"])this.triggers["__state__"].forEach(fn=>{fn(updateObj)});return this.data};this.setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};this.triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>obj.onchange(value);this.triggers[key].forEach(fn)}};this.subscribeState=onchange=>{return this.subscribeEvent("__state__",onchange)};this.unsubscribeState=sub=>{return this.unsubscribeEvent("__state__",sub)};this.subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let biggest=0;for(const trigger of this.triggers[key]){if(trigger.sub>biggest)biggest=trigger.sub}let l=biggest+1;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub){delete this.triggers[key];delete this.data[key]}else{let sub2=void 0;let obj=triggers.find((o,i2)=>{if(o.sub===sub2){sub2=i2;return true}});if(obj)triggers.splice(sub2,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed)};this.getEvent=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};this.getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};this.__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state};let setProps2=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys2=Object.getOwnPropertyNames(properties);for(const key of keys2){this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps2();setNode();setParent();assignProps();bindCallbacks();setOp()}};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))subscribeToGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}};this.__unsubscribe=(sub,key,unsubInput)=>{if(key)return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub);else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph)}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;if(typeof props2[k]==="function"&&k!=="__operator"){let fn=props2[k].bind(this);props2[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}}else{let get,set;if(this.__props?.[k]){get=()=>{return this.__props[k]};set=v=>{this.__props[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)}}else{localState[k]=props2[k];get=()=>{return localState[k]};set=v=>{localState[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)}}const descriptor={get,set,enumerable:true,configurable:true};Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};this.__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){if(typeof obj[k]==="function"){this[k]=(...args)=>{return obj[k](...args)}}else{const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}}};this.__setProperties(properties,parent,graph)}__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};this.init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};this.load=roots=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(target)Object.assign(target,obj);else target=Object.assign({},obj);recursivelyAssignChildren(target,obj,true,false)}if(obj.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){target[key]=Object.assign({},obj[key]);if(obj[key].__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};this.add=(properties,parent)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys2=Object.getOwnPropertyNames(properties);let cpy={};for(const key of keys2){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=properties;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent,listeners={},origin)=>{let keys2=Object.getOwnPropertyNames(origin);for(const key of keys2){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let keys3=Object.getOwnPropertyNames(p);let cpy={};for(const key2 of keys3){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(!(parent instanceof Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else{this.set(node.__node.tag,node);this.runLoaders(node,parent,t[key],key);t[key]=node;this.__node.roots[node.__node.tag]=p;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}console.log(key,t[key].__listeners);t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined")listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k].__args,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if("__callback"in listeners[key][k]){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState);node.__listeners[key].sub=void 0}}}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};this.subscribe=(nodeEvent,onEvent,args,key,subInput,target,bound)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}let sub;if(target instanceof GraphNode)target=target.__node.tag;if(typeof onEvent==="string"){let key2=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){let n=this.get(onEvent2.substring(0,onEvent2.lastIndexOf(".")));let key3=onEvent2.substring(onEvent2.lastIndexOf(".")+1);if(typeof n[key3]==="function"){if(n[key3]instanceof GraphNode)onEvent2=n[key3];else onEvent2=function(...inp){return n[key3](...inp)}}else{onEvent2=function(inp){n[key3]=inp;return n[key3]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){onEvent=function(...inp){return node[key2](...inp)}}else if(node[key2]){if(node[key2]instanceof GraphNode)onEvent=node[key2];else onEvent=function(inp){node[key2]=inp;return node[key2]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}if((typeof onEvent==="function"||onEvent instanceof GraphNode)&&args){if(onEvent instanceof GraphNode&&onEvent.__operator)onEvent=function(inp){return onEvent.__operator(inp)};onEvent=wrapArgs(onEvent,args,this)}if(nd instanceof GraphNode){sub=nd.__subscribe(onEvent,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof nodeEvent==="string"){if(this.get(nodeEvent)){if(onEvent instanceof GraphNode&&onEvent.__operator){sub=this.get(nodeEvent).__subscribe(onEvent.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(nodeEvent).__unsubscribe(sub)};onEvent.__addOndisconnected(ondelete)}else if(typeof onEvent==="function"||typeof onEvent==="string"){sub=this.get(nodeEvent).__subscribe(onEvent,key,subInput,target,bound);this.__node.state.getEvent(this.get(nodeEvent).__node.unique,sub).source=nodeEvent}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function")sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"){if(target[key]?.constructor.name==="Object")recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);let fn=function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)};props.forEach(fn)}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return isFunction(thing)==="class"}function isFunction(x2){const res=typeof x2==="function"?x2.prototype?Object.getOwnPropertyDescriptor(x2,"prototype")?.writable?"function":"class":x2.constructor.name==="AsyncFunction"?"async":"arrow":"";return res}var wrapArgs=(callback,argOrder,graph)=>{let args=[];let getCallbackFromString=a=>{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};let forArg=(a,i2)=>{if(a==="__output"){args[i2]=inp=>{return inp}}else if(typeof a==="string"){args[i2]=getCallbackFromString(a)}else if(typeof a==="function"){let fn2=a;args[i2]=(...inp)=>{return fn2(...inp)}}else if(typeof a==="object"&&a.__input){let recursivelyCreateCallback=function(c){let input=c.__input;if(typeof c.__input==="string"){input=getCallbackFromString(c.__input)}if(c.__args){input=wrapArgs(input,c.__args,graph)}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output=getCallbackFromString(output)}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output==="function"){let fn2=input;input=(...inp)=>{return output(fn2(...inp))}}}return input};args[i2]=recursivelyCreateCallback(a)}else{let arg=a;args[i2]=()=>{return arg}}};argOrder.forEach(forArg);if(typeof callback==="string")callback=getCallbackFromString(callback);let fn=callback;callback=function(...inp){let mapArg=arg=>{return arg(...inp)};return fn(...args.map(mapArg))};return callback};var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator&&!node.__node.looperSet){if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i2=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i2,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){node.__node.looperSet=true;let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.load(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt)}rt.worker=worker;if(!rt.worker.__ondisconnected){let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,void 0,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent,graph,roots)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent?.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,void 0,rt.callback,void 0,void 0,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&roots[rt.__parent]?.worker){roots[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,void 0,void 0,void 0,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,method,transfer)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,method,transfer)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,args,key,subInput,blocking)=>{return this.subscribeToWorker(route,options._id,callback,args,key,subInput,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,void 0,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,void 0,workerSubs[key].callback,void 0,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub});console.log(JSON.stringify(workerSubs))}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub]).then(console.log)}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.open=this.addWorker;this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys2=Object.keys(this.workers);this.workers[keys2[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys2.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}else if(typeof worker==="object"){if(worker?._id){worker=worker.worker;delete this.workers[worker?._id]}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,args,key,subInput,blocking)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,args,key,subInput)};this.subscribeToWorker=(route,workerId,callback,args,key,subInput,blocking)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeEvent(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,args,key,subInput,blocking])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i2=0;i2{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,args,key,subInput,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof sourceWorker==="object"){return sourceWorker.run("unsubscribe",[sourceRoute,sub])}};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.load(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","altKey","shiftKey","button","which","pointerType","clientX","clientY","pageX","pageY","movementX","movementY","x","y","which","timeStamp"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","altKey","isComposing","keyCode","key","code","repeat","timeStamp"]);function focusEventHandler(event,sendFn){const data={type:event.type};data.isTrusted=event.isTrusted;data.bubbles=event.bubbles;data.cancelBubble=event.cancelBubble;data.cancelable=event.cancelable;data.composed=event.composed;data.defaultPrevent=event.defaultPrevented;data.eventPhase=event.eventPhase;data.returnValue=event.returnValue;data.currentTarget=event.currentTarget.id?event.currentTarget.id:event.currentTarget.constructor.name;data.target=data.currentTarget;data.srcElement=data.currentTarget;sendFn(data)}function wheelEventHandler(event,sendFn){if(event.preventDefault)event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){if(event.preventDefault)event.preventDefault()}function copyProperties(src,properties,dst){for(const name2 of properties){dst[name2]=src[name2]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i2=0;i2123))event.preventDefault();keydownEventHandler(event,sendFn)}}var eventHandlers={contextmenu:preventDefaultHandler,mousedown:mouseEventHandler,mousemove:mouseEventHandler,mouseup:mouseEventHandler,pointerdown:mouseEventHandler,pointermove:mouseEventHandler,pointerup:mouseEventHandler,pointerlockchange:mouseEventHandler,webkitpointerlockchange:mouseEventHandler,focus:focusEventHandler,blur:focusEventHandler,pointerout:mouseEventHandler,touchstart:touchEventHandler,touchmove:touchEventHandler,touchend:touchEventHandler,wheel:wheelEventHandler,keydown:filteredKeydownEventHandler,keyup:filteredKeydownEventHandler};function initProxyElement(element,worker,id){if(!id)id="proxy"+Math.floor(Math.random()*1e15);const sendEvent=data=>{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}if(eventHandlers.keydown){globalThis.addEventListener("keydown",function(ev2){eventHandlers.keydown(ev2,sendEvent)})}if(eventHandlers.keyup){globalThis.addEventListener("keyup",function(ev2){eventHandlers.keyup(ev2,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i2=0,l=array.length;i2{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}blur(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy);addTo.blur=proxy.blur.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={elementFromPoint:(...args)=>{return this.targets[Object.keys(this.targets)[0]].proxied}}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){console.log(options);if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let tr=[offscreen];if(options.transfer){tr.push(...options.transfer);delete options.transfer}worker.postMessage(message,tr);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:(props,transfer)=>{worker.postMessage({route:"drawFrame",args:[props,options._id]},transfer)},update:(props,transfer)=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]},transfer)},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:(newDrawProps,transfer)=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]},transfer)},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw.bind(settings)}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update.bind(settings)}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init.bind(settings)}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear.bind(settings)}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph){canvasOptions.graph=this.__node.graph;if(!canvasOptions.__node){canvasOptions.__node={}}if(!canvasOptions.__node.tag)canvasOptions.__node.tag=canvasOptions._id;canvasOptions=this.__node.graph.add(canvasOptions);canvasOptions.__addOndisconnected=()=>{canvasOptions.stop();delete this.__node.graph.CANVASES[canvasOptions._id]}}if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw.bind(canvasOptions)}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update.bind(canvasOptions)}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init.bind(canvasOptions)}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear.bind(canvasOptions)}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{if(this.__node?.graph)this.__node.graph.remove(options._id);else{stopAnim(options._id);if(this?.__node?.graph)delete this.__node.graph.CANVASES[canvasOptions._id];else delete globalThis.CANVASES[canvasOptions._id]}}};return canvascontrols}}function drawFrame(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts=getCanvas.call(this,_id);canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts=getCanvas.call(this,_id);if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")requestAnimationFrame(canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context));return _id}return void 0}function getCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}return canvasopts}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim,getCanvas};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var recursivelyStringifyFunctions=obj=>{let cpy={};for(const key in obj){if(typeof obj[key]==="object"){cpy[key]=recursivelyStringifyFunctions(obj[key])}else if(typeof obj[key]==="function"){cpy[key]=obj[key].toString()}else cpy[key]=obj[key]}return cpy};function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}function methodstrings(node){if(typeof node.__methods==="object"){for(const key in node.__methods){let fstr=node.__methods[key];let fn=typeof fstr==="function"?fstr:parseFunctionFromText2(fstr);if(key==="__operator"){node.__setOperator(fn)}else{node[key]=fn.bind(node)}}}}var nodeTemplates={};var remoteGraphRoutes={transferNode:(properties,connection,name2)=>{let str;if(typeof properties==="object"){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}str=recursivelyStringifyFunctions(properties)}else if(typeof properties==="function")str=properties.toString();else if(typeof properties==="string")str=properties;if(str){if(connection.run)return connection.run("setNode",[str]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:str},void 0);return new Promise(r=>r(name2))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:str}));return new Promise(r=>r(name2))}}},setNode:function(properties,name2){console.log("setting node",properties);if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText2(properties);if(typeof f==="function")properties={__operator:f,__node:{tag:name2?name2:f.name}};else{f=JSON.parse(properties);if(typeof f==="object")properties=f}}if(typeof properties==="object"||typeof properties==="function"){let template={};if(typeof properties==="object")Object.assign(template,properties);else template.__operator=properties;let node=this.__node.graph.add(properties);nodeTemplates[node.__node.tag]=template;return node.__node.tag}else return false},proxyRemoteNode:function(name2,connection){return new Promise((res,rej)=>{connection.run("getNodeProperties",name2).then(props=>{let proxy={};if(typeof props==="object"){for(const key in props){if(props[key]==="function"){proxy[key]=(...args)=>{return new Promise(r=>{connection.run(name2,args,key).then(r)})}}else{Object.defineProperty(proxy,key,{get:()=>{return new Promise(r=>{connection.run(name2,void 0,key).then(r)})},set:value=>{connection.post(name2,value,key)},configurable:true,enumerable:true})}}}res(proxy)})})},makeNodeTransferrable:function(properties,name2){if(!properties.__node){properties.__node={}}if(name2)properties.__node.tag=name2;for(const key in properties){if(typeof properties[key]==="function"){if(!properties.__methods)properties.__methods={};properties.__methods[key]=properties[key].toString()}}const str=recursivelyStringifyFunctions(properties);return str},setTemplate:function(properties,name2){if(typeof properties==="object"){if(properties.__methods){if(!this.__node.graph.__node.loaders.methodstrings){this.__node.graph.__node.loaders.methodstrings=methodstrings}}}if(typeof properties==="string"){let f=parseFunctionFromText2(properties);if(typeof f==="function"){if(!name2)name2=f.name;properties={__operator:f,__node:{tag:name2}}}else{f=JSON.parse(properties);if(typeof f==="object"){properties=f;if(!name2&&f.__node?.tag)name2=f.__node.tag}}}if(!name2)name2=`node${Math.floor(Math.random()*1e15)}`;if(typeof properties==="object"||typeof properties==="function"){nodeTemplates[name2]=properties;return name2}else return false},loadFromTemplate:function(templateName,name2,properties){if(nodeTemplates[templateName]){let cpy=recursivelyAssign2({},nodeTemplates[templateName]);if(name2){if(!cpy.__node)cpy.__node={};cpy.__node.tag=name2}if(properties)Object.assign(cpy,properties);let node=this.__node.graph.add(cpy);return node.__node.tag}},setMethod:function(nodeTag,fn,methodKey){if(typeof fn==="string"){let f=parseFunctionFromText2(fn);if(typeof f==="function")fn=f}if(!methodKey&&typeof fn==="function")methodKey=fn.name;if(this.__node.graph.get(nodeTag)){this.__node.graph.get(nodeTag)[methodKey]=fn}else this.__node.graph.add({__node:{tag:methodKey,[methodKey]:fn}});return true},assignNode:function(nodeTag,source){if(this.__node.graph.get(nodeTag)&&typeof source==="object"){Object.assign(this.__node.graph.get(nodeTag),source)}},getNodeProperties:function(nodeTag){let node=this.__node.graph.get(nodeTag);if(node){let properties=Object.getOwnPropertyNames(node);let result={};for(const key in properties){result[key]=typeof node[key]}return result}return void 0},transferClass:(classObj,connection,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};if(connection.run)return connection.run("receiveClass",[str,className]);else if(connection.postMessage){connection.postMessage({route:"receiveClass",args:[str,className]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"receiveClass",args:[str,className]}));return new Promise(r=>r(name))}return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name2=className;if(!name2)name2=cls.name;this.__node.graph[name2]=cls;return true}}return false},transferFunction:(fn,connection,fnName)=>{if(!fnName)fnName=fn.name;let str=fn.toString();let message={route:"setNode",args:[str,fnName]};if(connection.run)return connection.run("setNode",[str,fnName]);else if(connection.postMessage){connection.postMessage({route:"setNode",args:[str,fnName]},void 0);return new Promise(r=>r(name))}else if(connection.send){connection.send(JSON.stringify({route:"setNode",args:[str,fnName]}));return new Promise(r=>r(name))}return message},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},setGraphFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i2=0;i2a+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i2=0;i2{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i2)=>{dsqrd+=(point2[i2]-c)*(point2[i2]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i2)=>{return(c+point2[i2])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i2)=>{vecn[i2]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i2=0;i2precision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i22)=>{if(Math.abs(xn1-root){vec.push(point2[i2]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i2,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i2},y:${j}`);return v+i2+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i2=0;if(typeof asIndex==="function"){while(i2{result[i2]=func(buffer[i2],i2,...coordinate);i2++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i2=0;i2upperBounds[i2]){let temp=upperBounds[i2];upperBounds[i2]=lowerBounds[i2];lowerBounds[i2]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i2=0;i2x2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i2=0;i20){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i2=start;i20){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i22=0;i22{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i2].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i2]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i2]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i2){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i2-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i2=0;i2current+=previous)/(i2+1))}else{var arrslice=arr.slice(i2-window,i2);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i2=0;i2y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i2=incr;i2lastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i2=0;i2=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i2>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(i2Math.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(i2Math.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i2=0;i2=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i2>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i2=0;i2ref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i2=0){pass=false;break}else if(i2>ref.length*.5&&val<0){pass=false;break}}else{if(i2=0){pass=false;break}else if(i2>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i2=0;i2ref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i2)=>{if(peakIndices.indexOf(i2)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i2=0;i2new Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i2=range[0];i2{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i2=range[0][0]+stepx;i2{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i2=range[0][0]+stepx;i2{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i2=range[0];i2{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i2=1;i2<=fit2;i2++){result[i2]=lerp(v02,v12,a*i2);if(floor2)result[i2]=Math.floor(result[i2])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i2=0;i2 { - [key: string]: any; - }; - setValue: (key: any, value: any) => void; - triggerEvent: (key: any, value: any) => void; - subscribeState: (onchange: (res: any) => void) => number; - unsubscribeState: (sub: number) => boolean; - subscribeEvent: (key: string, onchange: (res: any) => void, refObject?: { - [key: string]: any; - }, refKey?: string) => number; - unsubscribeEvent: (key: string, sub?: number) => boolean; - subscribeEventOnce: (key: string, onchange: (res: any) => void) => any; - getEvent: (key: any, sub?: any) => { - [key: string]: any; - sub: number; - onchange: Function; - } | { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - getSnapshot: () => void; - onRemoved: (trigger: { - sub: number; - onchange: Function; - }) => void; -} diff --git a/src/extras/dist/core/Graph.d.ts b/src/extras/dist/core/Graph.d.ts deleted file mode 100644 index f77b09bd..00000000 --- a/src/extras/dist/core/Graph.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { EventHandler } from "./EventHandler"; -export declare const state: EventHandler; -export type GraphNodeProperties = { - __props?: Function | { - [key: string]: any; - } | GraphNodeProperties | GraphNode; - __operator?: ((...args: any[]) => any) | string; - __children?: { - [key: string]: any; - }; - __listeners?: { - [key: string]: true | string | ((result: any) => void) | { - __callback: string | ((result: any) => void) | true; - subInput?: boolean; - [key: string]: any; - }; - } | { - [key: string]: ((result: any) => void) | true | string; - }; - __onconnected?: ((node: any) => void | ((node: any) => void)[]); - __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); - __node?: { - tag?: string; - state?: EventHandler; - [key: string]: any; - }; - __args?: any[]; - __callable?: boolean; - [key: string]: any; -}; -export type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; -export type Roots = { - [key: string]: any; -}; -export type GraphOptions = { - roots?: Roots; - loaders?: { - [key: string]: Loader | { - init?: Loader; - connected?: (node: any) => void; - disconnected?: (node: any) => void; - }; - }; - state?: EventHandler; - mapGraphs?: false; - [key: string]: any; -}; -export type argObject = { - __input?: string | ((...args: any[]) => any); - __callback: string | ((...args: any[]) => any); - __args?: any[]; - __output?: string | argObject | ((...args: any[]) => any); -}; -export type Listener = { - __callback?: string; - __args?: (argObject | Function | string)[]; - sub: number; - node: GraphNode; - graph: Graph; - source?: string; - key?: string; - target?: string; - tkey?: string; - arguments?: Function[]; - subInput?: boolean; - onchange: Function; -}; -export declare class Callable extends Function { - __bound: Callable; - __call: ((...args: any[]) => any); - [key: string]: any; - constructor(); -} -export declare class GraphNode { - __node: { - tag: string; - unique: string; - state: EventHandler; - [key: string]: any; - }; - __children?: { - [key: string]: GraphNode; - }; - __parent?: Graph | GraphNode; - __operator?: any; - __listeners?: any; - __props?: any; - __args: any[]; - [key: string]: any; - constructor(properties: GraphNodeProperties, parent?: { - [key: string]: any; - }, graph?: Graph); - get __graph(): any; - set __graph(graph: any); - __setProperties: (properties: any, parent: any, graph: any) => void; - __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, target?: string, tkey?: string, args?: any[], callbackStr?: string) => any; - __unsubscribe: (sub?: number, key?: string, unsubInput?: boolean) => boolean; - __setOperator: (fn: (...args: any[]) => any) => any; - __addLocalState: (props?: { - [key: string]: any; - }, key?: string) => void; - __proxyObject: (obj: any) => void; - __addOnconnected(callback: (node: any) => void): void; - __addOndisconnected(callback: (node: any) => void): void; - __callConnected(node?: this): void; - __callDisconnected(node?: this): void; -} -export declare class Graph { - [key: string]: any; - __node: { - tag: string; - unique: string; - state: EventHandler; - nodes: Map; - roots: { - [key: string]: any; - }; - mapGraphs?: boolean; - [key: string]: any; - }; - constructor(options?: GraphOptions); - init: (options?: GraphOptions) => void; - load: (roots: { - [key: string]: any; - }, overwrite?: boolean) => { - [key: string]: any; - }; - setLoaders: (loaders: { - [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, props: any, key: string) => void; - }, replace?: boolean) => any; - runLoaders: (node: any, parent: any, properties: any, key: any) => void; - add: (properties: any, parent?: GraphNode | string, overwrite?: boolean) => GraphNode; - recursiveSet: (originCpy: any, parent: any, listeners: any, origin: any, overwrite?: boolean) => any; - remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; - run: (node: string | GraphNode, ...args: any[]) => any; - /** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners: (listeners: { - [key: string]: { - [key: string]: any; - }; - }) => void; - clearListeners: (node: GraphNode | string, listener?: string) => void; - get: (tag: string) => any; - getByUnique: (unique: string) => any; - set: (tag: string, node: GraphNode) => Map; - delete: (tag: string) => boolean; - list: () => string[]; - getListener: (nodeTag: string, key?: string, sub?: number) => Listener; - getProps: (node: GraphNode | string, getInitial?: boolean) => void; - subscribe: (nodeEvent: GraphNode | string, onEvent: string | GraphNode | ((...res: any) => void), args?: any[], key?: string | undefined, subInput?: boolean, target?: string | GraphNode, tkey?: string) => number; - unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; - setState: (update: { - [key: string]: any; - }) => void; -} -export declare function getAllProperties(obj: any): any[]; -export declare function instanceObject(obj: any): any; -export declare function isNativeClass(thing: any): boolean; -export declare function isFunction(x: any): "function" | "class" | "async" | "arrow" | ""; -export declare let getCallbackFromString: (a: any, graph: any) => (...inp: any[]) => any; -export declare const wrapArgs: (callback: any, argOrder: any, graph: any) => { - __callback: any; - __args: any[]; -}; diff --git a/src/extras/dist/extras/algorithms/accel_gyro.d.ts b/src/extras/dist/extras/algorithms/accel_gyro.d.ts deleted file mode 100644 index c98cb706..00000000 --- a/src/extras/dist/extras/algorithms/accel_gyro.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const accel_gyro: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/beat_detect.d.ts b/src/extras/dist/extras/algorithms/beat_detect.d.ts deleted file mode 100644 index bc3fb33d..00000000 --- a/src/extras/dist/extras/algorithms/beat_detect.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const beat_detect: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/blink.d.ts b/src/extras/dist/extras/algorithms/blink.d.ts deleted file mode 100644 index 4743de8d..00000000 --- a/src/extras/dist/extras/algorithms/blink.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const blink_detect: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/buffering.d.ts b/src/extras/dist/extras/algorithms/buffering.d.ts deleted file mode 100644 index 71e1efac..00000000 --- a/src/extras/dist/extras/algorithms/buffering.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const circularBuffer2d: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/coherence.d.ts b/src/extras/dist/extras/algorithms/coherence.d.ts deleted file mode 100644 index 0b35b736..00000000 --- a/src/extras/dist/extras/algorithms/coherence.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const coherence: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/dft.d.ts b/src/extras/dist/extras/algorithms/dft.d.ts deleted file mode 100644 index ccd239c3..00000000 --- a/src/extras/dist/extras/algorithms/dft.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const dft: GraphNodeProperties; diff --git a/src/extras/dist/extras/algorithms/index.d.ts b/src/extras/dist/extras/algorithms/index.d.ts deleted file mode 100644 index c3ec990e..00000000 --- a/src/extras/dist/extras/algorithms/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -declare const algorithms: { - [key: string]: GraphNodeProperties; -}; -export { algorithms }; diff --git a/src/extras/dist/extras/algorithms/index.gpu.d.ts b/src/extras/dist/extras/algorithms/index.gpu.d.ts deleted file mode 100644 index fcfc3ef0..00000000 --- a/src/extras/dist/extras/algorithms/index.gpu.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare const gpualgorithms: { - dft: import("../../core/Graph").GraphNodeProperties; - coherence: import("../../core/Graph").GraphNodeProperties; -}; diff --git a/src/extras/dist/extras/algorithms/rms.d.ts b/src/extras/dist/extras/algorithms/rms.d.ts deleted file mode 100644 index 39ad84d0..00000000 --- a/src/extras/dist/extras/algorithms/rms.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -export declare const rms: GraphNodeProperties; diff --git a/src/extras/dist/extras/ecs/ECS.systems.d.ts b/src/extras/dist/extras/ecs/ECS.systems.d.ts deleted file mode 100644 index 34de4406..00000000 --- a/src/extras/dist/extras/ecs/ECS.systems.d.ts +++ /dev/null @@ -1,383 +0,0 @@ -import { Entity } from "../../services/ecs/ECS.service"; -export declare const Systems: { - collision: { - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __node: { - tag: string; - }; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - collisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionEnabled?: boolean; - collisionType: 'sphere' | 'box' | 'point'; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionEnabled?: boolean; - collisionType: 'sphere' | 'box' | 'point'; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => number | false; - sphereCollisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - boxCollisionCheck: (body1: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, body2: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => boolean; - sphereBoxCollisionCheck: (sphere: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, box: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - isPointInsideSphere: (point: { - x: number; - y: number; - z: number; - }, sphere: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }, dist?: number) => boolean; - isPointInsideBox: (point: { - x: number; - y: number; - z: number; - }, box: { - [key: string]: any; - position: { - x: number; - y: number; - z: number; - }; - collisionRadius: number; - collisionBoundsScale: { - x: number; - y: number; - z: number; - }; - }) => boolean; - closestPointOnLine: (point: { - x: number; - y: number; - z: number; - }, lineStart: { - x: number; - y: number; - z: number; - }, lineEnd: { - x: number; - y: number; - z: number; - }) => { - x: number; - y: number; - z: number; - }; - closestPointOnPolygon: (point: { - x: number; - y: number; - z: number; - }, t0: { - x: number; - y: number; - z: number; - }, t1: { - x: number; - y: number; - z: number; - }, t2: { - x: number; - y: number; - z: number; - }) => { - [key: string]: number; - }; - calcNormal: (t0: { - x: number; - y: number; - z: number; - }, t1: { - x: number; - y: number; - z: number; - }, t2: { - x: number; - y: number; - z: number; - }, positive?: boolean) => {}; - dot: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - makeVec(p1: { - x: number; - y: number; - z: number; - }, p2: { - x: number; - y: number; - z: number; - }): { - x: number; - y: number; - z: number; - }; - vecadd: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecsub: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecmul: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecdiv: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecscale: (v1: { - [key: string]: number; - }, scalar: number) => { - [key: string]: number; - }; - distance: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - magnitude: (v: { - [key: string]: number; - }) => number; - normalize: (v: { - [key: string]: number; - }) => {}; - distance3D(v1: { - x: number; - y: number; - z: number; - }, v2: { - x: number; - y: number; - z: number; - }): number; - cross3D(v1: { - x: number; - y: number; - z: number; - }, v2: { - x: number; - y: number; - z: number; - }): { - x: number; - y: number; - z: number; - }; - nearestNeighborSearch(entities: { - [key: string]: Entity; - }, isWithinRadius?: number): {}; - generateBoundingVolumeTree(entities: { - [key: string]: Entity; - }, mode?: 'octree' | 'aabb', withinRadius?: number, minEntities?: number): any; - }; - collider: { - lastTime: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - checkBoundingBox: (entity: any) => void; - resolveBoxCollision: (body1: Entity, box: Entity, negate?: boolean) => void; - resolveSphereCollisions: (entity1: Entity, entity2: Entity, dist?: number) => void; - }; - nbody: { - lastTime: number; - G: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - attract: (body1: any, body2: any, dist?: number, G?: any, vecn?: { - x: number; - y: number; - z: number; - }) => void; - }; - boid: { - lastTime: number; - defaultAnchor: { - x: number; - y: number; - z: number; - mul: number; - }; - setupEntities: (entities: any) => any; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - __node: { - tag: string; - }; - }; - movement: { - __node: { - tag: string; - }; - lastTime: number; - setupEntities: (entities: { - [key: string]: Entity; - }) => void; - setupEntity: (entity: Entity) => Entity; - __operator: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - }; -}; diff --git a/src/extras/dist/extras/struct/Struct.backend.d.ts b/src/extras/dist/extras/struct/Struct.backend.d.ts deleted file mode 100644 index 278d1ebe..00000000 --- a/src/extras/dist/extras/struct/Struct.backend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ObjectId } from "./datastructures/bson.cjs"; -import { AuthorizationStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from "../../services/Service"; -import { User } from '../../services/router/Router'; -export declare const toObjectId: (str: any) => any; -export declare const getStringId: (mongoid: string | ObjectId) => any; -type CollectionsType = { - [x: string]: CollectionType; -}; -type CollectionType = any | { - instance?: any; - reference: { - [key: string]: any; - }; -}; -export declare class StructBackend extends Service { - name: string; - debug: boolean; - db: any; - users: { - [key: string]: User; - }; - collections: CollectionsType; - mode: 'local' | 'mongo' | string; - useAuths: boolean; - useAccessTokens: boolean; - useRefreshTokens: boolean; - accessTokens: Map; - refreshTokens: Map; - constructor(options?: any, dboptions?: { - users?: { - [key: string]: User; - }; - mode?: 'local' | 'mongo' | string; - db?: any; - collections?: CollectionsType; - useAuths?: boolean; - debug?: boolean; - useAccessTokens?: boolean; - useRefreshTokens?: boolean; - }); - initDB: (dboptions: any) => void; - query: (requestingUserId: string, collection?: any, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - getUser: (requestingUserId: string, lookupId: string, basicInfo?: boolean, token?: string) => Promise; - setUser: (requestingUserId: string, struct: Partial, token: string) => Promise; - getUsersByIds: (requestingUserId: string, userIds: string[], basicInfo?: boolean) => Promise; - getUsersByRole: (requestingUserId: string, role: string) => Promise; - deleteUser: (requestingUserId: string, userId: string, deleteData?: boolean, token?: string) => Promise; - setData: (requestingUserId: string, structs: any[], notify?: boolean, token?: string) => Promise; - getData: (requestingUserId: string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number, token?: string) => Promise; - getDataByIds: (requestingUserId: string, structIds: string[], ownerId?: string, collection?: string, token?: string) => Promise; - getAllData: (requestingUserId: string, ownerId: string, excludedCollections?: string[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - deleteData: (requestingUserId: string, structIds: string[], token?: string) => Promise; - getUserGroups: (requestingUserId: string, userId?: string, groupId?: string) => Promise; - deleteGroup: (requestingUserId: string, groupId: string, token?: string) => Promise; - getAuthorizations: (requestingUserId: string, ownerId?: string, authId?: string, token?: string) => Promise; - deleteAuthorization: (requestingUserId: string, authId: string, token?: string) => Promise; - getToken: (user: Partial) => string; - notificationStruct: (parentStruct?: any) => { - structType: string; - timestamp: number; - _id: string; - note: string; - alert: boolean; - ownerId: string; - parentUserId: string; - parent: { - structType: any; - _id: any; - }; - }; - checkToNotify: (user: Partial, structs?: any[], mode?: string) => Promise; - queryMongo: (user: Partial, collection: string, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - setMongoData: (user: Partial, structs?: any[], notify?: boolean, token?: string) => Promise; - setMongoUser: (user: Partial, struct: Partial, token?: string) => Promise; - setGroup: (user: Partial, struct: any, mode?: string, token?: string) => Promise; - getMongoUser: (user: Partial, info?: string, requireAuth?: boolean, basicInfo?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - queryUsers: (user: Partial, info?: string, limit?: number, skip?: number, requireAuth?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - getMongoUsersByIds: (user: Partial, userIds?: any[], basicInfo?: boolean) => Promise; - getMongoUsersByRole: (user: Partial, role: string) => Promise; - getMongoDataByIds: (user: Partial, structIds: string[], ownerId: string | undefined, collection: string | undefined, token?: string) => Promise; - getMongoData: (user: Partial, collection: string | undefined, ownerId: string | undefined, dict?: any | undefined, limit?: number, skip?: number, token?: string) => Promise; - getAllUserMongoData: (user: Partial, ownerId: any, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - getMongoDataByRefs: (user: Partial, structRefs?: any[], token?: string) => Promise; - getMongoAuthorizations: (user: Partial, ownerId?: any, authId?: string, token?: string) => Promise; - getMongoGroups: (user: Partial, userId?: any, groupId?: string) => Promise; - deleteMongoData: (user: Partial, structRefs?: any[], token?: string) => Promise; - deleteMongoUser: (user: Partial, userId: any, deleteData?: boolean, token?: string) => Promise; - deleteMongoGroup: (user: Partial, groupId: any, token?: string) => Promise; - deleteMongoAuthorization: (user: Partial, authId: any, token?: string) => Promise; - setAuthorization: (user: Partial, authStruct: any, token?: string) => Promise; - checkAuthorization: (user: string | Partial | { - _id: string; - }, struct: any, request?: string, token?: string) => Promise; - wipeDB: () => Promise; - overwriteLocalData: (structs: any) => void; - setLocalData: (structs: any) => void; - getLocalData: (collection: any, query?: any) => any; - deleteLocalData: (struct: any) => boolean; -} -export {}; diff --git a/src/extras/dist/extras/struct/Struct.frontend.d.ts b/src/extras/dist/extras/struct/Struct.frontend.d.ts deleted file mode 100644 index 3b0ef8dc..00000000 --- a/src/extras/dist/extras/struct/Struct.frontend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { DataTablet } from './datastructures/index'; -import { Data, ProfileStruct, AuthorizationStruct, GroupStruct, DataStruct, EventStruct, ChatroomStruct, CommentStruct, Struct } from './datastructures/types'; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from '../../services/Service'; -import { User } from '../../services/router/Router'; -import { GraphNodeProperties } from '../../core/Graph'; -export declare const randomId: (prefix?: any) => string; -export declare const pseudoObjectId: (m?: Math, d?: DateConstructor, h?: number, s?: (s: any) => string) => string; -export type StructFrontendProps = { - useAccessTokens?: boolean; - useRefreshTokens?: boolean; -} & GraphNodeProperties; -export declare class StructFrontend extends Service { - name: string; - currentUser: User; - tablet: DataTablet; - collections: Map; - id: string; - useAccessTokens: boolean; - useRefreshTokens: boolean; - constructor(options?: any, user?: Partial); - getToken(user: Partial): string; - setupUser: (userinfo: Partial, callback?: (currentUser: any) => void) => Promise; - baseServerCallback: (data: any) => void; - structNotification: () => void; - structDeleted: (struct: { - _id: string; - structType: string; - }) => void; - onResult: (data: any) => void; - randomId(tag?: string): string; - /** - let struct = { - _id: randomId(structType+'defaultId'), //random id associated for unique identification, used for lookup and indexing - structType: structType, //this is how you will look it up by type in the server - ownerId: parentUser?._id, //owner user - timestamp: Date.now(), //date of creation - parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) - } - */ - addStruct: (structType?: string, props?: any, parentUser?: { - [key: string]: any; - }, parentStruct?: { - [key: string]: any; - }, updateServer?: boolean) => Promise; - getUser: (info?: string | number, basicInfo?: boolean, callback?: (data: any) => void) => Promise<{ - user: ProfileStruct; - groups: GroupStruct[]; - authorizations: AuthorizationStruct[]; - }>; - queryUsers: (info: string, skip?: number, limit?: number, callback?: (data: any) => void) => Promise; - getUsers: (ids?: (string | number)[], basicInfo?: boolean, callback?: (data: any) => void) => Promise; - getUsersByRole: (userRole: string, callback?: (data: any) => void) => Promise; - getAllUserData: (ownerId: string | number, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], callback?: (data: any) => void) => Promise; - query: (collection: string, mongoQuery?: {}, findOne?: boolean, skip?: number, callback?: (data: any) => void) => Promise; - getDataByTimeRange(collection: any, timeRange?: [number | TimeSpecifier, number | TimeSpecifier], ownerId?: string | number | undefined, limit?: number, skip?: number, key?: string): Promise; - getData: (collection: string, ownerId?: string | number | undefined, searchDict?: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - getDataByIds: (structIds?: any[], ownerId?: string | number | undefined, collection?: string | undefined, callback?: (data: any) => void) => Promise; - getStructParentData: (struct: Struct, callback?: (data: any) => void) => Promise; - setUser: (userStruct: ProfileStruct, callback?: (data: any) => void) => Promise; - checkUserToken: (usertoken: any, user?: User, callback?: (data: any) => void) => Promise; - setData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; - updateServerData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; - deleteData: (structs?: any[], callback?: (data: any) => void) => Promise; - deleteUser: (userId?: string, deleteData?: boolean, callback?: (data: any) => void) => Promise; - setGroup: (groupStruct: GroupStruct, callback?: (data: any) => void) => Promise; - getUserGroups: (userId?: string, groupId?: string, callback?: (data: any) => void) => Promise; - deleteGroup: (groupId: any, callback?: (data: any) => void) => Promise; - setAuthorization: (authorizationStruct: AuthorizationStruct, callback?: (data: any) => void) => Promise; - getAuthorizations: (userId?: string, authorizationId?: string, callback?: (data: any) => void) => Promise; - deleteAuthorization: (authorizationId: any, callback?: (data: any) => void) => Promise; - checkForNotifications: (userId?: string) => Promise; - resolveNotifications: (notifications?: any[], pull?: boolean, user?: Partial) => Promise; - setAuthorizationsByGroup: (user?: User) => Promise; - deleteRoom: (roomStruct: any) => Promise; - deleteComment: (commentStruct: any) => Promise; - getUserDataByAuthorization: (authorizationStruct: any, collection: any, searchDict: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - getUserDataByAuthorizationGroup: (groupId: string, collection: any, searchDict: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; - overwriteLocalData(structs: any): void; - setLocalData(structs: any): void; - getLocalData(collection: any, query?: any): any; - getLocalUserPeerIds: (user?: User) => any; - getLocalReplies(struct: any): any; - hasLocalAuthorization(otherUserId: any, ownerId?: string): any; - deleteLocalData(structs: Struct[]): boolean; - deleteStruct(struct: Struct): boolean; - stripStruct(struct: Struct): Struct; - createStruct(structType: string, props: { - [key: string]: any; - }, parentUser?: User, parentStruct?: Struct): any; - userStruct(props?: Partial, currentUser?: boolean): ProfileStruct; - authorizeUser: (parentUser: Partial, authorizerUserId?: string, authorizerUserName?: string, authorizedUserId?: string, authorizedUserName?: string, authorizations?: {}, structs?: {}, excluded?: {}, groups?: {}, expires?: boolean) => Promise; - addGroup: (parentUser: Partial, name?: string, details?: string, admins?: {}, peers?: {}, clients?: {}, updateServer?: boolean) => Promise; - dataObject(data?: any, type?: string, timestamp?: string | number): { - type: string; - data: any; - timestamp: string | number; - }; - addData: (parentUser: Partial, author?: string, title?: string, type?: string, data?: string | Data[], expires?: boolean, updateServer?: boolean) => Promise; - addEvent: (parentUser: Partial, author?: string, event?: string | number, notes?: string, startTime?: string | number, endTime?: string | number, grade?: string | number, value?: any, units?: string, location?: any, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addChatroom: (parentUser: Partial, authorId?: string, message?: string, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addComment: (parentUser: Partial, roomStruct?: { - _id: string; - users: any[]; - comments: any[]; - }, replyTo?: { - _id: string; - replies: any[]; - }, authorId?: string, message?: string, attachments?: string | Data[], updateServer?: boolean) => Promise; -} diff --git a/src/extras/dist/extras/struct/datastructures/bson.d.cts b/src/extras/dist/extras/struct/datastructures/bson.d.cts deleted file mode 100644 index 2efd64df..00000000 --- a/src/extras/dist/extras/struct/datastructures/bson.d.cts +++ /dev/null @@ -1,419 +0,0 @@ -declare var bson: Readonly<{ - __proto__: any; - Code: typeof Code; - BSONSymbol: typeof BSONSymbol; - DBRef: typeof DBRef; - Binary: typeof Binary; - ObjectId: typeof ObjectId; - UUID: typeof UUID; - Long: typeof Long; - Timestamp: typeof Timestamp; - Double: typeof Double; - Int32: typeof Int32; - MinKey: typeof MinKey; - MaxKey: typeof MaxKey; - BSONRegExp: typeof BSONRegExp; - Decimal128: typeof Decimal128; - setInternalBufferSize: typeof setInternalBufferSize; - serialize: typeof serialize; - serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; - deserialize: typeof deserialize; - calculateObjectSize: typeof calculateObjectSize; - deserializeStream: typeof deserializeStream; - BSONValue: typeof BSONValue; - BSONError: typeof BSONError; - BSONVersionError: typeof BSONVersionError; - BSONRuntimeError: typeof BSONRuntimeError; - BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; - }>; - EJSON: any; -}>; -export class BSONError extends Error { - static isBSONError(value: any): boolean; - constructor(message: any); - get bsonError(): boolean; - get name(): string; -} -export class BSONRegExp extends BSONValue { - static parseOptions(options: any): any; - static fromExtendedJSON(doc: any): any; - constructor(pattern: any, options: any); - get _bsontype(): string; - pattern: any; - options: any; - toExtendedJSON(options: any): { - $regex: any; - $options: any; - $regularExpression?: undefined; - } | { - $regularExpression: { - pattern: any; - options: any; - }; - $regex?: undefined; - $options?: undefined; - }; - inspect(): string; -} -export class BSONRuntimeError extends BSONError { -} -export class BSONSymbol extends BSONValue { - static fromExtendedJSON(doc: any): BSONSymbol; - constructor(value: any); - get _bsontype(): string; - value: any; - valueOf(): any; - toString(): any; - inspect(): string; - toJSON(): any; - toExtendedJSON(): { - $symbol: any; - }; -} -export const BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; -}>; -export class BSONValue { -} -export class BSONVersionError extends BSONError { - constructor(); -} -export class Binary extends BSONValue { - static fromExtendedJSON(doc: any, options: any): Binary; - constructor(buffer: any, subType: any); - get _bsontype(): string; - sub_type: any; - buffer: any; - position: any; - put(byteValue: any): void; - write(sequence: any, offset: any): void; - read(position: any, length: any): any; - value(asRaw: any): any; - length(): any; - toJSON(): any; - toString(encoding: any): any; - toExtendedJSON(options: any): { - $binary: any; - $type: string; - } | { - $binary: { - base64: any; - subType: string; - }; - $type?: undefined; - }; - toUUID(): UUID; - inspect(): string; -} -export namespace Binary { - let BSON_BINARY_SUBTYPE_DEFAULT: number; - let BUFFER_SIZE: number; - let SUBTYPE_DEFAULT: number; - let SUBTYPE_FUNCTION: number; - let SUBTYPE_BYTE_ARRAY: number; - let SUBTYPE_UUID_OLD: number; - let SUBTYPE_UUID: number; - let SUBTYPE_MD5: number; - let SUBTYPE_ENCRYPTED: number; - let SUBTYPE_COLUMN: number; - let SUBTYPE_USER_DEFINED: number; -} -export class Code extends BSONValue { - static fromExtendedJSON(doc: any): Code; - constructor(code: any, scope: any); - get _bsontype(): string; - code: any; - scope: any; - toJSON(): { - code: any; - scope: any; - } | { - code: any; - scope?: undefined; - }; - toExtendedJSON(): { - $code: any; - $scope: any; - } | { - $code: any; - $scope?: undefined; - }; - inspect(): string; -} -export class DBRef extends BSONValue { - static fromExtendedJSON(doc: any): DBRef; - constructor(collection: any, oid: any, db: any, fields: any); - get _bsontype(): string; - collection: any; - oid: any; - db: any; - fields: any; - set namespace(value: any); - get namespace(): any; - toJSON(): any; - toExtendedJSON(options: any): { - $ref: any; - $id: any; - }; - inspect(): string; -} -export class Decimal128 extends BSONValue { - static fromString(representation: any): Decimal128; - static fromExtendedJSON(doc: any): Decimal128; - constructor(bytes: any); - get _bsontype(): string; - bytes: any; - toJSON(): { - $numberDecimal: string; - }; - toExtendedJSON(): { - $numberDecimal: string; - }; - inspect(): string; -} -export class Double extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Double; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toJSON(): number; - toString(radix: any): string; - toExtendedJSON(options: any): number | { - $numberDouble: string; - }; - inspect(): string; -} -export const EJSON: any; -export class Int32 extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Int32; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toString(radix: any): string; - toJSON(): number; - toExtendedJSON(options: any): number | { - $numberInt: string; - }; - inspect(): string; -} -export class Long extends BSONValue { - static fromBits(lowBits: any, highBits: any, unsigned: any): Long; - static fromInt(value: any, unsigned: any): any; - static fromNumber(value: any, unsigned: any): any; - static fromBigInt(value: any, unsigned: any): any; - static fromString(str: any, unsigned: any, radix: any): any; - static fromBytes(bytes: any, unsigned: any, le: any): Long; - static fromBytesLE(bytes: any, unsigned: any): Long; - static fromBytesBE(bytes: any, unsigned: any): Long; - static isLong(value: any): boolean; - static fromValue(val: any, unsigned: any): any; - static fromExtendedJSON(doc: any, options: any): any; - constructor(low: number, high: any, unsigned: any); - get _bsontype(): string; - get __isLong__(): boolean; - low: number; - high: number; - unsigned: boolean; - add(addend: any): Long; - and(other: any): Long; - compare(other: any): 0 | 1 | -1; - comp(other: any): 0 | 1 | -1; - divide(divisor: any): any; - div(divisor: any): any; - equals(other: any): boolean; - eq(other: any): boolean; - getHighBits(): number; - getHighBitsUnsigned(): number; - getLowBits(): number; - getLowBitsUnsigned(): number; - getNumBitsAbs(): any; - greaterThan(other: any): boolean; - gt(other: any): boolean; - greaterThanOrEqual(other: any): boolean; - gte(other: any): boolean; - ge(other: any): boolean; - isEven(): boolean; - isNegative(): boolean; - isOdd(): boolean; - isPositive(): boolean; - isZero(): boolean; - lessThan(other: any): boolean; - lt(other: any): boolean; - lessThanOrEqual(other: any): boolean; - lte(other: any): boolean; - modulo(divisor: any): Long; - mod(divisor: any): Long; - rem(divisor: any): Long; - multiply(multiplier: any): any; - mul(multiplier: any): any; - negate(): Long; - neg(): Long; - not(): Long; - notEquals(other: any): boolean; - neq(other: any): boolean; - ne(other: any): boolean; - or(other: any): Long; - shiftLeft(numBits: any): Long; - shl(numBits: any): Long; - shiftRight(numBits: any): Long; - shr(numBits: any): Long; - shiftRightUnsigned(numBits: any): Long; - shr_u(numBits: any): Long; - shru(numBits: any): Long; - subtract(subtrahend: any): Long; - sub(subtrahend: any): Long; - toInt(): number; - toNumber(): number; - toBigInt(): bigint; - toBytes(le: any): number[]; - toBytesLE(): number[]; - toBytesBE(): number[]; - toSigned(): Long; - toString(radix: any): any; - toUnsigned(): Long; - xor(other: any): Long; - eqz(): boolean; - le(other: any): boolean; - toExtendedJSON(options: any): number | { - $numberLong: any; - }; - inspect(): string; -} -export namespace Long { - let TWO_PWR_24: any; - let MAX_UNSIGNED_VALUE: Long; - let ZERO: any; - let UZERO: any; - let ONE: any; - let UONE: any; - let NEG_ONE: any; - let MAX_VALUE: Long; - let MIN_VALUE: Long; -} -export class MaxKey extends BSONValue { - static fromExtendedJSON(): MaxKey; - get _bsontype(): string; - toExtendedJSON(): { - $maxKey: number; - }; - inspect(): string; -} -export class MinKey extends BSONValue { - static fromExtendedJSON(): MinKey; - get _bsontype(): string; - toExtendedJSON(): { - $minKey: number; - }; - inspect(): string; -} -export class ObjectId extends BSONValue { - static getInc(): number; - static generate(time: any): any; - static createPk(): ObjectId; - static createFromTime(time: any): ObjectId; - static createFromHexString(hexString: any): ObjectId; - static isValid(id: any): boolean; - static fromExtendedJSON(doc: any): ObjectId; - constructor(inputId: any); - get _bsontype(): string; - __id: any; - set id(value: any); - get id(): any; - toHexString(): any; - toString(encoding: any): any; - toJSON(): any; - equals(otherId: any): any; - getTimestamp(): Date; - toExtendedJSON(): { - $oid: any; - }; - inspect(): string; - [kId]: any; -} -export namespace ObjectId { - let index: number; -} -export class Timestamp extends Long { - static fromInt(value: any): Timestamp; - static fromNumber(value: any): Timestamp; - static fromBits(lowBits: any, highBits: any): Timestamp; - static fromString(str: any, optRadix: any): Timestamp; - static fromExtendedJSON(doc: any): Timestamp; - constructor(low: any); - toJSON(): { - $timestamp: any; - }; - toExtendedJSON(): { - $timestamp: { - t: number; - i: number; - }; - }; -} -export namespace Timestamp { - import MAX_VALUE_1 = Long.MAX_UNSIGNED_VALUE; - export { MAX_VALUE_1 as MAX_VALUE }; -} -export class UUID extends Binary { - static generate(): any; - static isValid(input: any): boolean; - static createFromHexString(hexString: any): UUID; - constructor(input: any); - __id: any; - set id(value: any); - get id(): any; - toHexString(includeDashes?: boolean): any; - equals(otherId: any): any; - toBinary(): Binary; -} -export function calculateObjectSize(object: any, options?: {}): number; -export function deserialize(buffer: any, options?: {}): {}; -export function deserializeStream(data: any, startIndex: any, numberOfDocuments: any, documents: any, docStartIndex: any, options: any): any; -export function serialize(object: any, options?: {}): any; -export function serializeWithBufferAndIndex(object: any, finalBuffer: any, options?: {}): number; -export function setInternalBufferSize(size: any): void; -declare const kId: unique symbol; -export { bson as BSON }; diff --git a/src/extras/dist/extras/struct/datastructures/types.d.ts b/src/extras/dist/extras/struct/datastructures/types.d.ts deleted file mode 100644 index ddb01f54..00000000 --- a/src/extras/dist/extras/struct/datastructures/types.d.ts +++ /dev/null @@ -1,243 +0,0 @@ -export type ArbitraryObject = { - [x: string | number]: any; -}; -export type Struct = { - _id: string; - structType?: string | number; - timestamp?: string | number; - ownerId?: string | number; - parent?: { - structType: string; - _id: string | number; - }; - [key: string]: any; -}; -export type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined; -export type StructTypes = LooseStructTypes | DataTypes | 'data' | 'struct' | string | number | undefined; -export type LooseStructTypes = 'coherence' | 'imu' | 'eyetracker' | 'profile' | 'authorization' | 'group' | 'event' | 'chatroom' | 'comment' | 'notification' | 'schedule' | 'date' | string | number | undefined; -export type Data = { - type: string; - data: any; - timestamp?: string | number; -}; -export type DataStruct = { - title?: string; - author?: string; - expires: boolean | number | string; - type: string; - data: Data[]; - tag?: string | number; -} & Struct; -export type EventStruct = { - event: string; - author: string; - startTime: string; - endTime?: string; - grade?: string | number; - value?: any; - units?: string; - notes?: string; - location?: any; - attachments?: Data | string | number[]; - users?: { - [key: string]: true; - }; - tag?: string | number; -} & Struct; -export type ChatroomStruct = { - message: string; - topic: string; - author: string; - attachments: Data | string | number[]; - comments: string[]; - replies: string[]; - users: { - [key: string]: true; - }; - audioChatActive: boolean; - videoChatActive: boolean; - tag?: string | number; -} & Struct; -export type CommentStruct = { - author: string; - replyTo: string; - attachments: Data | string | number[]; - replies: string[]; - users: { - [key: string]: true; - }; - tag?: string | number; -} & Struct; -export type NotificationStruct = { - note: string; - parentUserId: string; - tag?: string | number; -} & Struct; -export type ScheduleStruct = { - title: string; - author: string; - attachments: Data | string | number[]; - dates: string[]; - tag?: string | number; -} & Struct; -export type DateStruct = { - timeSet: string | number; - notes: string; - recurs: number | string | boolean; - attachments: Data | string | number[]; - tag?: string | number; -} & Struct; -export type ProfileStruct = { - username?: string; - name?: string; - firstName?: string; - lastName?: string; - fullName?: string; - email?: string; - phone?: string; - sex?: string; - birthday?: string; - userRoles?: {}; - socials?: {}; - data?: {}; - type?: string; - hidden?: boolean; - pictureUrl: string; - accessToken?: string; - refreshToken?: string; - tag?: string | number; -} & Struct; -export type AuthorizationStruct = { - authorizedId: string; - authorizedName: string; - authorizerId: string; - authorizerName: string; - authorizations: {}; - structs: {}; - excluded: {}; - groups: {}; - status: "PENDING" | "OKAY"; - expires: string | boolean; - associatedAuthId: string | number; - tag?: string | number; -} & Struct; -export type GroupStruct = { - name: string; - details: string; - admins: {}; - peers: {}; - clients: {}; - users: {}; - tag?: string | number; -} & Struct; -type FreqBand = [number[], number[]]; -export type FrequencyBandNames = 'scp' | 'delta' | 'theta' | 'alpha1' | 'alpha2' | 'beta' | 'lowgamma' | 'highgamma'; -export type FrequencyBandsStruct = { - scp: FreqBand | []; - delta: FreqBand | []; - theta: FreqBand | []; - alpha1: FreqBand | []; - alpha2: FreqBand | []; - beta: FreqBand | []; - lowgamma: FreqBand | []; - highgamma: FreqBand | []; -}; -export type EEGStruct = { - position: { - x: number; - y: number; - z: number; - }; - count: number; - times: number[]; - raw: number[]; - filtered: number[]; - fftCount: number; - fftTimes: number[]; - ffts: [][]; - slices: FrequencyBandsStruct; - means: FrequencyBandsStruct; - startTime: number | string; - tag?: string | number; -} & Struct; -export type CoherenceStruct = { - x0: number; - y0: number; - z0: number; - x1: number; - y1: number; - z1: number; - fftCount: number; - fftTimes: number[]; - ffts: [][]; - slices: FrequencyBandsStruct; - means: FrequencyBandsStruct; - startTime: number | string; - tag?: string | number; -} & Struct; -export type FNIRSStruct = { - position: { - x: number; - y: number; - z: number; - }; - count: number; - times: number[]; - red: number[]; - ir: number[]; - ir2: number[]; - ambient: number[]; - ratio: number[]; - temp: number[]; - beat_detect: { - beats: any[]; - breaths: any[]; - rir: any[]; - rir2: any[]; - drir_dt: any[]; - localmins: any[]; - localmaxs: any[]; - val_dists: any[]; - peak_dists: any[]; - localmins2: any[]; - localmaxs2: any[]; - val_dists2: any[]; - peak_dists2: any[]; - }; - startTime: number | string; - tag?: string | number; -} & Struct; -export type IMUStruct = { - Ax: number[]; - Ay: number[]; - Az: number[]; - Gx: number[]; - Gy: number[]; - Gz: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type EyeTrackerStruct = { - count: number; - times: number[]; - x: number[]; - y: number[]; - smax: number[]; - smay: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type ECGStruct = { - count: number; - times: number[]; - raw: number[]; - filtered: number[]; - bpm: number[]; - hrv: number[]; - startTime: number | string; - tag?: string | number; -} & Struct; -export type PPGStruct = FNIRSStruct; -export type HRVStruct = ECGStruct; -export type EMGStruct = EEGStruct; -export {}; diff --git a/src/extras/dist/extras/struct/genTimestamps.d.ts b/src/extras/dist/extras/struct/genTimestamps.d.ts deleted file mode 100644 index 69253e3d..00000000 --- a/src/extras/dist/extras/struct/genTimestamps.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type TimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' | 'decade' | 'century' | 'millennium' | 'microsecond' | 'nanosecond'; -type Plural = `${T}s`; -export type TimeSpecifier = `now` | `last ${string} ${Plural}` | `last ${TimeUnit}`; -export declare let defaultSpecifiers: (TimeUnit | "now")[]; -export declare function genTimeSpecifiers(specifiers?: (TimeUnit | "now")[]): string[]; -export declare function genTimestampFromString(specifier: TimeSpecifier): number; -export {}; diff --git a/src/extras/dist/extras/webgl-plot/webglplot.routes.d.ts b/src/extras/dist/extras/webgl-plot/webglplot.routes.d.ts deleted file mode 100644 index 26ef2e6b..00000000 --- a/src/extras/dist/extras/webgl-plot/webglplot.routes.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { WorkerInfo } from '../../services/worker/Worker.service'; -import { WebglLinePlotInfo, WebglLinePlotProps, WebglLinePlotUtil, WebglLineProps } from "webgl-plot-utils"; -import { FilterSettings } from "../algorithms/util/BiquadFilters"; -export { WebglLinePlotUtil, WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo }; -export declare const webglPlotRoutes: { - setupChart: (settings: WebglLinePlotProps) => any; - updateChartData: (plot: WebglLinePlotInfo | string, lines?: { - [key: string]: number[] | WebglLineProps | { - [key: string]: any; - values: number[]; - }; - }, draw?: boolean) => boolean; - clearChart: (plot: WebglLinePlotInfo | string) => boolean; - resetChart: (plot: WebglLinePlotInfo | string, settings: WebglLinePlotProps) => any; - getChartSettings: (plotId: any) => any; -}; -export declare function setSignalControls(controlsDiv: HTMLElement, plotId: string, streamworker: WorkerInfo, chartworker: WorkerInfo, chartSettings: Partial, filterSettings: FilterSettings): Promise; diff --git a/src/extras/dist/index.gpu.services.d.ts b/src/extras/dist/index.gpu.services.d.ts deleted file mode 100644 index ab57cca9..00000000 --- a/src/extras/dist/index.gpu.services.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './extras/gpu/GPU.service'; -export { gpualgorithms } from './extras/algorithms/index.gpu'; diff --git a/src/extras/dist/index.services.esm.js b/src/extras/dist/index.services.esm.js deleted file mode 100644 index 46e6014b..00000000 --- a/src/extras/dist/index.services.esm.js +++ /dev/null @@ -1,50 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x3=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x3,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x3)(function(x3){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x3+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_bson=__commonJS({"struct/datastructures/bson.cjs"(exports){"use strict";var BSON_MAJOR_VERSION=5;var BSON_INT32_MAX=2147483647;var BSON_INT32_MIN=-2147483648;var BSON_INT64_MAX=Math.pow(2,63)-1;var BSON_INT64_MIN=-Math.pow(2,63);var JS_INT_MAX=Math.pow(2,53);var JS_INT_MIN=-Math.pow(2,53);var BSON_DATA_NUMBER=1;var BSON_DATA_STRING=2;var BSON_DATA_OBJECT=3;var BSON_DATA_ARRAY=4;var BSON_DATA_BINARY=5;var BSON_DATA_UNDEFINED=6;var BSON_DATA_OID=7;var BSON_DATA_BOOLEAN=8;var BSON_DATA_DATE=9;var BSON_DATA_NULL=10;var BSON_DATA_REGEXP=11;var BSON_DATA_DBPOINTER=12;var BSON_DATA_CODE=13;var BSON_DATA_SYMBOL=14;var BSON_DATA_CODE_W_SCOPE=15;var BSON_DATA_INT=16;var BSON_DATA_TIMESTAMP=17;var BSON_DATA_LONG=18;var BSON_DATA_DECIMAL128=19;var BSON_DATA_MIN_KEY=255;var BSON_DATA_MAX_KEY=127;var BSON_BINARY_SUBTYPE_DEFAULT=0;var BSON_BINARY_SUBTYPE_UUID_NEW=4;var BSONType=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});var BSONError=class extends Error{get bsonError(){return true}get name(){return"BSONError"}constructor(message){super(message)}static isBSONError(value){return value!=null&&typeof value==="object"&&"bsonError"in value&&value.bsonError===true&&"name"in value&&"message"in value&&"stack"in value}};var BSONVersionError=class extends BSONError{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`)}};var BSONRuntimeError=class extends BSONError{get name(){return"BSONRuntimeError"}constructor(message){super(message)}};function nodejsMathRandomBytes(byteLength){return nodeJsByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var nodejsRandomBytes=(()=>{try{return __require("crypto").randomBytes}catch{return nodejsMathRandomBytes}})();var nodeJsByteUtils={toLocalBufferType(potentialBuffer){if(Buffer.isBuffer(potentialBuffer)){return potentialBuffer}if(ArrayBuffer.isView(potentialBuffer)){return Buffer.from(potentialBuffer.buffer,potentialBuffer.byteOffset,potentialBuffer.byteLength)}const stringTag=potentialBuffer?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialBuffer);if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return Buffer.from(potentialBuffer)}throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`)},allocate(size){return Buffer.alloc(size)},equals(a,b){return nodeJsByteUtils.toLocalBufferType(a).equals(b)},fromNumberArray(array){return Buffer.from(array)},fromBase64(base64){return Buffer.from(base64,"base64")},toBase64(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64")},fromISO88591(codePoints){return Buffer.from(codePoints,"binary")},toISO88591(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary")},fromHex(hex){return Buffer.from(hex,"hex")},toHex(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex")},fromUTF8(text){return Buffer.from(text,"utf8")},toUTF8(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8")},utf8ByteLength(input){return Buffer.byteLength(input,"utf8")},encodeUTF8Into(buffer2,source,byteOffset){return nodeJsByteUtils.toLocalBufferType(buffer2).write(source,byteOffset,void 0,"utf8")},randomBytes:nodejsRandomBytes};function isReactNative(){const{navigator}=globalThis;return typeof navigator==="object"&&navigator.product==="ReactNative"}function webMathRandomBytes(byteLength){if(byteLength<0){throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`)}return webByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var webRandomBytes=(()=>{const{crypto}=globalThis;if(crypto!=null&&typeof crypto.getRandomValues==="function"){return byteLength=>{return crypto.getRandomValues(webByteUtils.allocate(byteLength))}}else{if(isReactNative()){const{console:console2}=globalThis;console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return webMathRandomBytes}})();var HEX_DIGIT=/(\d|[a-f])/i;var webByteUtils={toLocalBufferType(potentialUint8array){const stringTag=potentialUint8array?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialUint8array);if(stringTag==="Uint8Array"){return potentialUint8array}if(ArrayBuffer.isView(potentialUint8array)){return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset,potentialUint8array.byteOffset+potentialUint8array.byteLength))}if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return new Uint8Array(potentialUint8array)}throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`)},allocate(size){if(typeof size!=="number"){throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`)}return new Uint8Array(size)},equals(a,b){if(a.byteLength!==b.byteLength){return false}for(let i=0;ic.charCodeAt(0))},toBase64(uint8array){return btoa(webByteUtils.toISO88591(uint8array))},fromISO88591(codePoints){return Uint8Array.from(codePoints,c=>c.charCodeAt(0)&255)},toISO88591(uint8array){return Array.from(Uint16Array.from(uint8array),b=>String.fromCharCode(b)).join("")},fromHex(hex){const evenLengthHex=hex.length%2===0?hex:hex.slice(0,hex.length-1);const buffer2=[];for(let i=0;ibyte.toString(16).padStart(2,"0")).join("")},fromUTF8(text){return new TextEncoder().encode(text)},toUTF8(uint8array){return new TextDecoder("utf8",{fatal:false}).decode(uint8array)},utf8ByteLength(input){return webByteUtils.fromUTF8(input).byteLength},encodeUTF8Into(buffer2,source,byteOffset){const bytes=webByteUtils.fromUTF8(source);buffer2.set(bytes,byteOffset);return bytes.byteLength},randomBytes:webRandomBytes};var hasGlobalBuffer=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==true;var ByteUtils=hasGlobalBuffer?nodeJsByteUtils:webByteUtils;var BSONDataView=class extends DataView{static fromUint8Array(input){return new DataView(input.buffer,input.byteOffset,input.byteLength)}};var VALIDATION_REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;var uuidValidateString=str2=>typeof str2==="string"&&VALIDATION_REGEX.test(str2);var uuidHexStringToBuffer=hexString=>{if(!uuidValidateString(hexString)){throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".')}const sanitizedHexString=hexString.replace(/-/g,"");return ByteUtils.fromHex(sanitizedHexString)};function bufferToUuidHexString(buffer2,includeDashes=true){if(includeDashes){return[ByteUtils.toHex(buffer2.subarray(0,4)),ByteUtils.toHex(buffer2.subarray(4,6)),ByteUtils.toHex(buffer2.subarray(6,8)),ByteUtils.toHex(buffer2.subarray(8,10)),ByteUtils.toHex(buffer2.subarray(10,16))].join("-")}return ByteUtils.toHex(buffer2)}function isAnyArrayBuffer(value){return["[object ArrayBuffer]","[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value))}function isUint8Array(value){return Object.prototype.toString.call(value)==="[object Uint8Array]"}function isRegExp(d2){return Object.prototype.toString.call(d2)==="[object RegExp]"}function isMap(d2){return Object.prototype.toString.call(d2)==="[object Map]"}function isDate(d2){return Object.prototype.toString.call(d2)==="[object Date]"}var BSONValue=class{get[Symbol.for("@@mdb.bson.version")](){return BSON_MAJOR_VERSION}};var Binary=class _Binary extends BSONValue{get _bsontype(){return"Binary"}constructor(buffer2,subType){super();if(!(buffer2==null)&&!(typeof buffer2==="string")&&!ArrayBuffer.isView(buffer2)&&!(buffer2 instanceof ArrayBuffer)&&!Array.isArray(buffer2)){throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array")}this.sub_type=subType??_Binary.BSON_BINARY_SUBTYPE_DEFAULT;if(buffer2==null){this.buffer=ByteUtils.allocate(_Binary.BUFFER_SIZE);this.position=0}else{if(typeof buffer2==="string"){this.buffer=ByteUtils.fromISO88591(buffer2)}else if(Array.isArray(buffer2)){this.buffer=ByteUtils.fromNumberArray(buffer2)}else{this.buffer=ByteUtils.toLocalBufferType(buffer2)}this.position=this.buffer.byteLength}}put(byteValue){if(typeof byteValue==="string"&&byteValue.length!==1){throw new BSONError("only accepts single character String")}else if(typeof byteValue!=="number"&&byteValue.length!==1)throw new BSONError("only accepts single character Uint8Array or Array");let decodedByte;if(typeof byteValue==="string"){decodedByte=byteValue.charCodeAt(0)}else if(typeof byteValue==="number"){decodedByte=byteValue}else{decodedByte=byteValue[0]}if(decodedByte<0||decodedByte>255){throw new BSONError("only accepts number in a valid unsigned byte range 0-255")}if(this.buffer.byteLength>this.position){this.buffer[this.position++]=decodedByte}else{const newSpace=ByteUtils.allocate(_Binary.BUFFER_SIZE+this.buffer.length);newSpace.set(this.buffer,0);this.buffer=newSpace;this.buffer[this.position++]=decodedByte}}write(sequence,offset){offset=typeof offset==="number"?offset:this.position;if(this.buffer.byteLengththis.position?offset+sequence.length:this.position}else if(typeof sequence==="string"){const bytes=ByteUtils.fromISO88591(sequence);this.buffer.set(bytes,offset);this.position=offset+sequence.length>this.position?offset+sequence.length:this.position}}read(position,length){length=length&&length>0?length:this.position;return this.buffer.slice(position,position+length)}value(asRaw){asRaw=!!asRaw;if(asRaw&&this.buffer.length===this.position){return this.buffer}if(asRaw){return this.buffer.slice(0,this.position)}return ByteUtils.toISO88591(this.buffer.subarray(0,this.position))}length(){return this.position}toJSON(){return ByteUtils.toBase64(this.buffer)}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.buffer);if(encoding==="base64")return ByteUtils.toBase64(this.buffer);if(encoding==="utf8"||encoding==="utf-8")return ByteUtils.toUTF8(this.buffer);return ByteUtils.toUTF8(this.buffer)}toExtendedJSON(options){options=options||{};const base64String=ByteUtils.toBase64(this.buffer);const subType=Number(this.sub_type).toString(16);if(options.legacy){return{$binary:base64String,$type:subType.length===1?"0"+subType:subType}}return{$binary:{base64:base64String,subType:subType.length===1?"0"+subType:subType}}}toUUID(){if(this.sub_type===_Binary.SUBTYPE_UUID){return new UUID(this.buffer.slice(0,this.position))}throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`)}static fromExtendedJSON(doc,options){options=options||{};let data;let type;if("$binary"in doc){if(options.legacy&&typeof doc.$binary==="string"&&"$type"in doc){type=doc.$type?parseInt(doc.$type,16):0;data=ByteUtils.fromBase64(doc.$binary)}else{if(typeof doc.$binary!=="string"){type=doc.$binary.subType?parseInt(doc.$binary.subType,16):0;data=ByteUtils.fromBase64(doc.$binary.base64)}}}else if("$uuid"in doc){type=4;data=uuidHexStringToBuffer(doc.$uuid)}if(!data){throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`)}return type===BSON_BINARY_SUBTYPE_UUID_NEW?new UUID(data):new _Binary(data,type)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`}};Binary.BSON_BINARY_SUBTYPE_DEFAULT=0;Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_ENCRYPTED=6;Binary.SUBTYPE_COLUMN=7;Binary.SUBTYPE_USER_DEFINED=128;var UUID_BYTE_LENGTH=16;var UUID=class _UUID extends Binary{constructor(input){let bytes;let hexStr;if(input==null){bytes=_UUID.generate()}else if(input instanceof _UUID){bytes=ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));hexStr=input.__id}else if(ArrayBuffer.isView(input)&&input.byteLength===UUID_BYTE_LENGTH){bytes=ByteUtils.toLocalBufferType(input)}else if(typeof input==="string"){bytes=uuidHexStringToBuffer(input)}else{throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).")}super(bytes,BSON_BINARY_SUBTYPE_UUID_NEW);this.__id=hexStr}get id(){return this.buffer}set id(value){this.buffer=value;if(_UUID.cacheHexString){this.__id=bufferToUuidHexString(value)}}toHexString(includeDashes=true){if(_UUID.cacheHexString&&this.__id){return this.__id}const uuidHexString=bufferToUuidHexString(this.id,includeDashes);if(_UUID.cacheHexString){this.__id=uuidHexString}return uuidHexString}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.id);if(encoding==="base64")return ByteUtils.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(!otherId){return false}if(otherId instanceof _UUID){return ByteUtils.equals(otherId.id,this.id)}try{return ByteUtils.equals(new _UUID(otherId).id,this.id)}catch{return false}}toBinary(){return new Binary(this.id,Binary.SUBTYPE_UUID)}static generate(){const bytes=ByteUtils.randomBytes(UUID_BYTE_LENGTH);bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return bytes}static isValid(input){if(!input){return false}if(input instanceof _UUID){return true}if(typeof input==="string"){return uuidValidateString(input)}if(isUint8Array(input)){if(input.byteLength!==UUID_BYTE_LENGTH){return false}return(input[6]&240)===64&&(input[8]&128)===128}return false}static createFromHexString(hexString){const buffer2=uuidHexStringToBuffer(hexString);return new _UUID(buffer2)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new UUID("${this.toHexString()}")`}};var Code=class _Code extends BSONValue{get _bsontype(){return"Code"}constructor(code,scope){super();this.code=code.toString();this.scope=scope??null}toJSON(){if(this.scope!=null){return{code:this.code,scope:this.scope}}return{code:this.code}}toExtendedJSON(){if(this.scope){return{$code:this.code,$scope:this.scope}}return{$code:this.code}}static fromExtendedJSON(doc){return new _Code(doc.$code,doc.$scope)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const codeJson=this.toJSON();return`new Code("${String(codeJson.code)}"${codeJson.scope!=null?`, ${JSON.stringify(codeJson.scope)}`:""})`}};function isDBRefLike(value){return value!=null&&typeof value==="object"&&"$id"in value&&value.$id!=null&&"$ref"in value&&typeof value.$ref==="string"&&(!("$db"in value)||"$db"in value&&typeof value.$db==="string")}var DBRef=class _DBRef extends BSONValue{get _bsontype(){return"DBRef"}constructor(collection,oid,db,fields){super();const parts=collection.split(".");if(parts.length===2){db=parts.shift();collection=parts.shift()}this.collection=collection;this.oid=oid;this.db=db;this.fields=fields||{}}get namespace(){return this.collection}set namespace(value){this.collection=value}toJSON(){const o=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)o.$db=this.db;return o}toExtendedJSON(options){options=options||{};let o={$ref:this.collection,$id:this.oid};if(options.legacy){return o}if(this.db)o.$db=this.db;o=Object.assign(o,this.fields);return o}static fromExtendedJSON(doc){const copy=Object.assign({},doc);delete copy.$ref;delete copy.$id;delete copy.$db;return new _DBRef(doc.$ref,doc.$id,doc.$db,copy)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const oid=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return`new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db?`, "${this.db}"`:""})`}};var wasm=void 0;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var INT_CACHE={};var UINT_CACHE={};var MAX_INT64_STRING_LENGTH=20;var DECIMAL_REG_EX=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;var Long=class _Long extends BSONValue{get _bsontype(){return"Long"}get __isLong__(){return true}constructor(low=0,high,unsigned){super();if(typeof low==="bigint"){Object.assign(this,_Long.fromBigInt(low,!!high))}else if(typeof low==="string"){Object.assign(this,_Long.fromString(low,!!high))}else{this.low=low|0;this.high=high|0;this.unsigned=!!unsigned}}static fromBits(lowBits,highBits,unsigned){return new _Long(lowBits,highBits,unsigned)}static fromInt(value,unsigned){let obj,cachedObj,cache;if(unsigned){value>>>=0;if(cache=0<=value&&value<256){cachedObj=UINT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,(value|0)<0?-1:0,true);if(cache)UINT_CACHE[value]=obj;return obj}else{value|=0;if(cache=-128<=value&&value<128){cachedObj=INT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,value<0?-1:0,false);if(cache)INT_CACHE[value]=obj;return obj}}static fromNumber(value,unsigned){if(isNaN(value))return unsigned?_Long.UZERO:_Long.ZERO;if(unsigned){if(value<0)return _Long.UZERO;if(value>=TWO_PWR_64_DBL)return _Long.MAX_UNSIGNED_VALUE}else{if(value<=-TWO_PWR_63_DBL)return _Long.MIN_VALUE;if(value+1>=TWO_PWR_63_DBL)return _Long.MAX_VALUE}if(value<0)return _Long.fromNumber(-value,unsigned).neg();return _Long.fromBits(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0,unsigned)}static fromBigInt(value,unsigned){return _Long.fromString(value.toString(),unsigned)}static fromString(str2,unsigned,radix){if(str2.length===0)throw new BSONError("empty string");if(str2==="NaN"||str2==="Infinity"||str2==="+Infinity"||str2==="-Infinity")return _Long.ZERO;if(typeof unsigned==="number"){radix=unsigned,unsigned=false}else{unsigned=!!unsigned}radix=radix||10;if(radix<2||360)throw new BSONError("interior hyphen");else if(p2===0){return _Long.fromString(str2.substring(1),unsigned,radix).neg()}const radixToPower=_Long.fromNumber(Math.pow(radix,8));let result=_Long.ZERO;for(let i=0;i>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=addend.high>>>16;const b32=addend.high&65535;const b16=addend.low>>>16;const b00=addend.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}and(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low&other.low,this.high&other.high,this.unsigned)}compare(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.eq(other))return 0;const thisNeg=this.isNegative(),otherNeg=other.isNegative();if(thisNeg&&!otherNeg)return-1;if(!thisNeg&&otherNeg)return 1;if(!this.unsigned)return this.sub(other).isNegative()?-1:1;return other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}comp(other){return this.compare(other)}divide(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(divisor.isZero())throw new BSONError("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&divisor.low===-1&&divisor.high===-1){return this}const low=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?_Long.UZERO:_Long.ZERO;let approx,rem,res;if(!this.unsigned){if(this.eq(_Long.MIN_VALUE)){if(divisor.eq(_Long.ONE)||divisor.eq(_Long.NEG_ONE))return _Long.MIN_VALUE;else if(divisor.eq(_Long.MIN_VALUE))return _Long.ONE;else{const halfThis=this.shr(1);approx=halfThis.div(divisor).shl(1);if(approx.eq(_Long.ZERO)){return divisor.isNegative()?_Long.ONE:_Long.NEG_ONE}else{rem=this.sub(divisor.mul(approx));res=approx.add(rem.div(divisor));return res}}}else if(divisor.eq(_Long.MIN_VALUE))return this.unsigned?_Long.UZERO:_Long.ZERO;if(this.isNegative()){if(divisor.isNegative())return this.neg().div(divisor.neg());return this.neg().div(divisor).neg()}else if(divisor.isNegative())return this.div(divisor.neg()).neg();res=_Long.ZERO}else{if(!divisor.unsigned)divisor=divisor.toUnsigned();if(divisor.gt(this))return _Long.UZERO;if(divisor.gt(this.shru(1)))return _Long.UONE;res=_Long.UZERO}rem=this;while(rem.gte(divisor)){approx=Math.max(1,Math.floor(rem.toNumber()/divisor.toNumber()));const log2=Math.ceil(Math.log(approx)/Math.LN2);const delta=log2<=48?1:Math.pow(2,log2-48);let approxRes=_Long.fromNumber(approx);let approxRem=approxRes.mul(divisor);while(approxRem.isNegative()||approxRem.gt(rem)){approx-=delta;approxRes=_Long.fromNumber(approx,this.unsigned);approxRem=approxRes.mul(divisor)}if(approxRes.isZero())approxRes=_Long.ONE;res=res.add(approxRes);rem=rem.sub(approxRem)}return res}div(divisor){return this.divide(divisor)}equals(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.unsigned!==other.unsigned&&this.high>>>31===1&&other.high>>>31===1)return false;return this.high===other.high&&this.low===other.low}eq(other){return this.equals(other)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative()){return this.eq(_Long.MIN_VALUE)?64:this.neg().getNumBitsAbs()}const val=this.high!==0?this.high:this.low;let bit;for(bit=31;bit>0;bit--)if((val&1<0}gt(other){return this.greaterThan(other)}greaterThanOrEqual(other){return this.comp(other)>=0}gte(other){return this.greaterThanOrEqual(other)}ge(other){return this.greaterThanOrEqual(other)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(other){return this.comp(other)<0}lt(other){return this.lessThan(other)}lessThanOrEqual(other){return this.comp(other)<=0}lte(other){return this.lessThanOrEqual(other)}modulo(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(wasm){const low=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}return this.sub(this.div(divisor).mul(divisor))}mod(divisor){return this.modulo(divisor)}rem(divisor){return this.modulo(divisor)}multiply(multiplier){if(this.isZero())return _Long.ZERO;if(!_Long.isLong(multiplier))multiplier=_Long.fromValue(multiplier);if(wasm){const low=wasm.mul(this.low,this.high,multiplier.low,multiplier.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(multiplier.isZero())return _Long.ZERO;if(this.eq(_Long.MIN_VALUE))return multiplier.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(multiplier.eq(_Long.MIN_VALUE))return this.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(this.isNegative()){if(multiplier.isNegative())return this.neg().mul(multiplier.neg());else return this.neg().mul(multiplier).neg()}else if(multiplier.isNegative())return this.mul(multiplier.neg()).neg();if(this.lt(_Long.TWO_PWR_24)&&multiplier.lt(_Long.TWO_PWR_24))return _Long.fromNumber(this.toNumber()*multiplier.toNumber(),this.unsigned);const a48=this.high>>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=multiplier.high>>>16;const b32=multiplier.high&65535;const b16=multiplier.low>>>16;const b00=multiplier.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}mul(multiplier){return this.multiply(multiplier)}negate(){if(!this.unsigned&&this.eq(_Long.MIN_VALUE))return _Long.MIN_VALUE;return this.not().add(_Long.ONE)}neg(){return this.negate()}not(){return _Long.fromBits(~this.low,~this.high,this.unsigned)}notEquals(other){return!this.equals(other)}neq(other){return this.notEquals(other)}ne(other){return this.notEquals(other)}or(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low|other.low,this.high|other.high,this.unsigned)}shiftLeft(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();if((numBits&=63)===0)return this;else if(numBits<32)return _Long.fromBits(this.low<>>32-numBits,this.unsigned);else return _Long.fromBits(0,this.low<>>numBits|this.high<<32-numBits,this.high>>numBits,this.unsigned);else return _Long.fromBits(this.high>>numBits-32,this.high>=0?0:-1,this.unsigned)}shr(numBits){return this.shiftRight(numBits)}shiftRightUnsigned(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();numBits&=63;if(numBits===0)return this;else{const high=this.high;if(numBits<32){const low=this.low;return _Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits,this.unsigned)}else if(numBits===32)return _Long.fromBits(high,0,this.unsigned);else return _Long.fromBits(high>>>numBits-32,0,this.unsigned)}}shr_u(numBits){return this.shiftRightUnsigned(numBits)}shru(numBits){return this.shiftRightUnsigned(numBits)}subtract(subtrahend){if(!_Long.isLong(subtrahend))subtrahend=_Long.fromValue(subtrahend);return this.add(subtrahend.neg())}sub(subtrahend){return this.subtract(subtrahend)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(le){return le?this.toBytesLE():this.toBytesBE()}toBytesLE(){const hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}toBytesBE(){const hi=this.high,lo=this.low;return[hi>>>24,hi>>>16&255,hi>>>8&255,hi&255,lo>>>24,lo>>>16&255,lo>>>8&255,lo&255]}toSigned(){if(!this.unsigned)return this;return _Long.fromBits(this.low,this.high,false)}toString(radix){radix=radix||10;if(radix<2||36>>0;let digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6)digits="0"+digits;result=""+digits+result}}}toUnsigned(){if(this.unsigned)return this;return _Long.fromBits(this.low,this.high,true)}xor(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low^other.low,this.high^other.high,this.unsigned)}eqz(){return this.isZero()}le(other){return this.lessThanOrEqual(other)}toExtendedJSON(options){if(options&&options.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(doc,options){const{useBigInt64=false,relaxed=true}={...options};if(doc.$numberLong.length>MAX_INT64_STRING_LENGTH){throw new BSONError("$numberLong string is too long")}if(!DECIMAL_REG_EX.test(doc.$numberLong)){throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`)}if(useBigInt64){const bigIntResult=BigInt(doc.$numberLong);return BigInt.asIntN(64,bigIntResult)}const longResult=_Long.fromString(doc.$numberLong);if(relaxed){return longResult.toNumber()}return longResult}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Long("${this.toString()}"${this.unsigned?", true":""})`}};Long.TWO_PWR_24=Long.fromInt(TWO_PWR_24_DBL);Long.MAX_UNSIGNED_VALUE=Long.fromBits(4294967295|0,4294967295|0,true);Long.ZERO=Long.fromInt(0);Long.UZERO=Long.fromInt(0,true);Long.ONE=Long.fromInt(1);Long.UONE=Long.fromInt(1,true);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0,false);Long.MIN_VALUE=Long.fromBits(0,2147483648|0,false);var PARSE_STRING_REGEXP=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var PARSE_INF_REGEXP=/^(\+|-)?(Infinity|inf)$/i;var PARSE_NAN_REGEXP=/^(\+|-)?NaN$/i;var EXPONENT_MAX=6111;var EXPONENT_MIN=-6176;var EXPONENT_BIAS=6176;var MAX_DIGITS=34;var NAN_BUFFER=ByteUtils.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_NEGATIVE_BUFFER=ByteUtils.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_POSITIVE_BUFFER=ByteUtils.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var EXPONENT_REGEX=/^([-+])?(\d+)?$/;var COMBINATION_MASK=31;var EXPONENT_MASK=16383;var COMBINATION_INFINITY=30;var COMBINATION_NAN=31;function isDigit(value){return!isNaN(parseInt(value,10))}function divideu128(value){const DIVISOR=Long.fromNumber(1e3*1e3*1e3);let _rem=Long.fromNumber(0);if(!value.parts[0]&&!value.parts[1]&&!value.parts[2]&&!value.parts[3]){return{quotient:value,rem:_rem}}for(let i=0;i<=3;i++){_rem=_rem.shiftLeft(32);_rem=_rem.add(new Long(value.parts[i],0));value.parts[i]=_rem.div(DIVISOR).low;_rem=_rem.modulo(DIVISOR)}return{quotient:value,rem:_rem}}function multiply64x2(left,right){if(!left&&!right){return{high:Long.fromNumber(0),low:Long.fromNumber(0)}}const leftHigh=left.shiftRightUnsigned(32);const leftLow=new Long(left.getLowBits(),0);const rightHigh=right.shiftRightUnsigned(32);const rightLow=new Long(right.getLowBits(),0);let productHigh=leftHigh.multiply(rightHigh);let productMid=leftHigh.multiply(rightLow);const productMid2=leftLow.multiply(rightHigh);let productLow=leftLow.multiply(rightLow);productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productMid=new Long(productMid.getLowBits(),0).add(productMid2).add(productLow.shiftRightUnsigned(32));productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productLow=productMid.shiftLeft(32).add(new Long(productLow.getLowBits(),0));return{high:productHigh,low:productLow}}function lessThan(left,right){const uhleft=left.high>>>0;const uhright=right.high>>>0;if(uhleft>>0;const ulright=right.low>>>0;if(ulleft=7e3){throw new BSONError(""+representation+" not a valid Decimal128 string")}const stringMatch=representation.match(PARSE_STRING_REGEXP);const infMatch=representation.match(PARSE_INF_REGEXP);const nanMatch=representation.match(PARSE_NAN_REGEXP);if(!stringMatch&&!infMatch&&!nanMatch||representation.length===0){throw new BSONError(""+representation+" not a valid Decimal128 string")}if(stringMatch){const unsignedNumber=stringMatch[2];const e=stringMatch[4];const expSign=stringMatch[5];const expNumber=stringMatch[6];if(e&&expNumber===void 0)invalidErr(representation,"missing exponent power");if(e&&unsignedNumber===void 0)invalidErr(representation,"missing exponent base");if(e===void 0&&(expSign||expNumber)){invalidErr(representation,"missing e before exponent")}}if(representation[index]==="+"||representation[index]==="-"){isNegative=representation[index++]==="-"}if(!isDigit(representation[index])&&representation[index]!=="."){if(representation[index]==="i"||representation[index]==="I"){return new _Decimal128(isNegative?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER)}else if(representation[index]==="N"){return new _Decimal128(NAN_BUFFER)}}while(isDigit(representation[index])||representation[index]==="."){if(representation[index]==="."){if(sawRadix)invalidErr(representation,"contains multiple periods");sawRadix=true;index=index+1;continue}if(nDigitsStored<34){if(representation[index]!=="0"||foundNonZero){if(!foundNonZero){firstNonZero=nDigitsRead}foundNonZero=true;digits[digitsInsert++]=parseInt(representation[index],10);nDigitsStored=nDigitsStored+1}}if(foundNonZero)nDigits=nDigits+1;if(sawRadix)radixPosition=radixPosition+1;nDigitsRead=nDigitsRead+1;index=index+1}if(sawRadix&&!nDigitsRead)throw new BSONError(""+representation+" not a valid Decimal128 string");if(representation[index]==="e"||representation[index]==="E"){const match=representation.substr(++index).match(EXPONENT_REGEX);if(!match||!match[2])return new _Decimal128(NAN_BUFFER);exponent=parseInt(match[0],10);index=index+match[0].length}if(representation[index])return new _Decimal128(NAN_BUFFER);firstDigit=0;if(!nDigitsStored){firstDigit=0;lastDigit=0;digits[0]=0;nDigits=1;nDigitsStored=1;significantDigits=0}else{lastDigit=nDigitsStored-1;significantDigits=nDigits;if(significantDigits!==1){while(digits[firstNonZero+significantDigits-1]===0){significantDigits=significantDigits-1}}}if(exponent<=radixPosition&&radixPosition-exponent>1<<14){exponent=EXPONENT_MIN}else{exponent=exponent-radixPosition}while(exponent>EXPONENT_MAX){lastDigit=lastDigit+1;if(lastDigit-firstDigit>MAX_DIGITS){const digitsString=digits.join("");if(digitsString.match(/^0+$/)){exponent=EXPONENT_MAX;break}invalidErr(representation,"overflow")}exponent=exponent-1}while(exponent=5){roundBit=1;if(roundDigit===5){roundBit=digits[lastDigit]%2===1?1:0;for(i=firstNonZero+lastDigit+2;i=0;dIdx--){if(++digits[dIdx]>9){digits[dIdx]=0;if(dIdx===0){if(exponent>8&255;buffer2[index++]=dec.low.low>>16&255;buffer2[index++]=dec.low.low>>24&255;buffer2[index++]=dec.low.high&255;buffer2[index++]=dec.low.high>>8&255;buffer2[index++]=dec.low.high>>16&255;buffer2[index++]=dec.low.high>>24&255;buffer2[index++]=dec.high.low&255;buffer2[index++]=dec.high.low>>8&255;buffer2[index++]=dec.high.low>>16&255;buffer2[index++]=dec.high.low>>24&255;buffer2[index++]=dec.high.high&255;buffer2[index++]=dec.high.high>>8&255;buffer2[index++]=dec.high.high>>16&255;buffer2[index++]=dec.high.high>>24&255;return new _Decimal128(buffer2)}toString(){let biased_exponent;let significand_digits=0;const significand=new Array(36);for(let i=0;i>26&COMBINATION_MASK;if(combination>>3===3){if(combination===COMBINATION_INFINITY){return string.join("")+"Infinity"}else if(combination===COMBINATION_NAN){return"NaN"}else{biased_exponent=high>>15&EXPONENT_MASK;significand_msb=8+(high>>14&1)}}else{significand_msb=high>>14&7;biased_exponent=high>>17&EXPONENT_MASK}const exponent=biased_exponent-EXPONENT_BIAS;significand128.parts[0]=(high&16383)+((significand_msb&15)<<14);significand128.parts[1]=midh;significand128.parts[2]=midl;significand128.parts[3]=low;if(significand128.parts[0]===0&&significand128.parts[1]===0&&significand128.parts[2]===0&&significand128.parts[3]===0){is_zero=true}else{for(k=3;k>=0;k--){let least_digits=0;const result=divideu128(significand128);significand128=result.quotient;least_digits=result.rem.low;if(!least_digits)continue;for(j=8;j>=0;j--){significand[k*9+j]=least_digits%10;least_digits=Math.floor(least_digits/10)}}}if(is_zero){significand_digits=1;significand[index]=0}else{significand_digits=36;while(!significand[index]){significand_digits=significand_digits-1;index=index+1}}const scientific_exponent=significand_digits-1+exponent;if(scientific_exponent>=34||scientific_exponent<=-7||exponent>0){if(significand_digits>34){string.push(`${0}`);if(exponent>0)string.push(`E+${exponent}`);else if(exponent<0)string.push(`E${exponent}`);return string.join("")}string.push(`${significand[index++]}`);significand_digits=significand_digits-1;if(significand_digits){string.push(".")}for(let i=0;i0){string.push(`+${scientific_exponent}`)}else{string.push(`${scientific_exponent}`)}}else{if(exponent>=0){for(let i=0;i0){for(let i=0;i>8&255;buffer2[9]=inc>>16&255;return buffer2}toString(encoding){if(encoding==="base64")return ByteUtils.toBase64(this.id);if(encoding==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(otherId===void 0||otherId===null){return false}if(otherId instanceof _ObjectId){return this[kId][11]===otherId[kId][11]&&ByteUtils.equals(this[kId],otherId[kId])}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12&&isUint8Array(this.id)){return ByteUtils.equals(this.id,ByteUtils.fromISO88591(otherId))}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===24){return otherId.toLowerCase()===this.toHexString()}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12){return ByteUtils.equals(ByteUtils.fromUTF8(otherId),this.id)}if(typeof otherId==="object"&&"toHexString"in otherId&&typeof otherId.toHexString==="function"){const otherIdString=otherId.toHexString();const thisIdString=this.toHexString().toLowerCase();return typeof otherIdString==="string"&&otherIdString.toLowerCase()===thisIdString}return false}getTimestamp(){const timestamp=new Date;const time=BSONDataView.fromUint8Array(this.id).getUint32(0,false);timestamp.setTime(Math.floor(time)*1e3);return timestamp}static createPk(){return new _ObjectId}static createFromTime(time){const buffer2=ByteUtils.fromNumberArray([0,0,0,0,0,0,0,0,0,0,0,0]);BSONDataView.fromUint8Array(buffer2).setUint32(0,time,false);return new _ObjectId(buffer2)}static createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new BSONError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}return new _ObjectId(ByteUtils.fromHex(hexString))}static isValid(id){if(id==null)return false;try{new _ObjectId(id);return true}catch{return false}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(doc){return new _ObjectId(doc.$oid)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new ObjectId("${this.toHexString()}")`}};ObjectId2.index=Math.floor(Math.random()*16777215);function internalCalculateObjectSize(object,serializeFunctions,ignoreUndefined){let totalLength=4+1;if(Array.isArray(object)){for(let i=0;i=JS_INT_MIN&&value<=JS_INT_MAX){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(4+1)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1;return 0;case"boolean":return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+1);case"object":if(value!=null&&typeof value._bsontype==="string"&&value[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(value==null||value._bsontype==="MinKey"||value._bsontype==="MaxKey"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1}else if(value._bsontype==="ObjectId"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(ArrayBuffer.isView(value)||value instanceof ArrayBuffer||isAnyArrayBuffer(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+4+1)+value.byteLength}else if(value._bsontype==="Long"||value._bsontype==="Double"||value._bsontype==="Timestamp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(value._bsontype==="Decimal128"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(16+1)}else if(value._bsontype==="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+4+ByteUtils.utf8ByteLength(value.code.toString())+1+internalCalculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.code.toString())+1}}else if(value._bsontype==="Binary"){const binary=value;if(binary.sub_type===Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1+4)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1)}}else if(value._bsontype==="Symbol"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+ByteUtils.utf8ByteLength(value.value)+4+1+1}else if(value._bsontype==="DBRef"){const ordered_values=Object.assign({$ref:value.collection,$id:value.oid},value.fields);if(value.db!=null){ordered_values["$db"]=value.db}return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+internalCalculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||isRegExp(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.source)+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value._bsontype==="BSONRegExp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.pattern)+1+ByteUtils.utf8ByteLength(value.options)+1}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+internalCalculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(serializeFunctions){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.toString())+1}}return 0}function alphabetize(str2){return str2.split("").sort().join("")}var BSONRegExp=class _BSONRegExp extends BSONValue{get _bsontype(){return"BSONRegExp"}constructor(pattern,options){super();this.pattern=pattern;this.options=alphabetize(options??"");if(this.pattern.indexOf("\0")!==-1){throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`)}if(this.options.indexOf("\0")!==-1){throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`)}for(let i=0;i4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max")}if(low.i>4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max")}super(low.i.valueOf(),low.t.valueOf(),true)}else{throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}}toJSON(){return{$timestamp:this.toString()}}static fromInt(value){return new _Timestamp(Long.fromInt(value,true))}static fromNumber(value){return new _Timestamp(Long.fromNumber(value,true))}static fromBits(lowBits,highBits){return new _Timestamp({i:lowBits,t:highBits})}static fromString(str2,optRadix){return new _Timestamp(Long.fromString(str2,true,optRadix))}toExtendedJSON(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}}static fromExtendedJSON(doc){const i=Long.isLong(doc.$timestamp.i)?doc.$timestamp.i.getLowBitsUnsigned():doc.$timestamp.i;const t=Long.isLong(doc.$timestamp.t)?doc.$timestamp.t.getLowBitsUnsigned():doc.$timestamp.t;return new _Timestamp({t,i})}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`}};Timestamp.MAX_VALUE=Long.MAX_UNSIGNED_VALUE;var FIRST_BIT=128;var FIRST_TWO_BITS=192;var FIRST_THREE_BITS=224;var FIRST_FOUR_BITS=240;var FIRST_FIVE_BITS=248;var TWO_BIT_CHAR=192;var THREE_BIT_CHAR=224;var FOUR_BIT_CHAR=240;var CONTINUING_CHAR=128;function validateUtf8(bytes,start,end){let continuation=0;for(let i=start;i= 5, is ${size}`)}if(options.allowObjectSmallerThanBufferSize&&buffer2.length= bson size ${size}`)}if(!options.allowObjectSmallerThanBufferSize&&buffer2.length!==size){throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`)}if(size+index>buffer2.byteLength){throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`)}if(buffer2[index+size-1]!==0){throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer2,index,options,isArray)}var allowedDBRefKeys=/^\$ref$|^\$id$|^\$db$/;function deserializeObject(buffer2,index,options,isArray=false){const fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];const raw=options["raw"]==null?false:options["raw"];const bsonRegExp=typeof options["bsonRegExp"]==="boolean"?options["bsonRegExp"]:false;const promoteBuffers=options.promoteBuffers??false;const promoteLongs=options.promoteLongs??true;const promoteValues=options.promoteValues??true;const useBigInt64=options.useBigInt64??false;if(useBigInt64&&!promoteValues){throw new BSONError("Must either request bigint or Long for int64 deserialization")}if(useBigInt64&&!promoteLongs){throw new BSONError("Must either request bigint or Long for int64 deserialization")}const validation=options.validation==null?{utf8:true}:options.validation;let globalUTFValidation=true;let validationSetting;const utf8KeysSet=new Set;const utf8ValidatedKeys=validation.utf8;if(typeof utf8ValidatedKeys==="boolean"){validationSetting=utf8ValidatedKeys}else{globalUTFValidation=false;const utf8ValidationValues=Object.keys(utf8ValidatedKeys).map(function(key){return utf8ValidatedKeys[key]});if(utf8ValidationValues.length===0){throw new BSONError("UTF-8 validation setting cannot be empty")}if(typeof utf8ValidationValues[0]!=="boolean"){throw new BSONError("Invalid UTF-8 validation option, must specify boolean values")}validationSetting=utf8ValidationValues[0];if(!utf8ValidationValues.every(item=>item===validationSetting)){throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}}if(!globalUTFValidation){for(const key of Object.keys(utf8ValidatedKeys)){utf8KeysSet.add(key)}}const startIndex=index;if(buffer2.length<5)throw new BSONError("corrupt bson message < 5 bytes long");const size=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(size<5||size>buffer2.length)throw new BSONError("corrupt bson message");const object=isArray?[]:{};let arrayIndex=0;const done=false;let isPossibleDBRef=isArray?false:null;const dataview=new DataView(buffer2.buffer,buffer2.byteOffset,buffer2.byteLength);while(!done){const elementType=buffer2[index++];if(elementType===0)break;let i=index;while(buffer2[i]!==0&&i=buffer2.byteLength)throw new BSONError("Bad BSON Document: illegal CString");const name=isArray?arrayIndex++:ByteUtils.toUTF8(buffer2.subarray(index,i));let shouldValidateKey=true;if(globalUTFValidation||utf8KeysSet.has(name)){shouldValidateKey=validationSetting}else{shouldValidateKey=!validationSetting}if(isPossibleDBRef!==false&&name[0]==="$"){isPossibleDBRef=allowedDBRefKeys.test(name)}let value;index=i+1;if(elementType===BSON_DATA_STRING){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}value=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize}else if(elementType===BSON_DATA_OID){const oid=ByteUtils.allocate(12);oid.set(buffer2.subarray(index,index+12));value=new ObjectId2(oid);index=index+12}else if(elementType===BSON_DATA_INT&&promoteValues===false){value=new Int32(buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24)}else if(elementType===BSON_DATA_INT){value=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24}else if(elementType===BSON_DATA_NUMBER&&promoteValues===false){value=new Double(dataview.getFloat64(index,true));index=index+8}else if(elementType===BSON_DATA_NUMBER){value=dataview.getFloat64(index,true);index=index+8}else if(elementType===BSON_DATA_DATE){const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;value=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType===BSON_DATA_BOOLEAN){if(buffer2[index]!==0&&buffer2[index]!==1)throw new BSONError("illegal boolean type value");value=buffer2[index++]===1}else if(elementType===BSON_DATA_OBJECT){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;if(objectSize<=0||objectSize>buffer2.length-index)throw new BSONError("bad embedded document length in bson");if(raw){value=buffer2.slice(index,index+objectSize)}else{let objectOptions=options;if(!globalUTFValidation){objectOptions={...options,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,objectOptions,false)}index=index+objectSize}else if(elementType===BSON_DATA_ARRAY){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;let arrayOptions=options;const stopIndex=index+objectSize;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={...options,raw:true}}if(!globalUTFValidation){arrayOptions={...arrayOptions,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,arrayOptions,true);index=index+objectSize;if(buffer2[index-1]!==0)throw new BSONError("invalid array terminator byte");if(index!==stopIndex)throw new BSONError("corrupted array bson")}else if(elementType===BSON_DATA_UNDEFINED){value=void 0}else if(elementType===BSON_DATA_NULL){value=null}else if(elementType===BSON_DATA_LONG){const dataview2=BSONDataView.fromUint8Array(buffer2.subarray(index,index+8));const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const long=new Long(lowBits,highBits);if(useBigInt64){value=dataview2.getBigInt64(0,true)}else if(promoteLongs&&promoteValues===true){value=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{value=long}}else if(elementType===BSON_DATA_DECIMAL128){const bytes=ByteUtils.allocate(16);bytes.set(buffer2.subarray(index,index+16),0);index=index+16;value=new Decimal128(bytes)}else if(elementType===BSON_DATA_BINARY){let binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const totalBinarySize=binarySize;const subType=buffer2[index++];if(binarySize<0)throw new BSONError("Negative binary type element size found");if(binarySize>buffer2.byteLength)throw new BSONError("Binary type size larger than document size");if(buffer2["slice"]!=null){if(subType===Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(binarySize<0)throw new BSONError("Negative binary type element size found for subtype 0x02");if(binarySize>totalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySizetotalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySize=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;const optionsArray=new Array(regExpOptions.length);for(i=0;i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;value=new BSONRegExp(source,regExpOptions)}else if(elementType===BSON_DATA_SYMBOL){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const symbol=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=promoteValues?symbol:new BSONSymbol(symbol);index=index+stringSize}else if(elementType===BSON_DATA_TIMESTAMP){const i2=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);const t=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);value=new Timestamp({i:i2,t})}else if(elementType===BSON_DATA_MIN_KEY){value=new MinKey}else if(elementType===BSON_DATA_MAX_KEY){value=new MaxKey}else if(elementType===BSON_DATA_CODE){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=new Code(functionString);index=index+stringSize}else if(elementType===BSON_DATA_CODE_W_SCOPE){const totalSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(totalSize<4+4+4+1){throw new BSONError("code_w_scope total size shorter minimum expected length")}const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize;const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;const scopeObject=deserializeObject(buffer2,_index,options,false);index=index+objectSize;if(totalSize<4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too short, truncating scope")}if(totalSize>4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too long, clips outer document")}value=new Code(functionString,scopeObject)}else if(elementType===BSON_DATA_DBPOINTER){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0)throw new BSONError("bad string length in bson");if(validation!=null&&validation.utf8){if(!validateUtf8(buffer2,index,index+stringSize-1)){throw new BSONError("Invalid UTF-8 string in BSON document")}}const namespace=ByteUtils.toUTF8(buffer2.subarray(index,index+stringSize-1));index=index+stringSize;const oidBuffer=ByteUtils.allocate(12);oidBuffer.set(buffer2.subarray(index,index+12),0);const oid=new ObjectId2(oidBuffer);index=index+12;value=new DBRef(namespace,oid)}else{throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`)}if(name==="__proto__"){Object.defineProperty(object,name,{value,writable:true,enumerable:true,configurable:true})}else{object[name]=value}}if(size!==index-startIndex){if(isArray)throw new BSONError("corrupt array bson");throw new BSONError("corrupt object bson")}if(!isPossibleDBRef)return object;if(isDBRefLike(object)){const copy=Object.assign({},object);delete copy.$ref;delete copy.$id;delete copy.$db;return new DBRef(object.$ref,object.$id,object.$db,copy)}return object}function getValidatedString(buffer2,start,end,shouldValidateUtf8){const value=ByteUtils.toUTF8(buffer2.subarray(start,end));if(shouldValidateUtf8){for(let i=0;i>24&255;buffer2[index+2]=size+1>>16&255;buffer2[index+1]=size+1>>8&255;buffer2[index]=size+1&255;index=index+4+size;buffer2[index++]=0;return index}var NUMBER_SPACE=new DataView(new ArrayBuffer(8),0,8);var FOUR_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,4);var EIGHT_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,8);function serializeNumber(buffer2,key,value,index){const isNegativeZero=Object.is(value,-0);const type=!isNegativeZero&&Number.isSafeInteger(value)&&value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN?BSON_DATA_INT:BSON_DATA_NUMBER;if(type===BSON_DATA_INT){NUMBER_SPACE.setInt32(0,value,true)}else{NUMBER_SPACE.setFloat64(0,value,true)}const bytes=type===BSON_DATA_INT?FOUR_BYTE_VIEW_ON_NUMBER:EIGHT_BYTE_VIEW_ON_NUMBER;buffer2[index++]=type;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(bytes,index);index+=bytes.byteLength;return index}function serializeBigInt(buffer2,key,value,index){buffer2[index++]=BSON_DATA_LONG;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index+=numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setBigInt64(0,value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index+=EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;return index}function serializeNull(buffer2,key,_,index){buffer2[index++]=BSON_DATA_NULL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeBoolean(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BOOLEAN;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value?1:0;return index}function serializeDate(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DATE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const dateInMilis=Long.fromNumber(value.getTime());const lowBits=dateInMilis.getLowBits();const highBits=dateInMilis.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw new BSONError("value "+value.source+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.source,index);buffer2[index++]=0;if(value.ignoreCase)buffer2[index++]=105;if(value.global)buffer2[index++]=115;if(value.multiline)buffer2[index++]=109;buffer2[index++]=0;return index}function serializeBSONRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.pattern.match(regexp)!=null){throw new BSONError("pattern "+value.pattern+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.pattern,index);buffer2[index++]=0;const sortedOptions=value.options.split("").sort().join("");index=index+ByteUtils.encodeUTF8Into(buffer2,sortedOptions,index);buffer2[index++]=0;return index}function serializeMinMax(buffer2,key,value,index){if(value===null){buffer2[index++]=BSON_DATA_NULL}else if(value._bsontype==="MinKey"){buffer2[index++]=BSON_DATA_MIN_KEY}else{buffer2[index++]=BSON_DATA_MAX_KEY}const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeObjectId(buffer2,key,value,index){buffer2[index++]=BSON_DATA_OID;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(isUint8Array(value.id)){buffer2.set(value.id.subarray(0,12),index)}else{throw new BSONError("object ["+JSON.stringify(value)+"] is not a valid ObjectId")}return index+12}function serializeBuffer(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=value.length;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=BSON_BINARY_SUBTYPE_DEFAULT;buffer2.set(value,index);index=index+size;return index}function serializeObject(buffer2,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined,path){if(path.has(value)){throw new BSONError("Cannot convert circular structure to BSON")}path.add(value);buffer2[index++]=Array.isArray(value)?BSON_DATA_ARRAY:BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const endIndex=serializeInto(buffer2,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);path.delete(value);return endIndex}function serializeDecimal128(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DECIMAL128;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(value.bytes.subarray(0,16),index);return index+16}function serializeLong(buffer2,key,value,index){buffer2[index++]=value._bsontype==="Long"?BSON_DATA_LONG:BSON_DATA_TIMESTAMP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const lowBits=value.getLowBits();const highBits=value.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeInt32(buffer2,key,value,index){value=value.valueOf();buffer2[index++]=BSON_DATA_INT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value&255;buffer2[index++]=value>>8&255;buffer2[index++]=value>>16&255;buffer2[index++]=value>>24&255;return index}function serializeDouble(buffer2,key,value,index){buffer2[index++]=BSON_DATA_NUMBER;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setFloat64(0,value.value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index=index+8;return index}function serializeFunction(buffer2,key,value,index){buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeCode(buffer2,key,value,index,checkKeys=false,depth=0,serializeFunctions=false,ignoreUndefined=true,path){if(value.scope&&typeof value.scope==="object"){buffer2[index++]=BSON_DATA_CODE_W_SCOPE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;const functionString=value.code;index=index+4;const codeSize=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=codeSize&255;buffer2[index+1]=codeSize>>8&255;buffer2[index+2]=codeSize>>16&255;buffer2[index+3]=codeSize>>24&255;buffer2[index+4+codeSize-1]=0;index=index+codeSize+4;const endIndex=serializeInto(buffer2,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);index=endIndex-1;const totalSize=endIndex-startIndex;buffer2[startIndex++]=totalSize&255;buffer2[startIndex++]=totalSize>>8&255;buffer2[startIndex++]=totalSize>>16&255;buffer2[startIndex++]=totalSize>>24&255;buffer2[index++]=0}else{buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.code.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0}return index}function serializeBinary(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const data=value.buffer;let size=value.position;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY)size=size+4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=value.sub_type;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY){size=size-4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255}buffer2.set(data,index);index=index+value.position;return index}function serializeSymbol(buffer2,key,value,index){buffer2[index++]=BSON_DATA_SYMBOL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=ByteUtils.encodeUTF8Into(buffer2,value.value,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeDBRef(buffer2,key,value,index,depth,serializeFunctions,path){buffer2[index++]=BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;let output={$ref:value.collection||value.namespace,$id:value.oid};if(value.db!=null){output.$db=value.db}output=Object.assign(output,value.fields);const endIndex=serializeInto(buffer2,output,false,index,depth+1,serializeFunctions,true,path);const size=endIndex-startIndex;buffer2[startIndex++]=size&255;buffer2[startIndex++]=size>>8&255;buffer2[startIndex++]=size>>16&255;buffer2[startIndex++]=size>>24&255;return endIndex}function serializeInto(buffer2,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined,path){if(path==null){if(object==null){buffer2[0]=5;buffer2[1]=0;buffer2[2]=0;buffer2[3]=0;buffer2[4]=0;return 5}if(Array.isArray(object)){throw new BSONError("serialize does not support an array as the root input")}if(typeof object!=="object"){throw new BSONError("serialize does not support non-object as the root input")}else if("_bsontype"in object&&typeof object._bsontype==="string"){throw new BSONError(`BSON types cannot be serialized as a document`)}else if(isDate(object)||isRegExp(object)||isUint8Array(object)||isAnyArrayBuffer(object)){throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`)}path=new Set}path.add(object);let index=startingIndex+4;if(Array.isArray(object)){for(let i=0;i>8&255;buffer2[startingIndex++]=size>>16&255;buffer2[startingIndex++]=size>>24&255;return index}function isBSONType(value){return value!=null&&typeof value==="object"&&"_bsontype"in value&&typeof value._bsontype==="string"}var keysToCodecs={$oid:ObjectId2,$binary:Binary,$uuid:Binary,$symbol:BSONSymbol,$numberInt:Int32,$numberDecimal:Decimal128,$numberDouble:Double,$numberLong:Long,$minKey:MinKey,$maxKey:MaxKey,$regex:BSONRegExp,$regularExpression:BSONRegExp,$timestamp:Timestamp};function deserializeValue(value,options={}){if(typeof value==="number"){const in32BitRange=value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN;const in64BitRange=value<=BSON_INT64_MAX&&value>=BSON_INT64_MIN;if(options.relaxed||options.legacy){return value}if(Number.isInteger(value)&&!Object.is(value,-0)){if(in32BitRange){return new Int32(value)}if(in64BitRange){if(options.useBigInt64){return BigInt(value)}return Long.fromNumber(value)}}return new Double(value)}if(value==null||typeof value!=="object")return value;if(value.$undefined)return null;const keys=Object.keys(value).filter(k=>k.startsWith("$")&&value[k]!=null);for(let i=0;ik.startsWith("$"));let valid=true;dollarKeys.forEach(k=>{if(["$ref","$id","$db"].indexOf(k)===-1)valid=false});if(valid)return DBRef.fromExtendedJSON(v2)}return value}function serializeArray(array,options){return array.map((v2,index)=>{options.seenObjects.push({propertyName:`index ${index}`,obj:null});try{return serializeValue(v2,options)}finally{options.seenObjects.pop()}})}function getISOString(date){const isoStr=date.toISOString();return date.getUTCMilliseconds()!==0?isoStr:isoStr.slice(0,-5)+"Z"}function serializeValue(value,options){if(value instanceof Map||isMap(value)){const obj=Object.create(null);for(const[k,v2]of value){if(typeof k!=="string"){throw new BSONError("Can only serialize maps with string keys")}obj[k]=v2}return serializeValue(obj,options)}if((typeof value==="object"||typeof value==="function")&&value!==null){const index=options.seenObjects.findIndex(entry=>entry.obj===value);if(index!==-1){const props=options.seenObjects.map(entry=>entry.propertyName);const leadingPart=props.slice(0,index).map(prop=>`${prop} -> `).join("");const alreadySeen=props[index];const circularPart=" -> "+props.slice(index+1,props.length-1).map(prop=>`${prop} -> `).join("");const current=props[props.length-1];const leadingSpace=" ".repeat(leadingPart.length+alreadySeen.length/2);const dashes="-".repeat(circularPart.length+(alreadySeen.length+current.length)/2-1);throw new BSONError(`Converting circular structure to EJSON: - ${leadingPart}${alreadySeen}${circularPart}${current} - ${leadingSpace}\\${dashes}/`)}options.seenObjects[options.seenObjects.length-1].obj=value}if(Array.isArray(value))return serializeArray(value,options);if(value===void 0)return null;if(value instanceof Date||isDate(value)){const dateNum=value.getTime(),inRange=dateNum>-1&&dateNum<2534023188e5;if(options.legacy){return options.relaxed&&inRange?{$date:value.getTime()}:{$date:getISOString(value)}}return options.relaxed&&inRange?{$date:getISOString(value)}:{$date:{$numberLong:value.getTime().toString()}}}if(typeof value==="number"&&(!options.relaxed||!isFinite(value))){if(Number.isInteger(value)&&!Object.is(value,-0)){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return{$numberInt:value.toString()}}if(value>=BSON_INT64_MIN&&value<=BSON_INT64_MAX){return{$numberLong:value.toString()}}}return{$numberDouble:Object.is(value,-0)?"-0.0":value.toString()}}if(typeof value==="bigint"){if(!options.relaxed){return{$numberLong:BigInt.asIntN(64,value).toString()}}return Number(BigInt.asIntN(64,value))}if(value instanceof RegExp||isRegExp(value)){let flags=value.flags;if(flags===void 0){const match=value.toString().match(/[gimuy]*$/);if(match){flags=match[0]}}const rx=new BSONRegExp(value.source,flags);return rx.toExtendedJSON(options)}if(value!=null&&typeof value==="object")return serializeDocument(value,options);return value}var BSON_TYPE_MAPPINGS={Binary:o=>new Binary(o.value(),o.sub_type),Code:o=>new Code(o.code,o.scope),DBRef:o=>new DBRef(o.collection||o.namespace,o.oid,o.db,o.fields),Decimal128:o=>new Decimal128(o.bytes),Double:o=>new Double(o.value),Int32:o=>new Int32(o.value),Long:o=>Long.fromBits(o.low!=null?o.low:o.low_,o.low!=null?o.high:o.high_,o.low!=null?o.unsigned:o.unsigned_),MaxKey:()=>new MaxKey,MinKey:()=>new MinKey,ObjectId:o=>new ObjectId2(o),BSONRegExp:o=>new BSONRegExp(o.pattern,o.options),BSONSymbol:o=>new BSONSymbol(o.value),Timestamp:o=>Timestamp.fromBits(o.low,o.high)};function serializeDocument(doc,options){if(doc==null||typeof doc!=="object")throw new BSONError("not an object instance");const bsontype=doc._bsontype;if(typeof bsontype==="undefined"){const _doc={};for(const name of Object.keys(doc)){options.seenObjects.push({propertyName:name,obj:null});try{const value=serializeValue(doc[name],options);if(name==="__proto__"){Object.defineProperty(_doc,name,{value,writable:true,enumerable:true,configurable:true})}else{_doc[name]=value}}finally{options.seenObjects.pop()}}return _doc}else if(doc!=null&&typeof doc==="object"&&typeof doc._bsontype==="string"&&doc[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(isBSONType(doc)){let outDoc=doc;if(typeof outDoc.toExtendedJSON!=="function"){const mapper=BSON_TYPE_MAPPINGS[doc._bsontype];if(!mapper){throw new BSONError("Unrecognized or invalid _bsontype: "+doc._bsontype)}outDoc=mapper(outDoc)}if(bsontype==="Code"&&outDoc.scope){outDoc=new Code(outDoc.code,serializeValue(outDoc.scope,options))}else if(bsontype==="DBRef"&&outDoc.oid){outDoc=new DBRef(serializeValue(outDoc.collection,options),serializeValue(outDoc.oid,options),serializeValue(outDoc.db,options),serializeValue(outDoc.fields,options))}return outDoc.toExtendedJSON(options)}else{throw new BSONError("_bsontype must be a string, but was: "+typeof bsontype)}}function parse(text,options){const ejsonOptions={useBigInt64:options?.useBigInt64??false,relaxed:options?.relaxed??true,legacy:options?.legacy??false};return JSON.parse(text,(key,value)=>{if(key.indexOf("\0")!==-1){throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`)}return deserializeValue(value,ejsonOptions)})}function stringify(value,replacer,space,options){if(space!=null&&typeof space==="object"){options=space;space=0}if(replacer!=null&&typeof replacer==="object"&&!Array.isArray(replacer)){options=replacer;replacer=void 0;space=0}const serializeOptions=Object.assign({relaxed:true,legacy:false},options,{seenObjects:[{propertyName:"(root)",obj:null}]});const doc=serializeValue(value,serializeOptions);return JSON.stringify(doc,replacer,space)}function EJSONserialize(value,options){options=options||{};return JSON.parse(stringify(value,options))}function EJSONdeserialize(ejson,options){options=options||{};return parse(JSON.stringify(ejson),options)}var EJSON=Object.create(null);EJSON.parse=parse;EJSON.stringify=stringify;EJSON.serialize=EJSONserialize;EJSON.deserialize=EJSONdeserialize;Object.freeze(EJSON);var MAXSIZE=1024*1024*17;var buffer=ByteUtils.allocate(MAXSIZE);function setInternalBufferSize(size){if(buffer.lengthAuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}onCollectionSet=(type,collection)=>{};runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b){if(a.timestamp&&b.timestamp)return a.timestamp-b.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_,__,___=this.data){}onSorted(_=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var defaultSpecifiers=["now","minute","5 minutes","30 minutes","hour","6 hours","12 hours","day","3 days","week","2 weeks","month","6 months","year","5 years","decade"];function genTimeSpecifiers(specifiers=defaultSpecifiers){let result=["now"];specifiers.forEach(s=>{if(s!=="now")result.push(`last ${s}`);else result.push(s)});return result}function genTimestampFromString(specifier){const now=new Date;if(specifier==="now"){}else if(specifier==="last minute"){now.setMinutes(now.getMinutes()-1)}else if(specifier==="last hour"){now.setHours(now.getHours()-1)}else if(specifier==="last day"){now.setDate(now.getDate()-1)}else if(specifier==="last week"){now.setDate(now.getDate()-7)}else if(specifier==="last month"){now.setMonth(now.getMonth()-1)}else if(specifier==="last year"){now.setFullYear(now.getFullYear()-1)}else if(specifier==="last decade"){now.setFullYear(now.getFullYear()-1*10)}else if(specifier==="last century"){now.setFullYear(now.getFullYear()-1*100)}else if(specifier==="last millennium"){now.setFullYear(now.getFullYear()-1*1e3)}else if(specifier==="last microsecond"){now.setMilliseconds(now.getMilliseconds()-1)}else if(specifier==="last nanosecond"){now.setMilliseconds(now.getMilliseconds()-1*.001)}else if(specifier.startsWith("last")){const[,count,unit]=specifier.match(/last (\d+) (\w+)/)||[];if(count&&unit){const num=parseInt(count,10);if(unit.includes("minute")){now.setMinutes(now.getMinutes()-num)}else if(unit.includes("hour")){now.setHours(now.getHours()-num)}else if(unit.includes("day")){now.setDate(now.getDate()-num)}else if(unit.includes("week")){now.setDate(now.getDate()-num*7)}else if(unit.includes("month")){now.setMonth(now.getMonth()-num)}else if(unit.includes("year")){now.setFullYear(now.getFullYear()-num)}else if(unit.includes("decade")){now.setFullYear(now.getFullYear()-num*10)}else if(unit.includes("century")){now.setFullYear(now.getFullYear()-num*100)}else if(unit.includes("millennium")){now.setFullYear(now.getFullYear()-num*1e3)}else if(unit.includes("microsecond")){now.setMilliseconds(now.getMilliseconds()-num)}else if(unit.includes("nanosecond")){now.setMilliseconds(now.getMilliseconds()-num*.001)}}}return now.getTime()}var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v2=>{if(!objProps[v2])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v2=>{obj2[k]=v2;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v2)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v2=>!objProps.includes(v2));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v2=>!objProps.includes(v2));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v2=>!objProps.includes(v2));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p2=origin[key];if(Array.isArray(p2))continue;let instanced;if(typeof p2==="function"){if(isNativeClass(p2)){p2=new p2;if(p2 instanceof GraphNode){p2=p2.prototype.constructor(p2,parent,this);instanced=true}}else p2={__operator:p2,__callable:true}}else if(typeof p2==="string"){if(this.__node.nodes.get(p2))p2=this.__node.nodes.get(p2);else p2=this.__node.roots[p2]}else if(typeof p2==="boolean"){if(this.__node.nodes.get(key))p2=this.__node.nodes.get(key);else p2=this.__node.roots[key]}if(p2&&typeof p2==="object"){if(!instanced&&!(p2 instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p2).filter(v2=>!objProps.includes(v2));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p2)).filter(v2=>!objProps.includes(v2));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p2[key2]}p2=cpy}if(!p2.__node)p2.__node={};if(!p2.__node.tag)p2.__node.tag=key;if(!p2.__node.initial)p2.__node.initial=originCpy[key];if(overwrite&&this.get(p2.__node.tag)){this.remove(p2.__node.tag,true)}else if(this.get(p2.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p2.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p2,2);if(instanced||p2 instanceof GraphNode){node=p2}else{node=new GraphNode(p2,parent,this);newnode=true}if(!newnode&&p2 instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d2=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d2.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{name="structs";currentUser;tablet=new DataTablet;collections=this.tablet.collections;id=randomId();useAccessTokens=false;useRefreshTokens=false;constructor(options,user){super(options);this.load(this);if(options.useAccessTokens)this.useAccessTokens=options.useAccessTokens;if(options.useRefreshTokens)this.useRefreshTokens=options.useRefreshTokens;if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}getToken(user){if(this.useAccessTokens)return user.accessToken;else if(this.useRefreshTokens)return user.refreshToken}setupUser=async(userinfo,callback=currentUser=>{})=>{if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u2;let newu=false;if(!user||!user._id){u2=this.userStruct(userinfo,false);newu=true;let wasSet=await this.setUser(u2);let structs=this.getLocalData(void 0,{"ownerId":u2._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u2)}else{u2=user;let toUpdate={_id:userinfo._id,ownerId:userinfo._id};let struct=this.userStruct(userinfo,false);for(const key in struct){if(userinfo[key]&&user[key]!==userinfo[key]){toUpdate[key]=userinfo[key];user[key]=userinfo[key]}else if(struct[key]&&!user[key]){toUpdate[key]=struct[key];user[key]=struct[key]}}if(Object.keys(toUpdate).length>2)await this.setUser(toUpdate);if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u2)}else{let data=await this.getAllUserData(u2._id,void 0,[genTimestampFromString("last day"),Date.now()]);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u2)}if(u2){if(this.currentUser)Object.assign(this.currentUser,u2);else this.currentUser=u2;callback(this.currentUser);return this.currentUser}else{callback(u2);return u2}};baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}this.onResult(data)};structNotification=()=>{this.checkForNotifications()};structDeleted=struct=>{this.deleteLocalData([struct])};onResult=data=>{};randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}addStruct=async(structType="struct",props={},parentUser,parentStruct,updateServer=true)=>{let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct};getUser=async(info="",basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info,basicInfo,this.getToken(this.currentUser)]});callback(res);return res}};queryUsers=async(info,skip,limit,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"queryUsers",args:[this.currentUser._id,info,skip,limit,void 0,this.getToken(this.currentUser)]});callback(res);return res}};getUsers=async(ids=[],basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids,basicInfo]});callback(res);return res}};getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};getAllUserData=async(ownerId,excluded=[],timeRange,callback=this.baseServerCallback)=>{if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[this.currentUser._id,ownerId,excluded,timeRange,this.getToken(this.currentUser)]});callback(res);return res}};query=async(collection,mongoQuery={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!mongoQuery)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,mongoQuery,findOne,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByTimeRange(collection,timeRange,ownerId,limit=0,skip=0,key){let query={};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}let range={$gt:timeRange[0],$lt:timeRange[1]};if(key)query[key]=range;else query.timestamp=range;return this.getData(collection,ownerId,query,limit,skip)}getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct?.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id,this.getToken(this.currentUser)];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};setUser=async(userStruct,callback=this.baseServerCallback)=>{if(userStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};updateServerData=this.setData;deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteUser=async(userId=this.currentUser._id,deleteData,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId,deleteData,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setGroup=async(groupStruct,callback=this.baseServerCallback)=>{if(groupStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setAuthorization=async(authorizationStruct,callback=this.baseServerCallback)=>{if(authorizationStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=await this.currentUser.request({route:"deleteAuthorization",args:[this.currentUser._id,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent){toUpdate=[parent];allReplies.forEach(r=>{let idx=parent.replies?.indexOf(r._id);if(idx>-1)parent.replies.splice(idx,1);let idx2=parent.comments?.indexOf(r._id);if(idx2>-1)parent.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent?._id){let idx=replyTo.replies?.indexOf(parent._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u2=authorizationStruct.authorizerId;if(u2){return new Promise(async resolve=>{this.getUser(u2,true,async data=>{let res;if(!collection)res=await this.getAllUserData(u2,["notification"],void 0,callback);else res=await this.getData(collection,u2,searchDict,limit,skip,callback);resolve(res);callback(res)})})}else return void 0};getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u2=o.authorizerId;if(u2){let data;let user=await this.getUser(u2,true,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u2,["notification"],void 0,callback);else data=await this.getData(collection,u2,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return{};let result={};let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result[a.authorizedId]=true});return result};getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b)=>a*(typeof b==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(void 0,{_id:struct});if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop]===""||copy[prop].constructor.name==="Map"||copy[prop].constructor.name==="Set"||typeof copy[prop]==="function")delete copy[prop];else if(Array.isArray(copy[prop])&©[prop].length===0)delete copy[prop];else if(typeof copy[prop]==="object"&&Object.keys(copy[prop]).length===0)delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(!user.name&&user.firstName)user.name=user.firstName+" "+user.lastName;else if(user.name&&!user.firstName){let split=user.name.split(" ");user.firstName=split[0];user.lastName=split[split.length-1]}if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e15);user._id=user.id;user.ownerId=user.id;let dummy=DataStructures_exports.ProfileStruct();for(const prop in props){if(Object.keys(dummy).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};addEvent=async(parentUser,author="",event="",notes="",startTime=void 0,endTime=void 0,grade=void 0,value=void 0,units=void 0,location=void 0,attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.value=value;newEvent.units=units;newEvent.users=users;newEvent.location=location;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};addChatroom=async(parentUser,authorId="",message="",attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=void 0,updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res}};var import_bson=__toESM(require_bson());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectId=str2=>{return typeof str2==="string"&&str2.length===24?new import_bson.ObjectId(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{name="structs";debug=false;db;users={};collections={};mode="local";useAuths=true;useAccessTokens=false;useRefreshTokens=false;accessTokens=new Map;refreshTokens=new Map;constructor(options,dboptions){super(options);this.load(this);if(dboptions){this.initDB(dboptions)}}initDB=dboptions=>{this.db=dboptions.db;if(dboptions?.users)this.users=dboptions.users;if(dboptions.mode)this.mode=dboptions.mode;if(dboptions?.collections)this.collections=dboptions.collections;if(dboptions.debug)this.debug=dboptions.debug;if(dboptions.useAccessTokens)this.useAccessTokens=dboptions.useAccessTokens;if(dboptions.useRefreshTokens)this.useRefreshTokens=dboptions.useRefreshTokens;if("useAuths"in dboptions)this.useAuths=dboptions.useAuths;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})};query=async(requestingUserId,collection,queryObj,findOne,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip,token)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token);if(passed)return res}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}));return data}};getUser=async(requestingUserId,lookupId,basicInfo,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId,void 0,basicInfo,token)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:void 0};else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};setUser=async(requestingUserId,struct,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(struct.accessToken){this.accessTokens.set(requestingUserId,token)}if(struct.refreshToken){this.refreshTokens.set(requestingUserId,struct.refreshToken)}delete struct.accessToken;delete struct.refreshToken;delete user.accessToken;delete user.refreshToken;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct,token)}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};getUsersByIds=async(requestingUserId,userIds,basicInfo)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds,basicInfo)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct){if(basicInfo)data.push({_id:struct._id,username:struct.username,firstName:struct.firstName,lastName:struct.lastName,fullName:struct.fullName,pictureUrl:struct.pictureUrl});else data.push(struct)}}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};deleteUser=async(requestingUserId,userId,deleteData,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId,deleteData,token)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};setData=async(requestingUserId,structs,notify,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify,token)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};getData=async(requestingUserId,collection,ownerId,dict,limit,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};getDataByIds=async(requestingUserId,structIds,ownerId,collection,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};getAllData=async(requestingUserId,ownerId,excludedCollections,timeRange,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections,timeRange,token)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};deleteData=async(requestingUserId,structIds,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds,token)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};deleteGroup=async(requestingUserId,groupId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId,token)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};getAuthorizations=async(requestingUserId,ownerId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId,token)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};deleteAuthorization=async(requestingUserId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId,token)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};getToken=user=>{return this.useAccessTokens?this.accessTokens.get(user._id):this.useRefreshTokens?this.refreshTokens.get(user._id):void 0};notificationStruct=(parentStruct={})=>{let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct};checkToNotify=async(user,structs=[],mode=this.mode)=>{if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(struct.ownerId&&user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+struct.ownerId;newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+usr;newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id)+"_"+auth.authorizedId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications,true,this.getToken(user))}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid]?.sendAll({route:"structNotification",args:true})}return true}else return false};queryMongo=async(user,collection,queryObj={},findOne=false,skip=0,token)=>{if(!collection&&!queryObj)return void 0;else if(findOne){let res=await this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token)}if(passed)return res;else return void 0}else{let res=this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];let arr=await res.toArray();if(arr.length>0){let passed=!this.useAuths;let checkedAuth="";for(const s of arr){if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)structs.push(s)}}return structs}};setMongoData=async(user,structs=[],notify=true,token)=>{let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:toObjectId(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType?struct.structType:"data").insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectId(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false};setMongoUser=async(user,struct,token)=>{if(struct._id){const _id=toObjectId(struct._id);let usersearch={_id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));copy._id=_id;if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false};setGroup=async(user,struct,mode=this.mode,token)=>{if(struct?._id){let uid=getStringId(user._id);let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(uid)<0))return false;if(uid!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u2=>{allusers.push({email:u2},{id:u2},{username:u2})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});let arr=cursor.toArray();if(arr.length>0){arr.forEach(user2=>{users[uid]=user2;ids[uid]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u2=users[id];if(struct.admins[getStringId(u2._id)]||struct.admins[u2.email]||struct.admins[u2.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u2._id)])admins[getStringId(u2._id)]=true}if(struct.peers[getStringId(u2._id)]||struct.peers[u2.email]||struct.peers[u2.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u2._id)])peers[getStringId(u2._id)]=true}if(struct.clients[getStringId(u2._id)]||struct.clients[u2.email]||struct.clients[u2.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u2._id)])clients[getStringId(u2._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType?struct.structType:"data").findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectId(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false};getMongoUser=(user,info="",requireAuth=true,basicInfo=false,token)=>{return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectId(info)})}catch(e){console.log("error creating ObjectId with ",info)}let u2=await this.collections.profile.instance.findOne({$or:query});if(!u2||u2==null)resolve(void 0);else{u2._id=getStringId(u2._id);if(!u2.ownerId)u2.ownerId=u2._id;if(basicInfo){if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}let stripped={username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id};u2=stripped;resolve({user:u2})}else if(requireAuth){if(getStringId(user._id)!==u2._id||getStringId(user._id)===u2._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u2,"READ",token);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u2._id});let aarr=await auths.toArray();if(auths.toArray().length>0){aarr.forEach(d2=>authorizations.push(d2))}let gs=this.collections.group.instance.find({users:{$all:[u2._id]}});let arr=await gs.toArray();let groups=[];if(arr.length>0){arr.forEach(d2=>groups.push(d2))}resolve({user:u2,authorizations,groups})}else{if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}resolve({user:u2})}}})};queryUsers=(user,info="",limit=0,skip=0,requireAuth=false,token)=>{if(typeof user==="string")user=this.users[user];if(!user)return;return new Promise(async resolve=>{let q={$regex:`^${info}`,$options:"i"};const query=[{email:q},{username:q},{firstName:q},{lastName:q},{name:q}];let arr;if(this.mode.includes("mongo")){let users=this.collections.profile.instance.find({$or:query},{projection:shallowqueryDummy}).skip(skip);if(limit>0)users.limit(limit);await users;arr=await users.toArray()}else{arr=[];for(let i=0;i{arr.push({firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,username:u2.username,pictureUrl:u2.pictureUrl})})}else if(dat)arr.push({firstName:dat.firstName,lastName:dat.lastName,fullName:dat.fullName,username:dat.username,pictureUrl:dat.pictureUrl})}}if(requireAuth){let result=[];let strid=getStringId(user._id);for(let i=0;i{let usrs=[];userIds.forEach(u2=>{try{usrs.push({_id:toObjectId(u2)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{if(basicInfo){found.push({username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id})}else found.push(u2)})}}return found};getMongoUsersByRole=async(user,role)=>{let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{found.push(u2)})}return found};getMongoDataByIds=async(user,structIds,ownerId,collection,token)=>{let uid=getStringId(user._id);if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectId(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});let arr=await cursor.toArray();if(arr.length>0){let passed=true;let checkedAuth="";for(let i=0;i0){let passed=true;let checkedAuth="";arr.forEach(async s=>{if(!s?.ownerId)passed=true;else if((uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}};getMongoData=async(user,collection,ownerId,dict={},limit=0,skip=0,token)=>{if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectId(dict._id);let uid=getStringId(user._id);let structs=[];let passed=true;let checkedAuth="";let cursor;if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip)}else if(collection&&Object.keys(dict).length>0){if(ownerId)dict.ownerId=ownerId;cursor=await this.db.collection(collection).find(dict).sort({$natural:-1}).skip(skip)}if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{cursor=await this.db.collection(name).find(dict).sort({$natural:-1}).skip(skip);;if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i{let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let query={ownerId};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1]);query.timestamp={$gt:timeRange[0],$lt:timeRange[1]}}let cursor=this.db.collection(name).find(query);let arr=await cursor.toArray();let count=arr.length;for(let k=0;k{let structs=[];if(structs.length>0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectId(ref._id)});if(struct){let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs};getMongoAuthorizations=async(user,ownerId=getStringId(user._id),authId="",token)=>{let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectId(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0],"READ",token);if(!passed)return void 0}return auths};getMongoGroups=async(user,userId=getStringId(user._id),groupId="")=>{let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId),users:{$all:[userId]}}))}catch{}}return groups};deleteMongoData=async(user,structRefs=[],token)=>{let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectId(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=notifications.toArray().length;for(let i=0;i{let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){await this.db.collection(struct.structType?struct.structType:"data").deleteOne({_id:toObjectId(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})}}}));return true};deleteMongoUser=async(user,userId,deleteData,token)=>{if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u2=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u2?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u2,"WRITE",token);if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(deleteData){for(const key in this.collections){this.collections[key].instance.deleteMany({ownerId:userId});this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}})}}if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId]?.sendAll({route:"structDeleted",args:{_id:userId,structType:"profile"}});return true};deleteMongoGroup=async(user,groupId,token)=>{let s=await this.collections.group.instance.findOne({_id:toObjectId(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u2=>{this.users[u2]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}})})}await this.collections.group.instance.deleteOne({_id:toObjectId(groupId)});return true}else return false};deleteMongoAuthorization=async(user,authId,token)=>{let s=await this.collections.authorization.instance.findOne({_id:toObjectId(authId)});let uid=getStringId(user._id);if(s){if(uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectId(s.associatedAuthId)});if(s.authorizerId!==uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}});else if(s.authorizedId!==uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}})}await this.collections.authorization.instance.deleteOne({_id:toObjectId(authId)});if(s.authorizerId===uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});else if(s.authorizedId===uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});return true}else return false};setAuthorization=async(user,authStruct,token)=>{let u1,u2;let mmode=this.mode.includes("mongo");if(mmode){u1=(await this.getMongoUser(user,authStruct.authorizedId,false)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,false)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})?.[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})?.[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.name)authStruct.authorizedName=u1.name;else if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u1.name)authStruct.authorizedName=u1.name;else if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE",token);if(!passed)return false}let auths=[];if(mmode){let s=await this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d2=>{if(d2.authorizerId===authStruct.authorizerId)auths.push(d2)})}}let otherAuthset;if(Array.isArray(auths)){for(let i=0;i{if(typeof user==="string"){if(this.users[user])user=this.users[user];else user={_id:user}}if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}return true}}if(this.useAccessTokens){if(!this.accessTokens.get(user._id)||this.accessTokens.get(user._id)!==token){return false}}else if(this.useRefreshTokens){if(!this.refreshTokens.get(user._id)||this.refreshTokens.get(user._id)!==token){return false}}let auth1,auth2;if(this.mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});if(!auth1)return false;auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(struct.ownerId)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(struct.ownerId)}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed};wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};overwriteLocalData=structs=>{if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}};setLocalData=structs=>{let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)};getLocalData=(collection,query)=>{let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result};deleteLocalData=struct=>{if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var shallowqueryDummy=DataStructures_exports.ProfileStruct();for(const key in shallowqueryDummy){if(key==="username"||key==="lastName"||key==="firstName"||key==="name"||key==="_id"||key==="pictureUrl")shallowqueryDummy[key]=1;else delete shallowqueryDummy[key]}var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u2=(dot11*dot02-dot01*dot12)*_denom;let v2=(dot00*dot12-dot01*dot02)*_denom;if(u2>=0&&v2>=0&&u2+v2<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v2=>{let magnitude=0;for(const key in v2){magnitude+=v2[key]*v2[key]}return Math.sqrt(magnitude)},normalize:v2=>{let magnitude=Systems.collision.magnitude(v2);let _mag=magnitude?1/magnitude:0;let vn={};for(const key in v2){vn[key]=v2[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w2=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w2||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var y=class{r;g;b;a;constructor(e,t,l,o){this.r=e,this.g=t,this.b=l,this.a=o}};var w=class{intensity;visible;numPoints;xy;color;scaleX;scaleY;offsetX;offsetY;loop;webglNumPoints;_vbuffer;_coord;constructor(){this.scaleX=1,this.scaleY=1,this.offsetX=0,this.offsetY=0,this.loop=false,this._vbuffer=0,this._coord=0,this.visible=true,this.intensity=1,this.xy=new Float32Array([]),this.numPoints=0,this.color=new y(0,0,0,1),this.webglNumPoints=0}};var v=class extends w{currentIndex=0;constructor(e,t){super(),this.webglNumPoints=t,this.numPoints=t,this.color=e,this.xy=new Float32Array(2*this.webglNumPoints)}setX(e,t){this.xy[e*2]=t}setY(e,t){this.xy[e*2+1]=t}getX(e){return this.xy[e*2]}getY(e){return this.xy[e*2+1]}lineSpaceX(e,t){for(let l=0;l{let l={x:0,y:0};return l.x=u2.x+e.x*t,l.y=u2.y+e.y*t,l};var A=u2=>P(-u2.y,u2.x);var p=(u2,e)=>{let t=R(u2,e);return t=M(t),t};var T=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x+e.x,t.y=u2.y+e.y,t};var C=(u2,e)=>u2.x*e.x+u2.y*e.y;var M=u2=>{let e={x:0,y:0},t=u2.x*u2.x+u2.y*u2.y;return t>0&&(t=1/Math.sqrt(t),e.x=u2.x*t,e.y=u2.y*t),e};var P=(u2,e)=>{let t={x:0,y:0};return t.x=u2,t.y=e,t};var R=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x-e.x,t.y=u2.y-e.y,t};var X=u2=>{let e,t={x:0,y:0},l={x:0,y:0},o=[],a=(s,r)=>{o.push({vec2:s,miterLength:r})},h=s=>({x:u2[s*2],y:u2[s*2+1]});t=p(h(1),h(0)),e=A(t),a(e,1);let n=u2.length/2;for(let s=1;s{let t=T(u2,e);return t=M(t),P(-t.y,t.x)};var N=(u2,e,t)=>{let l=P(-u2.y,u2.x);return t/C(e,l)};var d=class extends w{currentIndex=0;_linePoints;_thicknessRequested=0;_actualThickness=0;constructor(e,t,l){super(),this.webglNumPoints=t*2,this.numPoints=t,this.color=e,this._thicknessRequested=l,this._linePoints=new Float32Array(t*2),this.xy=new Float32Array(2*this.webglNumPoints)}convertToTriPoints(){let e=this._actualThickness/2,t=X(this._linePoints);for(let l=0;l{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(l.loop?t.LINE_LOOP:t.LINE_STRIP,0,l.webglNumPoints)}})}_drawSurfaces(e){let t=this.webgl;e.forEach(l=>{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(t.TRIANGLE_STRIP,0,l.webglNumPoints)}})}_drawTriangles(e){let t=this.webgl;t.bufferData(t.ARRAY_BUFFER,e.xy,t.STREAM_DRAW),t.useProgram(this._progLine);let l=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(l,false,new Float32Array([e.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,e.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let o=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(o,new Float32Array([e.offsetX+this.gOffsetX,e.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([0,0]));let h=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(h,[e.color.r,e.color.g,e.color.b,e.color.a]),t.drawArrays(t.TRIANGLE_STRIP,0,e.xy.length/2)}_drawThickLines(){this._thickLines.forEach(e=>{if(e.visible){let t=Math.min(this.gScaleX,this.gScaleY);e.setActualThickness(e.getThickness()/t),e.convertToTriPoints(),this._drawTriangles(e)}})}update(){this.clear(),this.draw()}draw(){this._drawLines(this.linesData),this._drawLines(this.linesAux),this._drawThickLines(),this._drawSurfaces(this.surfaces)}clear(){this.webgl.clear(this.webgl.COLOR_BUFFER_BIT)}_addLine(e){e._vbuffer=this.webgl.createBuffer(),this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER,e._vbuffer),this.webgl.bufferData(this.webgl.ARRAY_BUFFER,e.xy,this.webgl.STREAM_DRAW),e._coord=this.webgl.getAttribLocation(this._progLine,"coordinates"),this.webgl.vertexAttribPointer(e._coord,2,this.webgl.FLOAT,false,0,0),this.webgl.enableVertexAttribArray(e._coord)}addDataLine(e){this._addLine(e),this.linesData.push(e)}addLine=this.addDataLine;addAuxLine(e){this._addLine(e),this.linesAux.push(e)}addThickLine(e){this._addLine(e),this._thickLines.push(e)}addSurface(e){this._addLine(e),this.surfaces.push(e)}initThinLineProgram(){let e=` - attribute vec2 coordinates; - uniform mat2 uscale; - uniform vec2 uoffset; - uniform ivec2 is_log; - - void main(void) { - float x = (is_log[0]==1) ? log(coordinates.x) : coordinates.x; - float y = (is_log[1]==1) ? log(coordinates.y) : coordinates.y; - vec2 line = vec2(x, y); - gl_Position = vec4(uscale*line + uoffset, 0.0, 1.0); - }`,t=this.webgl.createShader(this.webgl.VERTEX_SHADER);this.webgl.shaderSource(t,e),this.webgl.compileShader(t);let l=` - precision mediump float; - uniform highp vec4 uColor; - void main(void) { - gl_FragColor = uColor; - }`,o=this.webgl.createShader(this.webgl.FRAGMENT_SHADER);this.webgl.shaderSource(o,l),this.webgl.compileShader(o),this._progLine=this.webgl.createProgram(),this.webgl.attachShader(this._progLine,t),this.webgl.attachShader(this._progLine,o),this.webgl.linkProgram(this._progLine)}popDataLine(){this.linesData.pop()}removeAllLines(){this._linesData=[],this._linesAux=[],this._thickLines=[],this._surfaces=[]}removeDataLines(){this._linesData=[]}removeAuxLines(){this._linesAux=[]}viewport(e,t,l,o){this.webgl.viewport(e,t,l,o)}log(e){this.debug&&console.log("[webgl-plot]:"+e)}};var S=class u{constructor(){this.plots={};this.renderOverlay=(e,t,l,o,a,h=1,n=0)=>{if(typeof l.settings.overlay=="object"&&(o.useOverlay||!("useOverlay"in o))){let s=l.settings.nLines-o.position-1,r=e.height*s/l.settings.nLines,i=e.height*(s+1)/l.settings.nLines;if(t.clearRect(0,r,e.width,i),l.settings.mode==="sweep"){t.strokeStyle=l.settings.sweepColor?l.settings.sweepColor:"rgba(0,255,0,0.8)",t.beginPath();let f=e.width*o.ct/o.values.length;t.moveTo(f,r),t.lineTo(f,i),t.stroke()}if(t.fillStyle=l.settings.overlayColor?l.settings.overlayColor:"white",a&&t.fillText(a,20,e.height*(s+.2)/l.settings.nLines),o.nSec){let f=this.formatTime(o.nSec);t.fillText(`${f}`,l.settings.mode==="sweep"?e.width-35:20,e.height*(s+.9)/l.settings.nLines),t.fillText("0:00",l.settings.mode==="sweep"?20:e.width-35,e.height*(s+.9)/l.settings.nLines)}typeof h=="number"&&t.fillText(`${Math.floor(h)===h?h:h?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.2)/l.settings.nLines),typeof n=="number"&&t.fillText(`${Math.floor(n)===n?n:n?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.8)/l.settings.nLines)}}}initPlot(e,t){if(t||(t=new x2(e.canvas,e.webglOptions)),!e._id)e._id=`plot${Math.floor(Math.random()*1e15)}`;else if(this.plots[e._id]){let r=this.plots[e._id].initial;if(e.lines){for(let i in e.lines)if(r.lines[i]&&Array.isArray(e.lines[i])){let f=e.lines[i];e.lines[i]=r.lines[i]}}e=Object.assign(r,e)}e.overlay&&(typeof e.overlay!="object"&&(e.overlay=document.createElement("canvas"),e.overlay.style.position="absolute",e.overlay.width=e.canvas.width,e.overlay.height=e.canvas.height,e.canvas.appendChild(e.overlay)),e.overlayCtx||(e.overlayCtx=e.overlay.getContext("2d"))),e.width&&(e.canvas.width=e.width,e.canvas.style&&(e.canvas.style.width=e.width+"px"),typeof e.overlay=="object"&&(e.overlay.width=e.width,e.overlay.style&&(e.overlay.style.width=e.width+"px"))),e.height&&(e.canvas.height=e.height,e.canvas.style&&(e.canvas.style.height=e.height+"px"),typeof e.overlay=="object"&&(e.overlay.height=e.height,e.overlay.style&&(e.overlay.style.height=e.height+"px"))),e.lines?.timestamp&&delete e.lines.timestamp,e.lines||(e.lines={});let l={};for(let r in e.lines)l[r]=Object.assign({},l[r]),"viewing"in e.lines[r]||(e.lines[r].viewing=true),l[r].viewing=e.lines[r].viewing,l[r].sps=e.lines[r].sps,l[r].nSec=e.lines[r].nSec,l[r].nPoints=e.lines[r].nPoints,l[r].ymin=e.lines[r].ymin,l[r].ymax=e.lines[r].ymax,l[r].units=e.lines[r].units;let o={plot:t,settings:e,initial:Object.assign(Object.assign({},e),{lines:l}),anim:()=>{t.update()}};this.plots[e._id]=o;let a=0,h=0;Object.keys(e.lines).forEach(r=>{e.lines[r]?.viewing!==false&&h++}),e.nLines=h;let n,s;typeof e.overlay=="object"&&(n=e.overlay,s=e.overlayCtx,s.clearRect(0,0,e.overlay.width,e.overlay.height),s.font=e.overlayFont?e.overlayFont:"1em Courier",s.fillStyle=e.overlayColor?e.overlayColor:"white");for(let r in e.lines){let i=e.lines[r];if(Array.isArray(i)&&(i={values:i},e.lines[r]=i),"viewing"in i||(i.viewing=true),i.color)Array.isArray(i.color)&&(i.color=new y(...i.color));else{let m=u.HSLToRGB(360*(a/h)%360,100,50,1);o.initial.lines[r].color=[...m,1],i.color=new y(...m,1)}let f;if(i.nSec&&i.sps?f=Math.ceil(i.nSec*i.sps):i.nPoints?f=i.nPoints:i.points?f=i.points:e.linePoints?f=e.linePoints:i.values?f=i.values.length:f=1e3,i.points=f,e.lines[r].viewing===false)continue;if((i.width||e.lineWidth)&&i.width!==0){let m=e.lineWidth;m||(m=i.width),i.width?i.line=new d(i.color,f,i.width):e.lineWidth&&(i.line=new d(i.color,f,e.lineWidth)),i.line.lineSpaceX(-1,2/i.line.numPoints)}else i.line=new v(i.color,f),i.line.arrangeX();i.values?.length===i.points?i.values.length!==f&&(i.interpolate?i.values.length>f?i.values=u.downsample(i.values,f):i.values.lengthi.points?i.values=i.values.slice(i.values.length-i.points):i.values=[...new Array(i.points-i.values.length).fill(0),...i.values]):Array.isArray(i.values)?i.values.length>f?i.values=i.values.slice(i.values.length-f):i.values.lengthg){let m=c;g=c,c=m}let _=Math.abs(c);if(i.absmax=_>g?_:g,"autoscale"in i||(i.autoscale=true),i.position||(i.position=e.nLines-a-1),i.autoscale?i.autoscale===2?("clamp"in i||(i.clamp=true),i.scaled=u.autoscale(i.values,i.position,h,i.centerZero,c,g,i.clamp)):(i.scaled=i.values,i.line.scaleY=u.getYScalar(i.values,h,i.centerZero,c,g),i.line.offsetY=u.getYOffset(i.position,h,c,i.line.scaleY)):i.scaled=i.values,i.scaled.forEach((m,L)=>i.line.setY(L,m)),i.line instanceof d?t.addThickLine(i.line):i.line instanceof v&&t.addDataLine(i.line),"xAxis"in i||(i.xAxis=true),i.xAxis){i.xColor?Array.isArray(i.xColor)&&(i.xColor=new y(...i.xColor)):i.xColor=new y(1,1,1,.3);let m=new v(i.xColor,2),L=i.autoscale?(a+1)*2/h-1-1/h:0;m.constY(L),m.arrangeX(),m.xy[2]=1,i.x=m,t.addAuxLine(m)}if(h>1&&i.autoscale&&a!==h-1){e.dividerColor?Array.isArray(e.dividerColor)&&(e.dividerColor=new y(...e.dividerColor)):e.dividerColor=new y(1,1,1,1);let m=new v(e.dividerColor,2);m.constY(i.autoscale?(a+1)*2/h-1:1),m.arrangeX(),m.xy[2]=1,i.divider=m,t.addAuxLine(m)}if(typeof e.overlay=="object"&&(i.useOverlay||!("useOverlay"in i))){let m=e.nLines-i.position-1;s.fillText(r,20,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(g)===g?g:g?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(c)===c?c:c?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.9)/e.nLines)}a++}return requestAnimationFrame(o.anim),this.plots[e._id]}deinitPlot(e){return typeof e=="string"&&(e=this.plots[e]),e.plot.clear(),e.plot.removeAllLines(),true}reinitPlot(e,t){if(typeof e=="string"){let l=e;e=this.plots[e],t._id||(t._id=l)}if(e.plot)return e.plot.clear(),e.plot.removeAllLines(),e.settings.overlayCtx&&e.settings.overlayCtx.clearRect(0,0,e.settings.overlay?.width,e.settings.overlay?.height),this.initPlot(t,e.plot)}getChartSettings(e,t){let l=this.plots[e];if(l){let o=Object.assign({},l.initial);for(let a in l.initial.lines)typeof l.initial.lines[a]?.ymax!="number"&&(o.lines[a].ymax=l.settings.lines[a]?.ymax),typeof l.initial.lines[a]?.ymin!="number"&&(o.lines[a].ymin=l.settings.lines[a]?.ymin),t&&(o.lines[a].values=l.settings.lines[a].values);return delete o.canvas,delete o.overlay,delete o.overlayCtx,o}}update(e,t,l=true){if(typeof e=="string"&&(e=this.plots[e]),!e)return false;let o,a;if(typeof e.settings.overlay=="object"&&(o=e.settings.overlay,a=e.settings.overlayCtx,a.font=e.settings.overlayFont?e.settings.overlayFont:"1em Courier",a.fillStyle=e.settings.overlayColor?e.settings.overlayColor:"white"),t){let h=false;for(let n in t)if(e.settings.lines[n]&&e.settings.lines[n].line){if(e.settings.lines[n]?.viewing===false)continue;let s=e.settings.lines[n];if(s.values){if(e.settings.mode&&e.settings.mode==="sweep"){"ct"in s||(s.ct=0);let g=b=>{s.ct>s.values.length&&(s.ct=0),s.values[s.ct]=b,s.ct++};Array.isArray(t[n])?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n][t[n].length-1])),t[n].forEach(g)):typeof t[n]=="number"?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n])),g(t[n])):t[n].values&&(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n].values[t[n].values.length-1])),t[n].values.forEach(g))}else Array.isArray(t[n])&&s.values?.length<1e5?(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n][t[n].length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n][t[n].length-1]),s.firstWrite=true),t[n].length===s.values.length?s.values=t[n]:u.circularBuffer(s.values,t[n])):typeof t[n]=="number"?(s.firstWrite||(s.values.fill(t[n]),s.firstWrite=true),s.values.push(t[n]),s.values.shift()):t[n]?.values&&(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true),t[n].values.length===s.values.length?s.values=t[n].values:u.circularBuffer(s.values,t[n].values));s.values.length!==s.points&&(s.interpolate?s.values.length>s.points?s.values=u.downsample(s.values,s.points):s.scaled.lengths.points?s.values.splice(0,s.values.length-s.points):s.values=new Array(s.points).fill(0).splice(s.points-s.values.length,0,s.values));let r=s.ymin,i=s.ymax,f=s.values.length<=1e5;if(r===i?(i=f?Math.max(...s.values):1,r=f?Math.min(...s.values):0):isNaN(i)&&(i=f?Math.max(...s.values):1),isNaN(r)&&(r=f?Math.min(...s.values):0),r>i){let g=r;i=r,r=g}let c=Math.abs(r);s.absmax=c>i?c:i,s.autoscale?s.autoscale===2?s.scaled=u.autoscale(s.values,s.position,e.settings.nLines,s.centerZero,r,i,s.clamp):(s.scaled=s.values,s.line.scaleY=u.getYScalar(s.values,e.settings.nLines,s.centerZero,r,i),s.line.offsetY=u.getYOffset(s.position,e.settings.nLines,r,s.line.scaleY)):s.scaled=s.values,s.scaled.forEach((g,b)=>{!s.autoscale&&s.absmax>1?s.line.setY(b,g/s.absmax):s.line.setY(b,g)}),this.renderOverlay(o,a,e,s,n,i,r)}}else e.settings.generateNewLines&&!n.includes("timestamp")&&(Array.isArray(t[n])&&(t[n]={values:t[n]}),!t[n].nSec&&!t[n].nPoints&&!e.settings.linePoints&&(t[n].nPoints=1e3),h=true);if(h)return e.settings.cleanGeneration||Object.keys(e.initial.lines).forEach(n=>{t[n]?t[n]=Object.assign(e.initial.lines[n],t[n]):t[n]=e.initial.lines[n]}),this.reinitPlot(e,{_id:e.settings._id,lines:t}),true}else for(let h in e.settings.lines){let n=e.settings.lines[h];this.renderOverlay(o,a,e,n,h,n.ymax,n.ymin)}return l&&requestAnimationFrame(e.anim),true}updateLine(e,t,l,o,a,h,n){return e.numPoints!==t.length&&(l?e.numPoints>t.length?t=u.downsample(t,e.numPoints):e.numPointse.numPoints?t=t.slice(t.length-e.numPoints):t=[...new Array(t.length).fill(0),...t]),o&&(t=u.autoscale(t,a,h,n)),t.forEach((s,r)=>e.setY(r,s)),true}formatTime(e){let t=Math.floor(e/60),l=Math.floor(t/60);t=t%60,e=e%60;let o="";return l>0&&(o+=l+":",t<10&&(o+="0")),o+=t+":",e>0&&(e<10&&(o+="0"),o+=e),o}static autoscale(e,t=0,l=1,o=false,a,h,n){if(e?.length===0)return e;let s=typeof h=="number"?h:e.length<=1e5?Math.max(...e):1,r=typeof a=="number"?a:e.length<=1e5?Math.min(...e):0,i=1/l,f=1;if(o){let c=Math.max(Math.abs(r),Math.abs(s));return c!==0&&(f=i/c),e.map(g=>(n&&(gs&&(g=s)),g*f+(i*(t+1)*2-1-i)))}else return s===r?s!==0?f=i/s:r!==0&&(f=i/Math.abs(r)):f=i/(s-r),e.map(c=>(n&&(cs&&(c=s)),2*((c-r)*f-1/(2*l))+(i*(t+1)*2-1-i)))}static getYScalar(e,t=1,l=false,o,a){if(e?.length===0)return e;let h=typeof a=="number"?a:e.length<=1e5?Math.max(...e):1,n=typeof o=="number"?o:e.length<=1e5?Math.min(...e):0,s=1/t,r=1;if(l){let i=Math.max(Math.abs(n),Math.abs(h));return i!==0&&(r=s/i),2*r}else return h===n?h!==0?r=s/h:n!==0&&(r=s/Math.abs(n)):r=s/(h-n),2*r}static getYOffset(e=0,t=1,l=0,o=1){let a=1/t,h=a*(e+1)*2-1-a;return l!==0?h-=l*o+1/t:h-=o+1/t,h}static absmax(e){return Math.max(Math.abs(Math.min(...e)),Math.max(...e))}static downsample(e,t,l=1){if(e.length>t){let o=new Array(t),a=e.length/t,h=e.length-1,n=0,s=0;for(let r=a;rh&&(i=h);for(let f=n;ft?u.downsample(e,t,l):e.lengthe.length){let l=e.length;e.splice(0,l,...t.slice(t.length-l))}else e.splice(0,e.length,...t);return e}static formatDataForCharts(e,t){if(Array.isArray(e)){if(Array.isArray(e[0])){let l={};if(e.forEach((o,a)=>{l[a]=o}),e=l,isNaN(e[0][0]))return}else if(t){if(e={[t]:e},isNaN(e[t][0]))return}else if(e={0:e},isNaN(e[0][0]))return}else if(typeof e=="object"){for(let l in e)if(typeof e[l]=="number"?e[l]=[e[l]]:e[l]?.values&&typeof e[l].values=="number"&&(e[l].values=[e[l].values]),isNaN(e[l][0]))return}else if(typeof e=="string"){let l;if(e.includes(`\r -`)){let o=e.split(`\r -`);e={},o.forEach((a,h)=>{a.includes(" ")?l=a.split(" "):a.includes(",")?l=a.split(","):a.includes("|")&&(l=a.split("|")),l&&l.forEach((n,s)=>{if(n.includes(":")){let[r,i]=n.split(":"),f=parseFloat(i);isNaN(f)||(e[r]=[f])}else{let r=parseFloat(n);isNaN(r)||(e[s]=[r])}})})}else e.includes(" ")?l=e.split(" "):e.includes(",")?l=e.split(","):e.includes("|")&&(l=e.split("|"));e={},l&&l.forEach((o,a)=>{if(o.includes(":")){let[h,n]=o.split(":"),s=parseFloat(n);isNaN(s)||(e[h]=[s])}else{let h=parseFloat(o);isNaN(h)||(e[a]=[h])}})}else typeof e=="number"&&(t?e={[t]:[e]}:e={0:[e]});return e}static padTime(e,t,l,o){let a=(e[0]-t)/l/o;return[...new Array(o-e.length).map((n,s)=>t+a*(s+1)),...e]}static interpolateForTime(e,t,l){return u.interpolate(e,Math.ceil(l*t))}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new S;return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new S;return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` -
- - - - - - - - - - - - - `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` - - - - - - - - - - - - - - - `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var Math2=class _Math2{constructor(){}static TWO_PI=Math.PI*2;static C=299792458;static G=66743e-15;static h=662607015e-42;static R=8314.32;static Ra=287;static H=69.3;static kbar=1054571817e-43;static kB=1380649e-29;static ke=89875517923e-1;static me=91093837015e-41;static mp=167262192369e-38;static mn=167492749804e-38;static P0=101325;static T0=288.15;static p0=1.225;static Na=60220978e16;static y=1.405;static M0=28.96643;static g0=9.80665;static Re=6378100;static B=1458e-9;static S=110.4;static Sigma=365e-12;static imgkernels={edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]};static HSLToRGB=(h,s,l,scalar=255)=>{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x22=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x22;b=0}else if(60<=h&&h<120){r=x22;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x22}else if(180<=h&&h<240){r=0;g=x22;b=c}else if(240<=h&&h<300){r=x22;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x22}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v2=>v2===a).length-arr.filter(v2=>v2===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean=void 0)=>{let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d2=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean=this.mean(arr);let std=this.std(arr,mean);let z=new Array(arr.length);for(let i=0;ia+(b-mean)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean=this.mean(arr);let std=this.std(arr,mean);return populationMean?std/populationMean:std/mean};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y2)=>acc+Math.pow(y2-meanY,2),0);const ssResidual=observed.reduce((acc,y2,i)=>acc+Math.pow(y2-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p2)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p2*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x22)=>sum+x22,0);const sumY=yCoords.reduce((sum,y2)=>sum+y2,0);const sumXY=xCoords.reduce((sum,x22,i)=>sum+x22*yCoords[i],0);const sumX2=xCoords.reduce((sum,x22)=>sum+x22*x22,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{return vec.map((v2,i)=>v2-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v2,i)=>v2/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x22,y2,z)=>{var r=Math.sqrt(x22*x22+y2*y2+z*z);var theta=Math.atan2(y2,x22);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v2=>(v2-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x22=>{return Math.pow(x22,5)+x22*x22-x22-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y2=x22;return y2},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x22+y2;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w2=x22+y2+z;return w2},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x22;return y2},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x22=Math.cos(t);return x22},yFunc=t=>{let y2=Math.sin(t);return y2},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u2,v2)=>u2,yFunc=(u2,v2)=>v2,zFunc=(u2,v2)=>u2+v2,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u2=rangeU[0];u2{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v2,i,x22,y2)=>{return v2+x22+y2})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v2}, idx:${idx}, x:${i},y:${j}`);return v2+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x22,y2)=>{return[x22*10,y2*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value,index)=>{const row=Array(values.length).fill(0);row[index]=value;return row})};static householderMatrix=v2=>{const size=v2.length;const vvT=v2.map(rowVal=>v2.map(colVal=>rowVal*colVal));const vTv=this.normalize(v2)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A2,B)=>{return A2.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix22*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value=>(value-min)/(max-min))};static garroteThreshold=(data,value)=>{return data.map(x22=>{if(Math.abs(x22)<=value){return 0}else{return x22-value*value/x22}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean1=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v2,i)=>(v2-mean1)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x22,x22),this.cov1d(x22,y2),this.cov1d(x22,z)],[this.cov1d(y2,x22),this.cov1d(y2,y2),this.cov1d(y2,z)],[this.cov1d(z,x22),this.cov1d(z,y2),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v2=>v2-mean)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N2=signalA.length;const M2=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N2=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N2;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x22=arr.filter((element,index)=>{return index%factor===0});return x22};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y2=>y2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x22)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A2,numIter=100)=>{let b=Array(A2.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A2[0].length>A2.length){A2=this.transpose(A2)}const m=A2.length;const n=A2[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A2);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x22):this.normalize(x22);const u2=this.vecsub(x22,e);const normU=this.normalize(u2);const v2=u2.map(val=>val/normU);const Qk=this.householderMatrix(v2);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p2=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p2[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p2[0]=this.matscale(p2[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p2[0]),p2[0]));p2[0]=this.matscale(p2[0],1/p_length);let t_new=this.matmul(mat,p2[0]);let pp=this.matmul(this.transpose(p2[0]),p2[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{ax=ax*this.accelConstant;ay=ay*this.accelConstant;az=az*this.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+this.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+this.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v2,i)=>{return apass(v2,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-this.lastGyroTime;this.lastGyroTime=timestamp;gx=gx*this.gyroConstant+this.gyroXError;gy=gy*this.gyroConstant+this.gyroYError;gz=gz*this.gyroConstant+this.gyroZError;this.gyroXAngle+=gx*elapsed;this.gyroYAngle+=gy*elapsed;this.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:this.gyroXAngle,pitch:this.gyroYAngle,yaw:this.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v2,i)=>{if(result){let r=gpass(v2,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v2,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(this.gyroXAngle||this.gyroYAngle||this.gyroZAngle){result.roll=result.roll*.04+this.gyroXAngle*.96;result.pitch=result.pitch*.04+this.gyroYAngle*.96;result.yaw=this.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-this.lastAccelTime;this.lastAccelTime=timestamp;this.px+=result2.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*.005555555555);this.py+=result2.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*.005555555555);this.pz+=result2.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*.005555555555);result2.px=this.px;result2.py=this.py;result2.pz=this.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{type;freq;sps;Q;dbGain;a0=0;a1=0;a2=0;b0=0;b1=0;b2=0;x1=0;x2=0;y1=0;y2=0;constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A2=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A2+A2);this[type](A2,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A2,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A2,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A2,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A2,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A2,sn,cs,alpha,beta){this.b0=1+alpha*A2;this.b1=-2*cs;this.b2=1-alpha*A2;this.a0=1+alpha/A2;this.a1=-2*cs;this.a2=1-alpha/A2}lowshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1-(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1-(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1+(A2+1)*cs+beta*sn;this.a1=2*(A2-1+(A2+1)*cs);this.a2=A2+1+(A2-1)*cs-beta*sn}highshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1+(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1+(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1-(A2+1)*cs-beta*sn;this.a1=2*(A2-1-(A2+1)*cs);this.a2=A2+1-(A2-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10,__onconnected:function(){if(!this.lowpass){let freq=this.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;this.lowpass=new Biquad("lowpass",this.maxFreq,this.sps);this.peakFinderWindow=Math.floor(this.sps/this.maxFreq);if(this.peakFinderWindow%2===0)this.peakFinderWindow+=1;if(this.peakFinderWindow<5)this.peakFinderWindow=5;this.midpoint=Math.round(this.peakFinderWindow*.5)}},__operator:function(data){if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*this.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){this.refdata.push(amplitude)}this.timestamp.push(timestamp);let beat;if(this.refdata.length>this.peakFinderWindow){this.refdata.shift();this.timestamp.shift()}this.smoothed.push(this.lowpass.applyFilter(this.refdata[this.refdata.length-1]));if(this.smoothed.length>this.peakFinderWindow){this.smoothed.shift()}if(this.smoothed.length===this.peakFinderWindow){if(Math2.isExtrema(this.smoothed,"valley")){this.valleys.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}else if(Math2.isExtrema(this.smoothed,"peak")){this.peaks.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}if(this.valleys.length>2&&this.peaks.length>2){if(this.valleys[this.valleys.length-1].timestamp1&&this.valley_distances.length>1){if(this.lastPeakthis.peak_distances[this.peak_distances.length-1].timestamp){let bpm,change=0;if(this.beats.length<1){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].distance+this.valley_distances[this.valley_distances.length-1].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-1].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].dt+this.valley_distances[this.valley_distances.length-1].dt));change=Math.abs(bpm-this.beats[this.beats.length-1].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-1].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-1].peak0-this.valley_distances[this.valley_distances.length-1].peak0,height1:this.peak_distances[this.peak_distances.length-1].peak1-this.valley_distances[this.valley_distances.length-1].peak1};this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}else{let bpm,change=0;if(this.beats.length<2){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-2].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance));change=Math.abs(bpm-this.beats[this.beats.length-2].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-2].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0,height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1};if(Array.isArray(beat.timestamp))beat.timestamp=beat.timestamp[0];this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}}}if(this.peaks.length>this.limit){this.peaks.shift()}if(this.valleys.length>this.limit){this.valleys.shift()}if(this.peak_distances.length>this.limit){this.peak_distances.shift()}if(this.valley_distances.length>this.limit){this.valley_distances.shift()}if(this.beats.length>this.limit){this.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)result=data.red.map((v2,i)=>{return pass(v2+data.ir[i],data.timestamp[i])}).filter(v2=>{if(v2)return true});else result=data.red.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}}};var blink_detect={sps:250,intervals:{},watch:["0"],tolerance:.2,__onconnected:node=>{node.watch.forEach(ch=>node.intervals[ch]={lowpass:new Biquad("lowpass",20,node.sps),filtered:[],averaged:[]})},__operator:function(data){let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=this.intervals[key].lowpass.applyFilter(n);this.intervals[key].filtered.push(next);this.intervals[key].averaged.push(next);if(this.intervals[key].filtered.length>checkCt){if(this.intervals[key].averaged.length>averageCt){this.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(this.intervals[key].averaged);if(Math.abs(Math.min(...this.intervals[key].filtered))>Math.abs(mean)+this.tolerance){this.intervals[key].filtered.length=0;passed=true;found[key]=true}}else this.intervals[key].filtered.shift()}};for(const key in this.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var ArrayManip=class _ArrayManip{static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,...newEntries.slice(newEntries.length-len))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d2={};data.forEach((arr,i)=>{d2[i]=arr});data=d2;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}static bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target};spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var rechk=/^([<>])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v2,o,c)=>String.fromCharCode(...new Uint8Array(v2.buffer,v2.byteOffset+o,c));var rts=(v2,o,c,s)=>new Uint8Array(v2.buffer,v2.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v2,o,c)=>str(v2,o+1,Math.min(v2.getUint8(o),c-1));var tsp=(v2,o,c,s)=>{v2.setUint8(o,s.length);rts(v2,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v2=>str(v2,o,1),p:(v2,c2)=>rts(v2,o,1,c2)})],"?":c=>[c,1,o=>({u:v2=>Boolean(v2.getUint8(o)),p:(v2,B)=>v2.setUint8(o,B)})],b:c=>[c,1,o=>({u:v2=>v2.getInt8(o),p:(v2,b)=>v2.setInt8(o,b)})],B:c=>[c,1,o=>({u:v2=>v2.getUint8(o),p:(v2,B)=>v2.setUint8(o,B)})],h:c=>[c,2,o=>({u:v2=>v2.getInt16(o,le),p:(v2,h)=>v2.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v2=>v2.getUint16(o,le),p:(v2,H)=>v2.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v2=>v2.getInt32(o,le),p:(v2,i)=>v2.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v2=>v2.getUint32(o,le),p:(v2,I)=>v2.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v2=>v2.getFloat32(o,le),p:(v2,f)=>v2.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v2=>v2.getFloat64(o,le),p:(v2,d2)=>v2.setFloat64(o,d2,le)})],s:c=>[1,c,o=>({u:v2=>str(v2,o,c),p:(v2,s)=>rts(v2,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v2=>pst(v2,o,c),p:(v2,s)=>tsp(v2,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var ByteParser=class _ByteParser extends ArrayManip{static codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x22){let int24=(255&x0)<<16|(255&x1)<<8|255&x22;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x22){return x0*65536+x1*256+x22}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x22,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x22)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x22,x3){return x0*16777216+x1*65536+x22*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M2=pattern.length;if(M2===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R2=256;var rightmost_positions=new Int32Array(R2);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v2=new DataView(arrb,offs|0);return fns.map(f=>f.u(v2))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v2,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var rms={sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{},__operator:function(data){this.watch.forEach(key=>{if(data[key]){if(!this.data[key]){if(Array.isArray(data[key])){this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0])}else this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key])}ByteParser.circularBuffer(this.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){this.rms.timestamp=data.timestamp[data.timestamp.length-1]}else this.rms.timestamp=data.timestamp}else this.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(this.watch.map(async key=>{if(this.data[key])this.rms[key]=Math.sqrt(Math.abs(this.data[key].reduce((p2,v2,i)=>p2+v2*v2)/this.data[key].length));else delete this.rms[key]}));res(this.rms)})}};var circularBuffer2d={bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false,__onconnected:function(node){for(const key in node.watch){node.data[key]=new Array(node.bufferSize).fill(0)}},__operator:function(data){let buffer2d=[];this.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(this.data[key],data[key]);buffer2d.push(this.data[key])}});return buffer2d}};var algorithms={beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d};algorithms["breath"].maxFreq=.2;export{StructBackend,StructFrontend,Systems,S as WebglLinePlotUtil,algorithms,defaultSpecifiers,genTimeSpecifiers,genTimestampFromString,getStringId,pseudoObjectId,randomId,setSignalControls,toObjectId,webglPlotRoutes}; diff --git a/src/extras/dist/index.services.js b/src/extras/dist/index.services.js deleted file mode 100644 index 1f46d0eb..00000000 --- a/src/extras/dist/index.services.js +++ /dev/null @@ -1,50 +0,0 @@ -(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x3=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x3,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x3)(function(x3){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x3+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_bson=__commonJS({"struct/datastructures/bson.cjs"(exports){"use strict";var BSON_MAJOR_VERSION=5;var BSON_INT32_MAX=2147483647;var BSON_INT32_MIN=-2147483648;var BSON_INT64_MAX=Math.pow(2,63)-1;var BSON_INT64_MIN=-Math.pow(2,63);var JS_INT_MAX=Math.pow(2,53);var JS_INT_MIN=-Math.pow(2,53);var BSON_DATA_NUMBER=1;var BSON_DATA_STRING=2;var BSON_DATA_OBJECT=3;var BSON_DATA_ARRAY=4;var BSON_DATA_BINARY=5;var BSON_DATA_UNDEFINED=6;var BSON_DATA_OID=7;var BSON_DATA_BOOLEAN=8;var BSON_DATA_DATE=9;var BSON_DATA_NULL=10;var BSON_DATA_REGEXP=11;var BSON_DATA_DBPOINTER=12;var BSON_DATA_CODE=13;var BSON_DATA_SYMBOL=14;var BSON_DATA_CODE_W_SCOPE=15;var BSON_DATA_INT=16;var BSON_DATA_TIMESTAMP=17;var BSON_DATA_LONG=18;var BSON_DATA_DECIMAL128=19;var BSON_DATA_MIN_KEY=255;var BSON_DATA_MAX_KEY=127;var BSON_BINARY_SUBTYPE_DEFAULT=0;var BSON_BINARY_SUBTYPE_UUID_NEW=4;var BSONType=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});var BSONError=class extends Error{get bsonError(){return true}get name(){return"BSONError"}constructor(message){super(message)}static isBSONError(value){return value!=null&&typeof value==="object"&&"bsonError"in value&&value.bsonError===true&&"name"in value&&"message"in value&&"stack"in value}};var BSONVersionError=class extends BSONError{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`)}};var BSONRuntimeError=class extends BSONError{get name(){return"BSONRuntimeError"}constructor(message){super(message)}};function nodejsMathRandomBytes(byteLength){return nodeJsByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var nodejsRandomBytes=(()=>{try{return __require("crypto").randomBytes}catch{return nodejsMathRandomBytes}})();var nodeJsByteUtils={toLocalBufferType(potentialBuffer){if(Buffer.isBuffer(potentialBuffer)){return potentialBuffer}if(ArrayBuffer.isView(potentialBuffer)){return Buffer.from(potentialBuffer.buffer,potentialBuffer.byteOffset,potentialBuffer.byteLength)}const stringTag=potentialBuffer?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialBuffer);if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return Buffer.from(potentialBuffer)}throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`)},allocate(size){return Buffer.alloc(size)},equals(a,b){return nodeJsByteUtils.toLocalBufferType(a).equals(b)},fromNumberArray(array){return Buffer.from(array)},fromBase64(base64){return Buffer.from(base64,"base64")},toBase64(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64")},fromISO88591(codePoints){return Buffer.from(codePoints,"binary")},toISO88591(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary")},fromHex(hex){return Buffer.from(hex,"hex")},toHex(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex")},fromUTF8(text){return Buffer.from(text,"utf8")},toUTF8(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8")},utf8ByteLength(input){return Buffer.byteLength(input,"utf8")},encodeUTF8Into(buffer2,source,byteOffset){return nodeJsByteUtils.toLocalBufferType(buffer2).write(source,byteOffset,void 0,"utf8")},randomBytes:nodejsRandomBytes};function isReactNative(){const{navigator}=globalThis;return typeof navigator==="object"&&navigator.product==="ReactNative"}function webMathRandomBytes(byteLength){if(byteLength<0){throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`)}return webByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var webRandomBytes=(()=>{const{crypto}=globalThis;if(crypto!=null&&typeof crypto.getRandomValues==="function"){return byteLength=>{return crypto.getRandomValues(webByteUtils.allocate(byteLength))}}else{if(isReactNative()){const{console:console2}=globalThis;console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return webMathRandomBytes}})();var HEX_DIGIT=/(\d|[a-f])/i;var webByteUtils={toLocalBufferType(potentialUint8array){const stringTag=potentialUint8array?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialUint8array);if(stringTag==="Uint8Array"){return potentialUint8array}if(ArrayBuffer.isView(potentialUint8array)){return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset,potentialUint8array.byteOffset+potentialUint8array.byteLength))}if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return new Uint8Array(potentialUint8array)}throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`)},allocate(size){if(typeof size!=="number"){throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`)}return new Uint8Array(size)},equals(a,b){if(a.byteLength!==b.byteLength){return false}for(let i=0;ic.charCodeAt(0))},toBase64(uint8array){return btoa(webByteUtils.toISO88591(uint8array))},fromISO88591(codePoints){return Uint8Array.from(codePoints,c=>c.charCodeAt(0)&255)},toISO88591(uint8array){return Array.from(Uint16Array.from(uint8array),b=>String.fromCharCode(b)).join("")},fromHex(hex){const evenLengthHex=hex.length%2===0?hex:hex.slice(0,hex.length-1);const buffer2=[];for(let i=0;ibyte.toString(16).padStart(2,"0")).join("")},fromUTF8(text){return new TextEncoder().encode(text)},toUTF8(uint8array){return new TextDecoder("utf8",{fatal:false}).decode(uint8array)},utf8ByteLength(input){return webByteUtils.fromUTF8(input).byteLength},encodeUTF8Into(buffer2,source,byteOffset){const bytes=webByteUtils.fromUTF8(source);buffer2.set(bytes,byteOffset);return bytes.byteLength},randomBytes:webRandomBytes};var hasGlobalBuffer=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==true;var ByteUtils=hasGlobalBuffer?nodeJsByteUtils:webByteUtils;var BSONDataView=class extends DataView{static fromUint8Array(input){return new DataView(input.buffer,input.byteOffset,input.byteLength)}};var VALIDATION_REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;var uuidValidateString=str2=>typeof str2==="string"&&VALIDATION_REGEX.test(str2);var uuidHexStringToBuffer=hexString=>{if(!uuidValidateString(hexString)){throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".')}const sanitizedHexString=hexString.replace(/-/g,"");return ByteUtils.fromHex(sanitizedHexString)};function bufferToUuidHexString(buffer2,includeDashes=true){if(includeDashes){return[ByteUtils.toHex(buffer2.subarray(0,4)),ByteUtils.toHex(buffer2.subarray(4,6)),ByteUtils.toHex(buffer2.subarray(6,8)),ByteUtils.toHex(buffer2.subarray(8,10)),ByteUtils.toHex(buffer2.subarray(10,16))].join("-")}return ByteUtils.toHex(buffer2)}function isAnyArrayBuffer(value){return["[object ArrayBuffer]","[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value))}function isUint8Array(value){return Object.prototype.toString.call(value)==="[object Uint8Array]"}function isRegExp(d2){return Object.prototype.toString.call(d2)==="[object RegExp]"}function isMap(d2){return Object.prototype.toString.call(d2)==="[object Map]"}function isDate(d2){return Object.prototype.toString.call(d2)==="[object Date]"}var BSONValue=class{get[Symbol.for("@@mdb.bson.version")](){return BSON_MAJOR_VERSION}};var Binary=class _Binary extends BSONValue{get _bsontype(){return"Binary"}constructor(buffer2,subType){super();if(!(buffer2==null)&&!(typeof buffer2==="string")&&!ArrayBuffer.isView(buffer2)&&!(buffer2 instanceof ArrayBuffer)&&!Array.isArray(buffer2)){throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array")}this.sub_type=subType??_Binary.BSON_BINARY_SUBTYPE_DEFAULT;if(buffer2==null){this.buffer=ByteUtils.allocate(_Binary.BUFFER_SIZE);this.position=0}else{if(typeof buffer2==="string"){this.buffer=ByteUtils.fromISO88591(buffer2)}else if(Array.isArray(buffer2)){this.buffer=ByteUtils.fromNumberArray(buffer2)}else{this.buffer=ByteUtils.toLocalBufferType(buffer2)}this.position=this.buffer.byteLength}}put(byteValue){if(typeof byteValue==="string"&&byteValue.length!==1){throw new BSONError("only accepts single character String")}else if(typeof byteValue!=="number"&&byteValue.length!==1)throw new BSONError("only accepts single character Uint8Array or Array");let decodedByte;if(typeof byteValue==="string"){decodedByte=byteValue.charCodeAt(0)}else if(typeof byteValue==="number"){decodedByte=byteValue}else{decodedByte=byteValue[0]}if(decodedByte<0||decodedByte>255){throw new BSONError("only accepts number in a valid unsigned byte range 0-255")}if(this.buffer.byteLength>this.position){this.buffer[this.position++]=decodedByte}else{const newSpace=ByteUtils.allocate(_Binary.BUFFER_SIZE+this.buffer.length);newSpace.set(this.buffer,0);this.buffer=newSpace;this.buffer[this.position++]=decodedByte}}write(sequence,offset){offset=typeof offset==="number"?offset:this.position;if(this.buffer.byteLengththis.position?offset+sequence.length:this.position}else if(typeof sequence==="string"){const bytes=ByteUtils.fromISO88591(sequence);this.buffer.set(bytes,offset);this.position=offset+sequence.length>this.position?offset+sequence.length:this.position}}read(position,length){length=length&&length>0?length:this.position;return this.buffer.slice(position,position+length)}value(asRaw){asRaw=!!asRaw;if(asRaw&&this.buffer.length===this.position){return this.buffer}if(asRaw){return this.buffer.slice(0,this.position)}return ByteUtils.toISO88591(this.buffer.subarray(0,this.position))}length(){return this.position}toJSON(){return ByteUtils.toBase64(this.buffer)}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.buffer);if(encoding==="base64")return ByteUtils.toBase64(this.buffer);if(encoding==="utf8"||encoding==="utf-8")return ByteUtils.toUTF8(this.buffer);return ByteUtils.toUTF8(this.buffer)}toExtendedJSON(options){options=options||{};const base64String=ByteUtils.toBase64(this.buffer);const subType=Number(this.sub_type).toString(16);if(options.legacy){return{$binary:base64String,$type:subType.length===1?"0"+subType:subType}}return{$binary:{base64:base64String,subType:subType.length===1?"0"+subType:subType}}}toUUID(){if(this.sub_type===_Binary.SUBTYPE_UUID){return new UUID(this.buffer.slice(0,this.position))}throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`)}static fromExtendedJSON(doc,options){options=options||{};let data;let type;if("$binary"in doc){if(options.legacy&&typeof doc.$binary==="string"&&"$type"in doc){type=doc.$type?parseInt(doc.$type,16):0;data=ByteUtils.fromBase64(doc.$binary)}else{if(typeof doc.$binary!=="string"){type=doc.$binary.subType?parseInt(doc.$binary.subType,16):0;data=ByteUtils.fromBase64(doc.$binary.base64)}}}else if("$uuid"in doc){type=4;data=uuidHexStringToBuffer(doc.$uuid)}if(!data){throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`)}return type===BSON_BINARY_SUBTYPE_UUID_NEW?new UUID(data):new _Binary(data,type)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`}};Binary.BSON_BINARY_SUBTYPE_DEFAULT=0;Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_ENCRYPTED=6;Binary.SUBTYPE_COLUMN=7;Binary.SUBTYPE_USER_DEFINED=128;var UUID_BYTE_LENGTH=16;var UUID=class _UUID extends Binary{constructor(input){let bytes;let hexStr;if(input==null){bytes=_UUID.generate()}else if(input instanceof _UUID){bytes=ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));hexStr=input.__id}else if(ArrayBuffer.isView(input)&&input.byteLength===UUID_BYTE_LENGTH){bytes=ByteUtils.toLocalBufferType(input)}else if(typeof input==="string"){bytes=uuidHexStringToBuffer(input)}else{throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).")}super(bytes,BSON_BINARY_SUBTYPE_UUID_NEW);this.__id=hexStr}get id(){return this.buffer}set id(value){this.buffer=value;if(_UUID.cacheHexString){this.__id=bufferToUuidHexString(value)}}toHexString(includeDashes=true){if(_UUID.cacheHexString&&this.__id){return this.__id}const uuidHexString=bufferToUuidHexString(this.id,includeDashes);if(_UUID.cacheHexString){this.__id=uuidHexString}return uuidHexString}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.id);if(encoding==="base64")return ByteUtils.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(!otherId){return false}if(otherId instanceof _UUID){return ByteUtils.equals(otherId.id,this.id)}try{return ByteUtils.equals(new _UUID(otherId).id,this.id)}catch{return false}}toBinary(){return new Binary(this.id,Binary.SUBTYPE_UUID)}static generate(){const bytes=ByteUtils.randomBytes(UUID_BYTE_LENGTH);bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return bytes}static isValid(input){if(!input){return false}if(input instanceof _UUID){return true}if(typeof input==="string"){return uuidValidateString(input)}if(isUint8Array(input)){if(input.byteLength!==UUID_BYTE_LENGTH){return false}return(input[6]&240)===64&&(input[8]&128)===128}return false}static createFromHexString(hexString){const buffer2=uuidHexStringToBuffer(hexString);return new _UUID(buffer2)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new UUID("${this.toHexString()}")`}};var Code=class _Code extends BSONValue{get _bsontype(){return"Code"}constructor(code,scope){super();this.code=code.toString();this.scope=scope??null}toJSON(){if(this.scope!=null){return{code:this.code,scope:this.scope}}return{code:this.code}}toExtendedJSON(){if(this.scope){return{$code:this.code,$scope:this.scope}}return{$code:this.code}}static fromExtendedJSON(doc){return new _Code(doc.$code,doc.$scope)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const codeJson=this.toJSON();return`new Code("${String(codeJson.code)}"${codeJson.scope!=null?`, ${JSON.stringify(codeJson.scope)}`:""})`}};function isDBRefLike(value){return value!=null&&typeof value==="object"&&"$id"in value&&value.$id!=null&&"$ref"in value&&typeof value.$ref==="string"&&(!("$db"in value)||"$db"in value&&typeof value.$db==="string")}var DBRef=class _DBRef extends BSONValue{get _bsontype(){return"DBRef"}constructor(collection,oid,db,fields){super();const parts=collection.split(".");if(parts.length===2){db=parts.shift();collection=parts.shift()}this.collection=collection;this.oid=oid;this.db=db;this.fields=fields||{}}get namespace(){return this.collection}set namespace(value){this.collection=value}toJSON(){const o=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)o.$db=this.db;return o}toExtendedJSON(options){options=options||{};let o={$ref:this.collection,$id:this.oid};if(options.legacy){return o}if(this.db)o.$db=this.db;o=Object.assign(o,this.fields);return o}static fromExtendedJSON(doc){const copy=Object.assign({},doc);delete copy.$ref;delete copy.$id;delete copy.$db;return new _DBRef(doc.$ref,doc.$id,doc.$db,copy)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const oid=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return`new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db?`, "${this.db}"`:""})`}};var wasm=void 0;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var INT_CACHE={};var UINT_CACHE={};var MAX_INT64_STRING_LENGTH=20;var DECIMAL_REG_EX=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;var Long=class _Long extends BSONValue{get _bsontype(){return"Long"}get __isLong__(){return true}constructor(low=0,high,unsigned){super();if(typeof low==="bigint"){Object.assign(this,_Long.fromBigInt(low,!!high))}else if(typeof low==="string"){Object.assign(this,_Long.fromString(low,!!high))}else{this.low=low|0;this.high=high|0;this.unsigned=!!unsigned}}static fromBits(lowBits,highBits,unsigned){return new _Long(lowBits,highBits,unsigned)}static fromInt(value,unsigned){let obj,cachedObj,cache;if(unsigned){value>>>=0;if(cache=0<=value&&value<256){cachedObj=UINT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,(value|0)<0?-1:0,true);if(cache)UINT_CACHE[value]=obj;return obj}else{value|=0;if(cache=-128<=value&&value<128){cachedObj=INT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,value<0?-1:0,false);if(cache)INT_CACHE[value]=obj;return obj}}static fromNumber(value,unsigned){if(isNaN(value))return unsigned?_Long.UZERO:_Long.ZERO;if(unsigned){if(value<0)return _Long.UZERO;if(value>=TWO_PWR_64_DBL)return _Long.MAX_UNSIGNED_VALUE}else{if(value<=-TWO_PWR_63_DBL)return _Long.MIN_VALUE;if(value+1>=TWO_PWR_63_DBL)return _Long.MAX_VALUE}if(value<0)return _Long.fromNumber(-value,unsigned).neg();return _Long.fromBits(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0,unsigned)}static fromBigInt(value,unsigned){return _Long.fromString(value.toString(),unsigned)}static fromString(str2,unsigned,radix){if(str2.length===0)throw new BSONError("empty string");if(str2==="NaN"||str2==="Infinity"||str2==="+Infinity"||str2==="-Infinity")return _Long.ZERO;if(typeof unsigned==="number"){radix=unsigned,unsigned=false}else{unsigned=!!unsigned}radix=radix||10;if(radix<2||360)throw new BSONError("interior hyphen");else if(p2===0){return _Long.fromString(str2.substring(1),unsigned,radix).neg()}const radixToPower=_Long.fromNumber(Math.pow(radix,8));let result=_Long.ZERO;for(let i=0;i>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=addend.high>>>16;const b32=addend.high&65535;const b16=addend.low>>>16;const b00=addend.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}and(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low&other.low,this.high&other.high,this.unsigned)}compare(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.eq(other))return 0;const thisNeg=this.isNegative(),otherNeg=other.isNegative();if(thisNeg&&!otherNeg)return-1;if(!thisNeg&&otherNeg)return 1;if(!this.unsigned)return this.sub(other).isNegative()?-1:1;return other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}comp(other){return this.compare(other)}divide(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(divisor.isZero())throw new BSONError("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&divisor.low===-1&&divisor.high===-1){return this}const low=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?_Long.UZERO:_Long.ZERO;let approx,rem,res;if(!this.unsigned){if(this.eq(_Long.MIN_VALUE)){if(divisor.eq(_Long.ONE)||divisor.eq(_Long.NEG_ONE))return _Long.MIN_VALUE;else if(divisor.eq(_Long.MIN_VALUE))return _Long.ONE;else{const halfThis=this.shr(1);approx=halfThis.div(divisor).shl(1);if(approx.eq(_Long.ZERO)){return divisor.isNegative()?_Long.ONE:_Long.NEG_ONE}else{rem=this.sub(divisor.mul(approx));res=approx.add(rem.div(divisor));return res}}}else if(divisor.eq(_Long.MIN_VALUE))return this.unsigned?_Long.UZERO:_Long.ZERO;if(this.isNegative()){if(divisor.isNegative())return this.neg().div(divisor.neg());return this.neg().div(divisor).neg()}else if(divisor.isNegative())return this.div(divisor.neg()).neg();res=_Long.ZERO}else{if(!divisor.unsigned)divisor=divisor.toUnsigned();if(divisor.gt(this))return _Long.UZERO;if(divisor.gt(this.shru(1)))return _Long.UONE;res=_Long.UZERO}rem=this;while(rem.gte(divisor)){approx=Math.max(1,Math.floor(rem.toNumber()/divisor.toNumber()));const log2=Math.ceil(Math.log(approx)/Math.LN2);const delta=log2<=48?1:Math.pow(2,log2-48);let approxRes=_Long.fromNumber(approx);let approxRem=approxRes.mul(divisor);while(approxRem.isNegative()||approxRem.gt(rem)){approx-=delta;approxRes=_Long.fromNumber(approx,this.unsigned);approxRem=approxRes.mul(divisor)}if(approxRes.isZero())approxRes=_Long.ONE;res=res.add(approxRes);rem=rem.sub(approxRem)}return res}div(divisor){return this.divide(divisor)}equals(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.unsigned!==other.unsigned&&this.high>>>31===1&&other.high>>>31===1)return false;return this.high===other.high&&this.low===other.low}eq(other){return this.equals(other)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative()){return this.eq(_Long.MIN_VALUE)?64:this.neg().getNumBitsAbs()}const val=this.high!==0?this.high:this.low;let bit;for(bit=31;bit>0;bit--)if((val&1<0}gt(other){return this.greaterThan(other)}greaterThanOrEqual(other){return this.comp(other)>=0}gte(other){return this.greaterThanOrEqual(other)}ge(other){return this.greaterThanOrEqual(other)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(other){return this.comp(other)<0}lt(other){return this.lessThan(other)}lessThanOrEqual(other){return this.comp(other)<=0}lte(other){return this.lessThanOrEqual(other)}modulo(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(wasm){const low=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}return this.sub(this.div(divisor).mul(divisor))}mod(divisor){return this.modulo(divisor)}rem(divisor){return this.modulo(divisor)}multiply(multiplier){if(this.isZero())return _Long.ZERO;if(!_Long.isLong(multiplier))multiplier=_Long.fromValue(multiplier);if(wasm){const low=wasm.mul(this.low,this.high,multiplier.low,multiplier.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(multiplier.isZero())return _Long.ZERO;if(this.eq(_Long.MIN_VALUE))return multiplier.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(multiplier.eq(_Long.MIN_VALUE))return this.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(this.isNegative()){if(multiplier.isNegative())return this.neg().mul(multiplier.neg());else return this.neg().mul(multiplier).neg()}else if(multiplier.isNegative())return this.mul(multiplier.neg()).neg();if(this.lt(_Long.TWO_PWR_24)&&multiplier.lt(_Long.TWO_PWR_24))return _Long.fromNumber(this.toNumber()*multiplier.toNumber(),this.unsigned);const a48=this.high>>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=multiplier.high>>>16;const b32=multiplier.high&65535;const b16=multiplier.low>>>16;const b00=multiplier.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}mul(multiplier){return this.multiply(multiplier)}negate(){if(!this.unsigned&&this.eq(_Long.MIN_VALUE))return _Long.MIN_VALUE;return this.not().add(_Long.ONE)}neg(){return this.negate()}not(){return _Long.fromBits(~this.low,~this.high,this.unsigned)}notEquals(other){return!this.equals(other)}neq(other){return this.notEquals(other)}ne(other){return this.notEquals(other)}or(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low|other.low,this.high|other.high,this.unsigned)}shiftLeft(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();if((numBits&=63)===0)return this;else if(numBits<32)return _Long.fromBits(this.low<>>32-numBits,this.unsigned);else return _Long.fromBits(0,this.low<>>numBits|this.high<<32-numBits,this.high>>numBits,this.unsigned);else return _Long.fromBits(this.high>>numBits-32,this.high>=0?0:-1,this.unsigned)}shr(numBits){return this.shiftRight(numBits)}shiftRightUnsigned(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();numBits&=63;if(numBits===0)return this;else{const high=this.high;if(numBits<32){const low=this.low;return _Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits,this.unsigned)}else if(numBits===32)return _Long.fromBits(high,0,this.unsigned);else return _Long.fromBits(high>>>numBits-32,0,this.unsigned)}}shr_u(numBits){return this.shiftRightUnsigned(numBits)}shru(numBits){return this.shiftRightUnsigned(numBits)}subtract(subtrahend){if(!_Long.isLong(subtrahend))subtrahend=_Long.fromValue(subtrahend);return this.add(subtrahend.neg())}sub(subtrahend){return this.subtract(subtrahend)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(le){return le?this.toBytesLE():this.toBytesBE()}toBytesLE(){const hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}toBytesBE(){const hi=this.high,lo=this.low;return[hi>>>24,hi>>>16&255,hi>>>8&255,hi&255,lo>>>24,lo>>>16&255,lo>>>8&255,lo&255]}toSigned(){if(!this.unsigned)return this;return _Long.fromBits(this.low,this.high,false)}toString(radix){radix=radix||10;if(radix<2||36>>0;let digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6)digits="0"+digits;result=""+digits+result}}}toUnsigned(){if(this.unsigned)return this;return _Long.fromBits(this.low,this.high,true)}xor(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low^other.low,this.high^other.high,this.unsigned)}eqz(){return this.isZero()}le(other){return this.lessThanOrEqual(other)}toExtendedJSON(options){if(options&&options.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(doc,options){const{useBigInt64=false,relaxed=true}={...options};if(doc.$numberLong.length>MAX_INT64_STRING_LENGTH){throw new BSONError("$numberLong string is too long")}if(!DECIMAL_REG_EX.test(doc.$numberLong)){throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`)}if(useBigInt64){const bigIntResult=BigInt(doc.$numberLong);return BigInt.asIntN(64,bigIntResult)}const longResult=_Long.fromString(doc.$numberLong);if(relaxed){return longResult.toNumber()}return longResult}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Long("${this.toString()}"${this.unsigned?", true":""})`}};Long.TWO_PWR_24=Long.fromInt(TWO_PWR_24_DBL);Long.MAX_UNSIGNED_VALUE=Long.fromBits(4294967295|0,4294967295|0,true);Long.ZERO=Long.fromInt(0);Long.UZERO=Long.fromInt(0,true);Long.ONE=Long.fromInt(1);Long.UONE=Long.fromInt(1,true);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0,false);Long.MIN_VALUE=Long.fromBits(0,2147483648|0,false);var PARSE_STRING_REGEXP=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var PARSE_INF_REGEXP=/^(\+|-)?(Infinity|inf)$/i;var PARSE_NAN_REGEXP=/^(\+|-)?NaN$/i;var EXPONENT_MAX=6111;var EXPONENT_MIN=-6176;var EXPONENT_BIAS=6176;var MAX_DIGITS=34;var NAN_BUFFER=ByteUtils.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_NEGATIVE_BUFFER=ByteUtils.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_POSITIVE_BUFFER=ByteUtils.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var EXPONENT_REGEX=/^([-+])?(\d+)?$/;var COMBINATION_MASK=31;var EXPONENT_MASK=16383;var COMBINATION_INFINITY=30;var COMBINATION_NAN=31;function isDigit(value){return!isNaN(parseInt(value,10))}function divideu128(value){const DIVISOR=Long.fromNumber(1e3*1e3*1e3);let _rem=Long.fromNumber(0);if(!value.parts[0]&&!value.parts[1]&&!value.parts[2]&&!value.parts[3]){return{quotient:value,rem:_rem}}for(let i=0;i<=3;i++){_rem=_rem.shiftLeft(32);_rem=_rem.add(new Long(value.parts[i],0));value.parts[i]=_rem.div(DIVISOR).low;_rem=_rem.modulo(DIVISOR)}return{quotient:value,rem:_rem}}function multiply64x2(left,right){if(!left&&!right){return{high:Long.fromNumber(0),low:Long.fromNumber(0)}}const leftHigh=left.shiftRightUnsigned(32);const leftLow=new Long(left.getLowBits(),0);const rightHigh=right.shiftRightUnsigned(32);const rightLow=new Long(right.getLowBits(),0);let productHigh=leftHigh.multiply(rightHigh);let productMid=leftHigh.multiply(rightLow);const productMid2=leftLow.multiply(rightHigh);let productLow=leftLow.multiply(rightLow);productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productMid=new Long(productMid.getLowBits(),0).add(productMid2).add(productLow.shiftRightUnsigned(32));productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productLow=productMid.shiftLeft(32).add(new Long(productLow.getLowBits(),0));return{high:productHigh,low:productLow}}function lessThan(left,right){const uhleft=left.high>>>0;const uhright=right.high>>>0;if(uhleft>>0;const ulright=right.low>>>0;if(ulleft=7e3){throw new BSONError(""+representation+" not a valid Decimal128 string")}const stringMatch=representation.match(PARSE_STRING_REGEXP);const infMatch=representation.match(PARSE_INF_REGEXP);const nanMatch=representation.match(PARSE_NAN_REGEXP);if(!stringMatch&&!infMatch&&!nanMatch||representation.length===0){throw new BSONError(""+representation+" not a valid Decimal128 string")}if(stringMatch){const unsignedNumber=stringMatch[2];const e=stringMatch[4];const expSign=stringMatch[5];const expNumber=stringMatch[6];if(e&&expNumber===void 0)invalidErr(representation,"missing exponent power");if(e&&unsignedNumber===void 0)invalidErr(representation,"missing exponent base");if(e===void 0&&(expSign||expNumber)){invalidErr(representation,"missing e before exponent")}}if(representation[index]==="+"||representation[index]==="-"){isNegative=representation[index++]==="-"}if(!isDigit(representation[index])&&representation[index]!=="."){if(representation[index]==="i"||representation[index]==="I"){return new _Decimal128(isNegative?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER)}else if(representation[index]==="N"){return new _Decimal128(NAN_BUFFER)}}while(isDigit(representation[index])||representation[index]==="."){if(representation[index]==="."){if(sawRadix)invalidErr(representation,"contains multiple periods");sawRadix=true;index=index+1;continue}if(nDigitsStored<34){if(representation[index]!=="0"||foundNonZero){if(!foundNonZero){firstNonZero=nDigitsRead}foundNonZero=true;digits[digitsInsert++]=parseInt(representation[index],10);nDigitsStored=nDigitsStored+1}}if(foundNonZero)nDigits=nDigits+1;if(sawRadix)radixPosition=radixPosition+1;nDigitsRead=nDigitsRead+1;index=index+1}if(sawRadix&&!nDigitsRead)throw new BSONError(""+representation+" not a valid Decimal128 string");if(representation[index]==="e"||representation[index]==="E"){const match=representation.substr(++index).match(EXPONENT_REGEX);if(!match||!match[2])return new _Decimal128(NAN_BUFFER);exponent=parseInt(match[0],10);index=index+match[0].length}if(representation[index])return new _Decimal128(NAN_BUFFER);firstDigit=0;if(!nDigitsStored){firstDigit=0;lastDigit=0;digits[0]=0;nDigits=1;nDigitsStored=1;significantDigits=0}else{lastDigit=nDigitsStored-1;significantDigits=nDigits;if(significantDigits!==1){while(digits[firstNonZero+significantDigits-1]===0){significantDigits=significantDigits-1}}}if(exponent<=radixPosition&&radixPosition-exponent>1<<14){exponent=EXPONENT_MIN}else{exponent=exponent-radixPosition}while(exponent>EXPONENT_MAX){lastDigit=lastDigit+1;if(lastDigit-firstDigit>MAX_DIGITS){const digitsString=digits.join("");if(digitsString.match(/^0+$/)){exponent=EXPONENT_MAX;break}invalidErr(representation,"overflow")}exponent=exponent-1}while(exponent=5){roundBit=1;if(roundDigit===5){roundBit=digits[lastDigit]%2===1?1:0;for(i=firstNonZero+lastDigit+2;i=0;dIdx--){if(++digits[dIdx]>9){digits[dIdx]=0;if(dIdx===0){if(exponent>8&255;buffer2[index++]=dec.low.low>>16&255;buffer2[index++]=dec.low.low>>24&255;buffer2[index++]=dec.low.high&255;buffer2[index++]=dec.low.high>>8&255;buffer2[index++]=dec.low.high>>16&255;buffer2[index++]=dec.low.high>>24&255;buffer2[index++]=dec.high.low&255;buffer2[index++]=dec.high.low>>8&255;buffer2[index++]=dec.high.low>>16&255;buffer2[index++]=dec.high.low>>24&255;buffer2[index++]=dec.high.high&255;buffer2[index++]=dec.high.high>>8&255;buffer2[index++]=dec.high.high>>16&255;buffer2[index++]=dec.high.high>>24&255;return new _Decimal128(buffer2)}toString(){let biased_exponent;let significand_digits=0;const significand=new Array(36);for(let i=0;i>26&COMBINATION_MASK;if(combination>>3===3){if(combination===COMBINATION_INFINITY){return string.join("")+"Infinity"}else if(combination===COMBINATION_NAN){return"NaN"}else{biased_exponent=high>>15&EXPONENT_MASK;significand_msb=8+(high>>14&1)}}else{significand_msb=high>>14&7;biased_exponent=high>>17&EXPONENT_MASK}const exponent=biased_exponent-EXPONENT_BIAS;significand128.parts[0]=(high&16383)+((significand_msb&15)<<14);significand128.parts[1]=midh;significand128.parts[2]=midl;significand128.parts[3]=low;if(significand128.parts[0]===0&&significand128.parts[1]===0&&significand128.parts[2]===0&&significand128.parts[3]===0){is_zero=true}else{for(k=3;k>=0;k--){let least_digits=0;const result=divideu128(significand128);significand128=result.quotient;least_digits=result.rem.low;if(!least_digits)continue;for(j=8;j>=0;j--){significand[k*9+j]=least_digits%10;least_digits=Math.floor(least_digits/10)}}}if(is_zero){significand_digits=1;significand[index]=0}else{significand_digits=36;while(!significand[index]){significand_digits=significand_digits-1;index=index+1}}const scientific_exponent=significand_digits-1+exponent;if(scientific_exponent>=34||scientific_exponent<=-7||exponent>0){if(significand_digits>34){string.push(`${0}`);if(exponent>0)string.push(`E+${exponent}`);else if(exponent<0)string.push(`E${exponent}`);return string.join("")}string.push(`${significand[index++]}`);significand_digits=significand_digits-1;if(significand_digits){string.push(".")}for(let i=0;i0){string.push(`+${scientific_exponent}`)}else{string.push(`${scientific_exponent}`)}}else{if(exponent>=0){for(let i=0;i0){for(let i=0;i>8&255;buffer2[9]=inc>>16&255;return buffer2}toString(encoding){if(encoding==="base64")return ByteUtils.toBase64(this.id);if(encoding==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(otherId===void 0||otherId===null){return false}if(otherId instanceof _ObjectId){return this[kId][11]===otherId[kId][11]&&ByteUtils.equals(this[kId],otherId[kId])}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12&&isUint8Array(this.id)){return ByteUtils.equals(this.id,ByteUtils.fromISO88591(otherId))}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===24){return otherId.toLowerCase()===this.toHexString()}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12){return ByteUtils.equals(ByteUtils.fromUTF8(otherId),this.id)}if(typeof otherId==="object"&&"toHexString"in otherId&&typeof otherId.toHexString==="function"){const otherIdString=otherId.toHexString();const thisIdString=this.toHexString().toLowerCase();return typeof otherIdString==="string"&&otherIdString.toLowerCase()===thisIdString}return false}getTimestamp(){const timestamp=new Date;const time=BSONDataView.fromUint8Array(this.id).getUint32(0,false);timestamp.setTime(Math.floor(time)*1e3);return timestamp}static createPk(){return new _ObjectId}static createFromTime(time){const buffer2=ByteUtils.fromNumberArray([0,0,0,0,0,0,0,0,0,0,0,0]);BSONDataView.fromUint8Array(buffer2).setUint32(0,time,false);return new _ObjectId(buffer2)}static createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new BSONError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}return new _ObjectId(ByteUtils.fromHex(hexString))}static isValid(id){if(id==null)return false;try{new _ObjectId(id);return true}catch{return false}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(doc){return new _ObjectId(doc.$oid)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new ObjectId("${this.toHexString()}")`}};ObjectId2.index=Math.floor(Math.random()*16777215);function internalCalculateObjectSize(object,serializeFunctions,ignoreUndefined){let totalLength=4+1;if(Array.isArray(object)){for(let i=0;i=JS_INT_MIN&&value<=JS_INT_MAX){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(4+1)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1;return 0;case"boolean":return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+1);case"object":if(value!=null&&typeof value._bsontype==="string"&&value[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(value==null||value._bsontype==="MinKey"||value._bsontype==="MaxKey"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1}else if(value._bsontype==="ObjectId"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(ArrayBuffer.isView(value)||value instanceof ArrayBuffer||isAnyArrayBuffer(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+4+1)+value.byteLength}else if(value._bsontype==="Long"||value._bsontype==="Double"||value._bsontype==="Timestamp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(value._bsontype==="Decimal128"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(16+1)}else if(value._bsontype==="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+4+ByteUtils.utf8ByteLength(value.code.toString())+1+internalCalculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.code.toString())+1}}else if(value._bsontype==="Binary"){const binary=value;if(binary.sub_type===Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1+4)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1)}}else if(value._bsontype==="Symbol"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+ByteUtils.utf8ByteLength(value.value)+4+1+1}else if(value._bsontype==="DBRef"){const ordered_values=Object.assign({$ref:value.collection,$id:value.oid},value.fields);if(value.db!=null){ordered_values["$db"]=value.db}return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+internalCalculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||isRegExp(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.source)+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value._bsontype==="BSONRegExp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.pattern)+1+ByteUtils.utf8ByteLength(value.options)+1}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+internalCalculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(serializeFunctions){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.toString())+1}}return 0}function alphabetize(str2){return str2.split("").sort().join("")}var BSONRegExp=class _BSONRegExp extends BSONValue{get _bsontype(){return"BSONRegExp"}constructor(pattern,options){super();this.pattern=pattern;this.options=alphabetize(options??"");if(this.pattern.indexOf("\0")!==-1){throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`)}if(this.options.indexOf("\0")!==-1){throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`)}for(let i=0;i4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max")}if(low.i>4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max")}super(low.i.valueOf(),low.t.valueOf(),true)}else{throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}}toJSON(){return{$timestamp:this.toString()}}static fromInt(value){return new _Timestamp(Long.fromInt(value,true))}static fromNumber(value){return new _Timestamp(Long.fromNumber(value,true))}static fromBits(lowBits,highBits){return new _Timestamp({i:lowBits,t:highBits})}static fromString(str2,optRadix){return new _Timestamp(Long.fromString(str2,true,optRadix))}toExtendedJSON(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}}static fromExtendedJSON(doc){const i=Long.isLong(doc.$timestamp.i)?doc.$timestamp.i.getLowBitsUnsigned():doc.$timestamp.i;const t=Long.isLong(doc.$timestamp.t)?doc.$timestamp.t.getLowBitsUnsigned():doc.$timestamp.t;return new _Timestamp({t,i})}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`}};Timestamp.MAX_VALUE=Long.MAX_UNSIGNED_VALUE;var FIRST_BIT=128;var FIRST_TWO_BITS=192;var FIRST_THREE_BITS=224;var FIRST_FOUR_BITS=240;var FIRST_FIVE_BITS=248;var TWO_BIT_CHAR=192;var THREE_BIT_CHAR=224;var FOUR_BIT_CHAR=240;var CONTINUING_CHAR=128;function validateUtf8(bytes,start,end){let continuation=0;for(let i=start;i= 5, is ${size}`)}if(options.allowObjectSmallerThanBufferSize&&buffer2.length= bson size ${size}`)}if(!options.allowObjectSmallerThanBufferSize&&buffer2.length!==size){throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`)}if(size+index>buffer2.byteLength){throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`)}if(buffer2[index+size-1]!==0){throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer2,index,options,isArray)}var allowedDBRefKeys=/^\$ref$|^\$id$|^\$db$/;function deserializeObject(buffer2,index,options,isArray=false){const fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];const raw=options["raw"]==null?false:options["raw"];const bsonRegExp=typeof options["bsonRegExp"]==="boolean"?options["bsonRegExp"]:false;const promoteBuffers=options.promoteBuffers??false;const promoteLongs=options.promoteLongs??true;const promoteValues=options.promoteValues??true;const useBigInt64=options.useBigInt64??false;if(useBigInt64&&!promoteValues){throw new BSONError("Must either request bigint or Long for int64 deserialization")}if(useBigInt64&&!promoteLongs){throw new BSONError("Must either request bigint or Long for int64 deserialization")}const validation=options.validation==null?{utf8:true}:options.validation;let globalUTFValidation=true;let validationSetting;const utf8KeysSet=new Set;const utf8ValidatedKeys=validation.utf8;if(typeof utf8ValidatedKeys==="boolean"){validationSetting=utf8ValidatedKeys}else{globalUTFValidation=false;const utf8ValidationValues=Object.keys(utf8ValidatedKeys).map(function(key){return utf8ValidatedKeys[key]});if(utf8ValidationValues.length===0){throw new BSONError("UTF-8 validation setting cannot be empty")}if(typeof utf8ValidationValues[0]!=="boolean"){throw new BSONError("Invalid UTF-8 validation option, must specify boolean values")}validationSetting=utf8ValidationValues[0];if(!utf8ValidationValues.every(item=>item===validationSetting)){throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}}if(!globalUTFValidation){for(const key of Object.keys(utf8ValidatedKeys)){utf8KeysSet.add(key)}}const startIndex=index;if(buffer2.length<5)throw new BSONError("corrupt bson message < 5 bytes long");const size=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(size<5||size>buffer2.length)throw new BSONError("corrupt bson message");const object=isArray?[]:{};let arrayIndex=0;const done=false;let isPossibleDBRef=isArray?false:null;const dataview=new DataView(buffer2.buffer,buffer2.byteOffset,buffer2.byteLength);while(!done){const elementType=buffer2[index++];if(elementType===0)break;let i=index;while(buffer2[i]!==0&&i=buffer2.byteLength)throw new BSONError("Bad BSON Document: illegal CString");const name=isArray?arrayIndex++:ByteUtils.toUTF8(buffer2.subarray(index,i));let shouldValidateKey=true;if(globalUTFValidation||utf8KeysSet.has(name)){shouldValidateKey=validationSetting}else{shouldValidateKey=!validationSetting}if(isPossibleDBRef!==false&&name[0]==="$"){isPossibleDBRef=allowedDBRefKeys.test(name)}let value;index=i+1;if(elementType===BSON_DATA_STRING){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}value=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize}else if(elementType===BSON_DATA_OID){const oid=ByteUtils.allocate(12);oid.set(buffer2.subarray(index,index+12));value=new ObjectId2(oid);index=index+12}else if(elementType===BSON_DATA_INT&&promoteValues===false){value=new Int32(buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24)}else if(elementType===BSON_DATA_INT){value=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24}else if(elementType===BSON_DATA_NUMBER&&promoteValues===false){value=new Double(dataview.getFloat64(index,true));index=index+8}else if(elementType===BSON_DATA_NUMBER){value=dataview.getFloat64(index,true);index=index+8}else if(elementType===BSON_DATA_DATE){const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;value=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType===BSON_DATA_BOOLEAN){if(buffer2[index]!==0&&buffer2[index]!==1)throw new BSONError("illegal boolean type value");value=buffer2[index++]===1}else if(elementType===BSON_DATA_OBJECT){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;if(objectSize<=0||objectSize>buffer2.length-index)throw new BSONError("bad embedded document length in bson");if(raw){value=buffer2.slice(index,index+objectSize)}else{let objectOptions=options;if(!globalUTFValidation){objectOptions={...options,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,objectOptions,false)}index=index+objectSize}else if(elementType===BSON_DATA_ARRAY){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;let arrayOptions=options;const stopIndex=index+objectSize;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={...options,raw:true}}if(!globalUTFValidation){arrayOptions={...arrayOptions,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,arrayOptions,true);index=index+objectSize;if(buffer2[index-1]!==0)throw new BSONError("invalid array terminator byte");if(index!==stopIndex)throw new BSONError("corrupted array bson")}else if(elementType===BSON_DATA_UNDEFINED){value=void 0}else if(elementType===BSON_DATA_NULL){value=null}else if(elementType===BSON_DATA_LONG){const dataview2=BSONDataView.fromUint8Array(buffer2.subarray(index,index+8));const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const long=new Long(lowBits,highBits);if(useBigInt64){value=dataview2.getBigInt64(0,true)}else if(promoteLongs&&promoteValues===true){value=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{value=long}}else if(elementType===BSON_DATA_DECIMAL128){const bytes=ByteUtils.allocate(16);bytes.set(buffer2.subarray(index,index+16),0);index=index+16;value=new Decimal128(bytes)}else if(elementType===BSON_DATA_BINARY){let binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const totalBinarySize=binarySize;const subType=buffer2[index++];if(binarySize<0)throw new BSONError("Negative binary type element size found");if(binarySize>buffer2.byteLength)throw new BSONError("Binary type size larger than document size");if(buffer2["slice"]!=null){if(subType===Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(binarySize<0)throw new BSONError("Negative binary type element size found for subtype 0x02");if(binarySize>totalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySizetotalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySize=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;const optionsArray=new Array(regExpOptions.length);for(i=0;i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;value=new BSONRegExp(source,regExpOptions)}else if(elementType===BSON_DATA_SYMBOL){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const symbol=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=promoteValues?symbol:new BSONSymbol(symbol);index=index+stringSize}else if(elementType===BSON_DATA_TIMESTAMP){const i2=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);const t=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);value=new Timestamp({i:i2,t})}else if(elementType===BSON_DATA_MIN_KEY){value=new MinKey}else if(elementType===BSON_DATA_MAX_KEY){value=new MaxKey}else if(elementType===BSON_DATA_CODE){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=new Code(functionString);index=index+stringSize}else if(elementType===BSON_DATA_CODE_W_SCOPE){const totalSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(totalSize<4+4+4+1){throw new BSONError("code_w_scope total size shorter minimum expected length")}const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize;const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;const scopeObject=deserializeObject(buffer2,_index,options,false);index=index+objectSize;if(totalSize<4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too short, truncating scope")}if(totalSize>4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too long, clips outer document")}value=new Code(functionString,scopeObject)}else if(elementType===BSON_DATA_DBPOINTER){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0)throw new BSONError("bad string length in bson");if(validation!=null&&validation.utf8){if(!validateUtf8(buffer2,index,index+stringSize-1)){throw new BSONError("Invalid UTF-8 string in BSON document")}}const namespace=ByteUtils.toUTF8(buffer2.subarray(index,index+stringSize-1));index=index+stringSize;const oidBuffer=ByteUtils.allocate(12);oidBuffer.set(buffer2.subarray(index,index+12),0);const oid=new ObjectId2(oidBuffer);index=index+12;value=new DBRef(namespace,oid)}else{throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`)}if(name==="__proto__"){Object.defineProperty(object,name,{value,writable:true,enumerable:true,configurable:true})}else{object[name]=value}}if(size!==index-startIndex){if(isArray)throw new BSONError("corrupt array bson");throw new BSONError("corrupt object bson")}if(!isPossibleDBRef)return object;if(isDBRefLike(object)){const copy=Object.assign({},object);delete copy.$ref;delete copy.$id;delete copy.$db;return new DBRef(object.$ref,object.$id,object.$db,copy)}return object}function getValidatedString(buffer2,start,end,shouldValidateUtf8){const value=ByteUtils.toUTF8(buffer2.subarray(start,end));if(shouldValidateUtf8){for(let i=0;i>24&255;buffer2[index+2]=size+1>>16&255;buffer2[index+1]=size+1>>8&255;buffer2[index]=size+1&255;index=index+4+size;buffer2[index++]=0;return index}var NUMBER_SPACE=new DataView(new ArrayBuffer(8),0,8);var FOUR_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,4);var EIGHT_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,8);function serializeNumber(buffer2,key,value,index){const isNegativeZero=Object.is(value,-0);const type=!isNegativeZero&&Number.isSafeInteger(value)&&value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN?BSON_DATA_INT:BSON_DATA_NUMBER;if(type===BSON_DATA_INT){NUMBER_SPACE.setInt32(0,value,true)}else{NUMBER_SPACE.setFloat64(0,value,true)}const bytes=type===BSON_DATA_INT?FOUR_BYTE_VIEW_ON_NUMBER:EIGHT_BYTE_VIEW_ON_NUMBER;buffer2[index++]=type;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(bytes,index);index+=bytes.byteLength;return index}function serializeBigInt(buffer2,key,value,index){buffer2[index++]=BSON_DATA_LONG;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index+=numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setBigInt64(0,value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index+=EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;return index}function serializeNull(buffer2,key,_,index){buffer2[index++]=BSON_DATA_NULL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeBoolean(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BOOLEAN;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value?1:0;return index}function serializeDate(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DATE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const dateInMilis=Long.fromNumber(value.getTime());const lowBits=dateInMilis.getLowBits();const highBits=dateInMilis.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw new BSONError("value "+value.source+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.source,index);buffer2[index++]=0;if(value.ignoreCase)buffer2[index++]=105;if(value.global)buffer2[index++]=115;if(value.multiline)buffer2[index++]=109;buffer2[index++]=0;return index}function serializeBSONRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.pattern.match(regexp)!=null){throw new BSONError("pattern "+value.pattern+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.pattern,index);buffer2[index++]=0;const sortedOptions=value.options.split("").sort().join("");index=index+ByteUtils.encodeUTF8Into(buffer2,sortedOptions,index);buffer2[index++]=0;return index}function serializeMinMax(buffer2,key,value,index){if(value===null){buffer2[index++]=BSON_DATA_NULL}else if(value._bsontype==="MinKey"){buffer2[index++]=BSON_DATA_MIN_KEY}else{buffer2[index++]=BSON_DATA_MAX_KEY}const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeObjectId(buffer2,key,value,index){buffer2[index++]=BSON_DATA_OID;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(isUint8Array(value.id)){buffer2.set(value.id.subarray(0,12),index)}else{throw new BSONError("object ["+JSON.stringify(value)+"] is not a valid ObjectId")}return index+12}function serializeBuffer(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=value.length;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=BSON_BINARY_SUBTYPE_DEFAULT;buffer2.set(value,index);index=index+size;return index}function serializeObject(buffer2,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined,path){if(path.has(value)){throw new BSONError("Cannot convert circular structure to BSON")}path.add(value);buffer2[index++]=Array.isArray(value)?BSON_DATA_ARRAY:BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const endIndex=serializeInto(buffer2,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);path.delete(value);return endIndex}function serializeDecimal128(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DECIMAL128;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(value.bytes.subarray(0,16),index);return index+16}function serializeLong(buffer2,key,value,index){buffer2[index++]=value._bsontype==="Long"?BSON_DATA_LONG:BSON_DATA_TIMESTAMP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const lowBits=value.getLowBits();const highBits=value.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeInt32(buffer2,key,value,index){value=value.valueOf();buffer2[index++]=BSON_DATA_INT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value&255;buffer2[index++]=value>>8&255;buffer2[index++]=value>>16&255;buffer2[index++]=value>>24&255;return index}function serializeDouble(buffer2,key,value,index){buffer2[index++]=BSON_DATA_NUMBER;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setFloat64(0,value.value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index=index+8;return index}function serializeFunction(buffer2,key,value,index){buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeCode(buffer2,key,value,index,checkKeys=false,depth=0,serializeFunctions=false,ignoreUndefined=true,path){if(value.scope&&typeof value.scope==="object"){buffer2[index++]=BSON_DATA_CODE_W_SCOPE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;const functionString=value.code;index=index+4;const codeSize=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=codeSize&255;buffer2[index+1]=codeSize>>8&255;buffer2[index+2]=codeSize>>16&255;buffer2[index+3]=codeSize>>24&255;buffer2[index+4+codeSize-1]=0;index=index+codeSize+4;const endIndex=serializeInto(buffer2,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);index=endIndex-1;const totalSize=endIndex-startIndex;buffer2[startIndex++]=totalSize&255;buffer2[startIndex++]=totalSize>>8&255;buffer2[startIndex++]=totalSize>>16&255;buffer2[startIndex++]=totalSize>>24&255;buffer2[index++]=0}else{buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.code.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0}return index}function serializeBinary(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const data=value.buffer;let size=value.position;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY)size=size+4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=value.sub_type;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY){size=size-4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255}buffer2.set(data,index);index=index+value.position;return index}function serializeSymbol(buffer2,key,value,index){buffer2[index++]=BSON_DATA_SYMBOL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=ByteUtils.encodeUTF8Into(buffer2,value.value,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeDBRef(buffer2,key,value,index,depth,serializeFunctions,path){buffer2[index++]=BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;let output={$ref:value.collection||value.namespace,$id:value.oid};if(value.db!=null){output.$db=value.db}output=Object.assign(output,value.fields);const endIndex=serializeInto(buffer2,output,false,index,depth+1,serializeFunctions,true,path);const size=endIndex-startIndex;buffer2[startIndex++]=size&255;buffer2[startIndex++]=size>>8&255;buffer2[startIndex++]=size>>16&255;buffer2[startIndex++]=size>>24&255;return endIndex}function serializeInto(buffer2,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined,path){if(path==null){if(object==null){buffer2[0]=5;buffer2[1]=0;buffer2[2]=0;buffer2[3]=0;buffer2[4]=0;return 5}if(Array.isArray(object)){throw new BSONError("serialize does not support an array as the root input")}if(typeof object!=="object"){throw new BSONError("serialize does not support non-object as the root input")}else if("_bsontype"in object&&typeof object._bsontype==="string"){throw new BSONError(`BSON types cannot be serialized as a document`)}else if(isDate(object)||isRegExp(object)||isUint8Array(object)||isAnyArrayBuffer(object)){throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`)}path=new Set}path.add(object);let index=startingIndex+4;if(Array.isArray(object)){for(let i=0;i>8&255;buffer2[startingIndex++]=size>>16&255;buffer2[startingIndex++]=size>>24&255;return index}function isBSONType(value){return value!=null&&typeof value==="object"&&"_bsontype"in value&&typeof value._bsontype==="string"}var keysToCodecs={$oid:ObjectId2,$binary:Binary,$uuid:Binary,$symbol:BSONSymbol,$numberInt:Int32,$numberDecimal:Decimal128,$numberDouble:Double,$numberLong:Long,$minKey:MinKey,$maxKey:MaxKey,$regex:BSONRegExp,$regularExpression:BSONRegExp,$timestamp:Timestamp};function deserializeValue(value,options={}){if(typeof value==="number"){const in32BitRange=value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN;const in64BitRange=value<=BSON_INT64_MAX&&value>=BSON_INT64_MIN;if(options.relaxed||options.legacy){return value}if(Number.isInteger(value)&&!Object.is(value,-0)){if(in32BitRange){return new Int32(value)}if(in64BitRange){if(options.useBigInt64){return BigInt(value)}return Long.fromNumber(value)}}return new Double(value)}if(value==null||typeof value!=="object")return value;if(value.$undefined)return null;const keys=Object.keys(value).filter(k=>k.startsWith("$")&&value[k]!=null);for(let i=0;ik.startsWith("$"));let valid=true;dollarKeys.forEach(k=>{if(["$ref","$id","$db"].indexOf(k)===-1)valid=false});if(valid)return DBRef.fromExtendedJSON(v2)}return value}function serializeArray(array,options){return array.map((v2,index)=>{options.seenObjects.push({propertyName:`index ${index}`,obj:null});try{return serializeValue(v2,options)}finally{options.seenObjects.pop()}})}function getISOString(date){const isoStr=date.toISOString();return date.getUTCMilliseconds()!==0?isoStr:isoStr.slice(0,-5)+"Z"}function serializeValue(value,options){if(value instanceof Map||isMap(value)){const obj=Object.create(null);for(const[k,v2]of value){if(typeof k!=="string"){throw new BSONError("Can only serialize maps with string keys")}obj[k]=v2}return serializeValue(obj,options)}if((typeof value==="object"||typeof value==="function")&&value!==null){const index=options.seenObjects.findIndex(entry=>entry.obj===value);if(index!==-1){const props=options.seenObjects.map(entry=>entry.propertyName);const leadingPart=props.slice(0,index).map(prop=>`${prop} -> `).join("");const alreadySeen=props[index];const circularPart=" -> "+props.slice(index+1,props.length-1).map(prop=>`${prop} -> `).join("");const current=props[props.length-1];const leadingSpace=" ".repeat(leadingPart.length+alreadySeen.length/2);const dashes="-".repeat(circularPart.length+(alreadySeen.length+current.length)/2-1);throw new BSONError(`Converting circular structure to EJSON: - ${leadingPart}${alreadySeen}${circularPart}${current} - ${leadingSpace}\\${dashes}/`)}options.seenObjects[options.seenObjects.length-1].obj=value}if(Array.isArray(value))return serializeArray(value,options);if(value===void 0)return null;if(value instanceof Date||isDate(value)){const dateNum=value.getTime(),inRange=dateNum>-1&&dateNum<2534023188e5;if(options.legacy){return options.relaxed&&inRange?{$date:value.getTime()}:{$date:getISOString(value)}}return options.relaxed&&inRange?{$date:getISOString(value)}:{$date:{$numberLong:value.getTime().toString()}}}if(typeof value==="number"&&(!options.relaxed||!isFinite(value))){if(Number.isInteger(value)&&!Object.is(value,-0)){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return{$numberInt:value.toString()}}if(value>=BSON_INT64_MIN&&value<=BSON_INT64_MAX){return{$numberLong:value.toString()}}}return{$numberDouble:Object.is(value,-0)?"-0.0":value.toString()}}if(typeof value==="bigint"){if(!options.relaxed){return{$numberLong:BigInt.asIntN(64,value).toString()}}return Number(BigInt.asIntN(64,value))}if(value instanceof RegExp||isRegExp(value)){let flags=value.flags;if(flags===void 0){const match=value.toString().match(/[gimuy]*$/);if(match){flags=match[0]}}const rx=new BSONRegExp(value.source,flags);return rx.toExtendedJSON(options)}if(value!=null&&typeof value==="object")return serializeDocument(value,options);return value}var BSON_TYPE_MAPPINGS={Binary:o=>new Binary(o.value(),o.sub_type),Code:o=>new Code(o.code,o.scope),DBRef:o=>new DBRef(o.collection||o.namespace,o.oid,o.db,o.fields),Decimal128:o=>new Decimal128(o.bytes),Double:o=>new Double(o.value),Int32:o=>new Int32(o.value),Long:o=>Long.fromBits(o.low!=null?o.low:o.low_,o.low!=null?o.high:o.high_,o.low!=null?o.unsigned:o.unsigned_),MaxKey:()=>new MaxKey,MinKey:()=>new MinKey,ObjectId:o=>new ObjectId2(o),BSONRegExp:o=>new BSONRegExp(o.pattern,o.options),BSONSymbol:o=>new BSONSymbol(o.value),Timestamp:o=>Timestamp.fromBits(o.low,o.high)};function serializeDocument(doc,options){if(doc==null||typeof doc!=="object")throw new BSONError("not an object instance");const bsontype=doc._bsontype;if(typeof bsontype==="undefined"){const _doc={};for(const name of Object.keys(doc)){options.seenObjects.push({propertyName:name,obj:null});try{const value=serializeValue(doc[name],options);if(name==="__proto__"){Object.defineProperty(_doc,name,{value,writable:true,enumerable:true,configurable:true})}else{_doc[name]=value}}finally{options.seenObjects.pop()}}return _doc}else if(doc!=null&&typeof doc==="object"&&typeof doc._bsontype==="string"&&doc[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(isBSONType(doc)){let outDoc=doc;if(typeof outDoc.toExtendedJSON!=="function"){const mapper=BSON_TYPE_MAPPINGS[doc._bsontype];if(!mapper){throw new BSONError("Unrecognized or invalid _bsontype: "+doc._bsontype)}outDoc=mapper(outDoc)}if(bsontype==="Code"&&outDoc.scope){outDoc=new Code(outDoc.code,serializeValue(outDoc.scope,options))}else if(bsontype==="DBRef"&&outDoc.oid){outDoc=new DBRef(serializeValue(outDoc.collection,options),serializeValue(outDoc.oid,options),serializeValue(outDoc.db,options),serializeValue(outDoc.fields,options))}return outDoc.toExtendedJSON(options)}else{throw new BSONError("_bsontype must be a string, but was: "+typeof bsontype)}}function parse(text,options){const ejsonOptions={useBigInt64:options?.useBigInt64??false,relaxed:options?.relaxed??true,legacy:options?.legacy??false};return JSON.parse(text,(key,value)=>{if(key.indexOf("\0")!==-1){throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`)}return deserializeValue(value,ejsonOptions)})}function stringify(value,replacer,space,options){if(space!=null&&typeof space==="object"){options=space;space=0}if(replacer!=null&&typeof replacer==="object"&&!Array.isArray(replacer)){options=replacer;replacer=void 0;space=0}const serializeOptions=Object.assign({relaxed:true,legacy:false},options,{seenObjects:[{propertyName:"(root)",obj:null}]});const doc=serializeValue(value,serializeOptions);return JSON.stringify(doc,replacer,space)}function EJSONserialize(value,options){options=options||{};return JSON.parse(stringify(value,options))}function EJSONdeserialize(ejson,options){options=options||{};return parse(JSON.stringify(ejson),options)}var EJSON=Object.create(null);EJSON.parse=parse;EJSON.stringify=stringify;EJSON.serialize=EJSONserialize;EJSON.deserialize=EJSONdeserialize;Object.freeze(EJSON);var MAXSIZE=1024*1024*17;var buffer=ByteUtils.allocate(MAXSIZE);function setInternalBufferSize(size){if(buffer.lengthAuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}onCollectionSet=(type,collection)=>{};runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b){if(a.timestamp&&b.timestamp)return a.timestamp-b.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_,__,___=this.data){}onSorted(_=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var defaultSpecifiers=["now","minute","5 minutes","30 minutes","hour","6 hours","12 hours","day","3 days","week","2 weeks","month","6 months","year","5 years","decade"];function genTimeSpecifiers(specifiers=defaultSpecifiers){let result=["now"];specifiers.forEach(s=>{if(s!=="now")result.push(`last ${s}`);else result.push(s)});return result}function genTimestampFromString(specifier){const now=new Date;if(specifier==="now"){}else if(specifier==="last minute"){now.setMinutes(now.getMinutes()-1)}else if(specifier==="last hour"){now.setHours(now.getHours()-1)}else if(specifier==="last day"){now.setDate(now.getDate()-1)}else if(specifier==="last week"){now.setDate(now.getDate()-7)}else if(specifier==="last month"){now.setMonth(now.getMonth()-1)}else if(specifier==="last year"){now.setFullYear(now.getFullYear()-1)}else if(specifier==="last decade"){now.setFullYear(now.getFullYear()-1*10)}else if(specifier==="last century"){now.setFullYear(now.getFullYear()-1*100)}else if(specifier==="last millennium"){now.setFullYear(now.getFullYear()-1*1e3)}else if(specifier==="last microsecond"){now.setMilliseconds(now.getMilliseconds()-1)}else if(specifier==="last nanosecond"){now.setMilliseconds(now.getMilliseconds()-1*.001)}else if(specifier.startsWith("last")){const[,count,unit]=specifier.match(/last (\d+) (\w+)/)||[];if(count&&unit){const num=parseInt(count,10);if(unit.includes("minute")){now.setMinutes(now.getMinutes()-num)}else if(unit.includes("hour")){now.setHours(now.getHours()-num)}else if(unit.includes("day")){now.setDate(now.getDate()-num)}else if(unit.includes("week")){now.setDate(now.getDate()-num*7)}else if(unit.includes("month")){now.setMonth(now.getMonth()-num)}else if(unit.includes("year")){now.setFullYear(now.getFullYear()-num)}else if(unit.includes("decade")){now.setFullYear(now.getFullYear()-num*10)}else if(unit.includes("century")){now.setFullYear(now.getFullYear()-num*100)}else if(unit.includes("millennium")){now.setFullYear(now.getFullYear()-num*1e3)}else if(unit.includes("microsecond")){now.setMilliseconds(now.getMilliseconds()-num)}else if(unit.includes("nanosecond")){now.setMilliseconds(now.getMilliseconds()-num*.001)}}}return now.getTime()}var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v2=>{if(!objProps[v2])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v2=>{obj2[k]=v2;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v2)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v2=>!objProps.includes(v2));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v2=>!objProps.includes(v2));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v2=>!objProps.includes(v2));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p2=origin[key];if(Array.isArray(p2))continue;let instanced;if(typeof p2==="function"){if(isNativeClass(p2)){p2=new p2;if(p2 instanceof GraphNode){p2=p2.prototype.constructor(p2,parent,this);instanced=true}}else p2={__operator:p2,__callable:true}}else if(typeof p2==="string"){if(this.__node.nodes.get(p2))p2=this.__node.nodes.get(p2);else p2=this.__node.roots[p2]}else if(typeof p2==="boolean"){if(this.__node.nodes.get(key))p2=this.__node.nodes.get(key);else p2=this.__node.roots[key]}if(p2&&typeof p2==="object"){if(!instanced&&!(p2 instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p2).filter(v2=>!objProps.includes(v2));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p2)).filter(v2=>!objProps.includes(v2));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p2[key2]}p2=cpy}if(!p2.__node)p2.__node={};if(!p2.__node.tag)p2.__node.tag=key;if(!p2.__node.initial)p2.__node.initial=originCpy[key];if(overwrite&&this.get(p2.__node.tag)){this.remove(p2.__node.tag,true)}else if(this.get(p2.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p2.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p2,2);if(instanced||p2 instanceof GraphNode){node=p2}else{node=new GraphNode(p2,parent,this);newnode=true}if(!newnode&&p2 instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d2=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d2.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{name="structs";currentUser;tablet=new DataTablet;collections=this.tablet.collections;id=randomId();useAccessTokens=false;useRefreshTokens=false;constructor(options,user){super(options);this.load(this);if(options.useAccessTokens)this.useAccessTokens=options.useAccessTokens;if(options.useRefreshTokens)this.useRefreshTokens=options.useRefreshTokens;if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}getToken(user){if(this.useAccessTokens)return user.accessToken;else if(this.useRefreshTokens)return user.refreshToken}setupUser=async(userinfo,callback=currentUser=>{})=>{if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u2;let newu=false;if(!user||!user._id){u2=this.userStruct(userinfo,false);newu=true;let wasSet=await this.setUser(u2);let structs=this.getLocalData(void 0,{"ownerId":u2._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u2)}else{u2=user;let toUpdate={_id:userinfo._id,ownerId:userinfo._id};let struct=this.userStruct(userinfo,false);for(const key in struct){if(userinfo[key]&&user[key]!==userinfo[key]){toUpdate[key]=userinfo[key];user[key]=userinfo[key]}else if(struct[key]&&!user[key]){toUpdate[key]=struct[key];user[key]=struct[key]}}if(Object.keys(toUpdate).length>2)await this.setUser(toUpdate);if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u2)}else{let data=await this.getAllUserData(u2._id,void 0,[genTimestampFromString("last day"),Date.now()]);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u2)}if(u2){if(this.currentUser)Object.assign(this.currentUser,u2);else this.currentUser=u2;callback(this.currentUser);return this.currentUser}else{callback(u2);return u2}};baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}this.onResult(data)};structNotification=()=>{this.checkForNotifications()};structDeleted=struct=>{this.deleteLocalData([struct])};onResult=data=>{};randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}addStruct=async(structType="struct",props={},parentUser,parentStruct,updateServer=true)=>{let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct};getUser=async(info="",basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info,basicInfo,this.getToken(this.currentUser)]});callback(res);return res}};queryUsers=async(info,skip,limit,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"queryUsers",args:[this.currentUser._id,info,skip,limit,void 0,this.getToken(this.currentUser)]});callback(res);return res}};getUsers=async(ids=[],basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids,basicInfo]});callback(res);return res}};getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};getAllUserData=async(ownerId,excluded=[],timeRange,callback=this.baseServerCallback)=>{if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[this.currentUser._id,ownerId,excluded,timeRange,this.getToken(this.currentUser)]});callback(res);return res}};query=async(collection,mongoQuery={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!mongoQuery)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,mongoQuery,findOne,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByTimeRange(collection,timeRange,ownerId,limit=0,skip=0,key){let query={};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}let range={$gt:timeRange[0],$lt:timeRange[1]};if(key)query[key]=range;else query.timestamp=range;return this.getData(collection,ownerId,query,limit,skip)}getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct?.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id,this.getToken(this.currentUser)];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};setUser=async(userStruct,callback=this.baseServerCallback)=>{if(userStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};updateServerData=this.setData;deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteUser=async(userId=this.currentUser._id,deleteData,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId,deleteData,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setGroup=async(groupStruct,callback=this.baseServerCallback)=>{if(groupStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setAuthorization=async(authorizationStruct,callback=this.baseServerCallback)=>{if(authorizationStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=await this.currentUser.request({route:"deleteAuthorization",args:[this.currentUser._id,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent){toUpdate=[parent];allReplies.forEach(r=>{let idx=parent.replies?.indexOf(r._id);if(idx>-1)parent.replies.splice(idx,1);let idx2=parent.comments?.indexOf(r._id);if(idx2>-1)parent.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent?._id){let idx=replyTo.replies?.indexOf(parent._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u2=authorizationStruct.authorizerId;if(u2){return new Promise(async resolve=>{this.getUser(u2,true,async data=>{let res;if(!collection)res=await this.getAllUserData(u2,["notification"],void 0,callback);else res=await this.getData(collection,u2,searchDict,limit,skip,callback);resolve(res);callback(res)})})}else return void 0};getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u2=o.authorizerId;if(u2){let data;let user=await this.getUser(u2,true,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u2,["notification"],void 0,callback);else data=await this.getData(collection,u2,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return{};let result={};let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result[a.authorizedId]=true});return result};getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b)=>a*(typeof b==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(void 0,{_id:struct});if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop]===""||copy[prop].constructor.name==="Map"||copy[prop].constructor.name==="Set"||typeof copy[prop]==="function")delete copy[prop];else if(Array.isArray(copy[prop])&©[prop].length===0)delete copy[prop];else if(typeof copy[prop]==="object"&&Object.keys(copy[prop]).length===0)delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(!user.name&&user.firstName)user.name=user.firstName+" "+user.lastName;else if(user.name&&!user.firstName){let split=user.name.split(" ");user.firstName=split[0];user.lastName=split[split.length-1]}if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e15);user._id=user.id;user.ownerId=user.id;let dummy=DataStructures_exports.ProfileStruct();for(const prop in props){if(Object.keys(dummy).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};addEvent=async(parentUser,author="",event="",notes="",startTime=void 0,endTime=void 0,grade=void 0,value=void 0,units=void 0,location=void 0,attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.value=value;newEvent.units=units;newEvent.users=users;newEvent.location=location;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};addChatroom=async(parentUser,authorId="",message="",attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=void 0,updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res}};var import_bson=__toESM(require_bson());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectId=str2=>{return typeof str2==="string"&&str2.length===24?new import_bson.ObjectId(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{name="structs";debug=false;db;users={};collections={};mode="local";useAuths=true;useAccessTokens=false;useRefreshTokens=false;accessTokens=new Map;refreshTokens=new Map;constructor(options,dboptions){super(options);this.load(this);if(dboptions){this.initDB(dboptions)}}initDB=dboptions=>{this.db=dboptions.db;if(dboptions?.users)this.users=dboptions.users;if(dboptions.mode)this.mode=dboptions.mode;if(dboptions?.collections)this.collections=dboptions.collections;if(dboptions.debug)this.debug=dboptions.debug;if(dboptions.useAccessTokens)this.useAccessTokens=dboptions.useAccessTokens;if(dboptions.useRefreshTokens)this.useRefreshTokens=dboptions.useRefreshTokens;if("useAuths"in dboptions)this.useAuths=dboptions.useAuths;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})};query=async(requestingUserId,collection,queryObj,findOne,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip,token)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token);if(passed)return res}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}));return data}};getUser=async(requestingUserId,lookupId,basicInfo,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId,void 0,basicInfo,token)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:void 0};else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};setUser=async(requestingUserId,struct,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(struct.accessToken){this.accessTokens.set(requestingUserId,token)}if(struct.refreshToken){this.refreshTokens.set(requestingUserId,struct.refreshToken)}delete struct.accessToken;delete struct.refreshToken;delete user.accessToken;delete user.refreshToken;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct,token)}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};getUsersByIds=async(requestingUserId,userIds,basicInfo)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds,basicInfo)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct){if(basicInfo)data.push({_id:struct._id,username:struct.username,firstName:struct.firstName,lastName:struct.lastName,fullName:struct.fullName,pictureUrl:struct.pictureUrl});else data.push(struct)}}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};deleteUser=async(requestingUserId,userId,deleteData,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId,deleteData,token)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};setData=async(requestingUserId,structs,notify,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify,token)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};getData=async(requestingUserId,collection,ownerId,dict,limit,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};getDataByIds=async(requestingUserId,structIds,ownerId,collection,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};getAllData=async(requestingUserId,ownerId,excludedCollections,timeRange,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections,timeRange,token)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};deleteData=async(requestingUserId,structIds,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds,token)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};deleteGroup=async(requestingUserId,groupId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId,token)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};getAuthorizations=async(requestingUserId,ownerId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId,token)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};deleteAuthorization=async(requestingUserId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId,token)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};getToken=user=>{return this.useAccessTokens?this.accessTokens.get(user._id):this.useRefreshTokens?this.refreshTokens.get(user._id):void 0};notificationStruct=(parentStruct={})=>{let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct};checkToNotify=async(user,structs=[],mode=this.mode)=>{if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(struct.ownerId&&user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+struct.ownerId;newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+usr;newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id)+"_"+auth.authorizedId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications,true,this.getToken(user))}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid]?.sendAll({route:"structNotification",args:true})}return true}else return false};queryMongo=async(user,collection,queryObj={},findOne=false,skip=0,token)=>{if(!collection&&!queryObj)return void 0;else if(findOne){let res=await this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token)}if(passed)return res;else return void 0}else{let res=this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];let arr=await res.toArray();if(arr.length>0){let passed=!this.useAuths;let checkedAuth="";for(const s of arr){if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)structs.push(s)}}return structs}};setMongoData=async(user,structs=[],notify=true,token)=>{let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:toObjectId(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType?struct.structType:"data").insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectId(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false};setMongoUser=async(user,struct,token)=>{if(struct._id){const _id=toObjectId(struct._id);let usersearch={_id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));copy._id=_id;if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false};setGroup=async(user,struct,mode=this.mode,token)=>{if(struct?._id){let uid=getStringId(user._id);let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(uid)<0))return false;if(uid!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u2=>{allusers.push({email:u2},{id:u2},{username:u2})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});let arr=cursor.toArray();if(arr.length>0){arr.forEach(user2=>{users[uid]=user2;ids[uid]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u2=users[id];if(struct.admins[getStringId(u2._id)]||struct.admins[u2.email]||struct.admins[u2.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u2._id)])admins[getStringId(u2._id)]=true}if(struct.peers[getStringId(u2._id)]||struct.peers[u2.email]||struct.peers[u2.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u2._id)])peers[getStringId(u2._id)]=true}if(struct.clients[getStringId(u2._id)]||struct.clients[u2.email]||struct.clients[u2.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u2._id)])clients[getStringId(u2._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType?struct.structType:"data").findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectId(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false};getMongoUser=(user,info="",requireAuth=true,basicInfo=false,token)=>{return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectId(info)})}catch(e){console.log("error creating ObjectId with ",info)}let u2=await this.collections.profile.instance.findOne({$or:query});if(!u2||u2==null)resolve(void 0);else{u2._id=getStringId(u2._id);if(!u2.ownerId)u2.ownerId=u2._id;if(basicInfo){if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}let stripped={username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id};u2=stripped;resolve({user:u2})}else if(requireAuth){if(getStringId(user._id)!==u2._id||getStringId(user._id)===u2._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u2,"READ",token);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u2._id});let aarr=await auths.toArray();if(auths.toArray().length>0){aarr.forEach(d2=>authorizations.push(d2))}let gs=this.collections.group.instance.find({users:{$all:[u2._id]}});let arr=await gs.toArray();let groups=[];if(arr.length>0){arr.forEach(d2=>groups.push(d2))}resolve({user:u2,authorizations,groups})}else{if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}resolve({user:u2})}}})};queryUsers=(user,info="",limit=0,skip=0,requireAuth=false,token)=>{if(typeof user==="string")user=this.users[user];if(!user)return;return new Promise(async resolve=>{let q={$regex:`^${info}`,$options:"i"};const query=[{email:q},{username:q},{firstName:q},{lastName:q},{name:q}];let arr;if(this.mode.includes("mongo")){let users=this.collections.profile.instance.find({$or:query},{projection:shallowqueryDummy}).skip(skip);if(limit>0)users.limit(limit);await users;arr=await users.toArray()}else{arr=[];for(let i=0;i{arr.push({firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,username:u2.username,pictureUrl:u2.pictureUrl})})}else if(dat)arr.push({firstName:dat.firstName,lastName:dat.lastName,fullName:dat.fullName,username:dat.username,pictureUrl:dat.pictureUrl})}}if(requireAuth){let result=[];let strid=getStringId(user._id);for(let i=0;i{let usrs=[];userIds.forEach(u2=>{try{usrs.push({_id:toObjectId(u2)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{if(basicInfo){found.push({username:u2.username,firstName:u2.firstName,lastName:u2.lastName,fullName:u2.fullName,pictureUrl:u2.pictureUrl,_id:u2._id})}else found.push(u2)})}}return found};getMongoUsersByRole=async(user,role)=>{let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];let arr=await users.toArray();if(arr.length>0){arr.forEach(u2=>{found.push(u2)})}return found};getMongoDataByIds=async(user,structIds,ownerId,collection,token)=>{let uid=getStringId(user._id);if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectId(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});let arr=await cursor.toArray();if(arr.length>0){let passed=true;let checkedAuth="";for(let i=0;i0){let passed=true;let checkedAuth="";arr.forEach(async s=>{if(!s?.ownerId)passed=true;else if((uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}};getMongoData=async(user,collection,ownerId,dict={},limit=0,skip=0,token)=>{if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectId(dict._id);let uid=getStringId(user._id);let structs=[];let passed=true;let checkedAuth="";let cursor;if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip)}else if(collection&&Object.keys(dict).length>0){if(ownerId)dict.ownerId=ownerId;cursor=await this.db.collection(collection).find(dict).sort({$natural:-1}).skip(skip)}if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{cursor=await this.db.collection(name).find(dict).sort({$natural:-1}).skip(skip);;if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i{let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let query={ownerId};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1]);query.timestamp={$gt:timeRange[0],$lt:timeRange[1]}}let cursor=this.db.collection(name).find(query);let arr=await cursor.toArray();let count=arr.length;for(let k=0;k{let structs=[];if(structs.length>0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectId(ref._id)});if(struct){let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs};getMongoAuthorizations=async(user,ownerId=getStringId(user._id),authId="",token)=>{let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectId(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0],"READ",token);if(!passed)return void 0}return auths};getMongoGroups=async(user,userId=getStringId(user._id),groupId="")=>{let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId),users:{$all:[userId]}}))}catch{}}return groups};deleteMongoData=async(user,structRefs=[],token)=>{let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectId(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=notifications.toArray().length;for(let i=0;i{let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){await this.db.collection(struct.structType?struct.structType:"data").deleteOne({_id:toObjectId(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})}}}));return true};deleteMongoUser=async(user,userId,deleteData,token)=>{if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u2=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u2?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u2,"WRITE",token);if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(deleteData){for(const key in this.collections){this.collections[key].instance.deleteMany({ownerId:userId});this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}})}}if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId]?.sendAll({route:"structDeleted",args:{_id:userId,structType:"profile"}});return true};deleteMongoGroup=async(user,groupId,token)=>{let s=await this.collections.group.instance.findOne({_id:toObjectId(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u2=>{this.users[u2]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}})})}await this.collections.group.instance.deleteOne({_id:toObjectId(groupId)});return true}else return false};deleteMongoAuthorization=async(user,authId,token)=>{let s=await this.collections.authorization.instance.findOne({_id:toObjectId(authId)});let uid=getStringId(user._id);if(s){if(uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectId(s.associatedAuthId)});if(s.authorizerId!==uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}});else if(s.authorizedId!==uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}})}await this.collections.authorization.instance.deleteOne({_id:toObjectId(authId)});if(s.authorizerId===uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});else if(s.authorizedId===uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});return true}else return false};setAuthorization=async(user,authStruct,token)=>{let u1,u2;let mmode=this.mode.includes("mongo");if(mmode){u1=(await this.getMongoUser(user,authStruct.authorizedId,false)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,false)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})?.[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})?.[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.name)authStruct.authorizedName=u1.name;else if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u1.name)authStruct.authorizedName=u1.name;else if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE",token);if(!passed)return false}let auths=[];if(mmode){let s=await this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d2=>auths.push(d2))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d2=>{if(d2.authorizerId===authStruct.authorizerId)auths.push(d2)})}}let otherAuthset;if(Array.isArray(auths)){for(let i=0;i{if(typeof user==="string"){if(this.users[user])user=this.users[user];else user={_id:user}}if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}return true}}if(this.useAccessTokens){if(!this.accessTokens.get(user._id)||this.accessTokens.get(user._id)!==token){return false}}else if(this.useRefreshTokens){if(!this.refreshTokens.get(user._id)||this.refreshTokens.get(user._id)!==token){return false}}let auth1,auth2;if(this.mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});if(!auth1)return false;auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(struct.ownerId)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(struct.ownerId)}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed};wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};overwriteLocalData=structs=>{if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}};setLocalData=structs=>{let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)};getLocalData=(collection,query)=>{let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result};deleteLocalData=struct=>{if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var shallowqueryDummy=DataStructures_exports.ProfileStruct();for(const key in shallowqueryDummy){if(key==="username"||key==="lastName"||key==="firstName"||key==="name"||key==="_id"||key==="pictureUrl")shallowqueryDummy[key]=1;else delete shallowqueryDummy[key]}var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u2=(dot11*dot02-dot01*dot12)*_denom;let v2=(dot00*dot12-dot01*dot02)*_denom;if(u2>=0&&v2>=0&&u2+v2<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v2=>{let magnitude=0;for(const key in v2){magnitude+=v2[key]*v2[key]}return Math.sqrt(magnitude)},normalize:v2=>{let magnitude=Systems.collision.magnitude(v2);let _mag=magnitude?1/magnitude:0;let vn={};for(const key in v2){vn[key]=v2[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w2=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w2||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var y=class{r;g;b;a;constructor(e,t,l,o){this.r=e,this.g=t,this.b=l,this.a=o}};var w=class{intensity;visible;numPoints;xy;color;scaleX;scaleY;offsetX;offsetY;loop;webglNumPoints;_vbuffer;_coord;constructor(){this.scaleX=1,this.scaleY=1,this.offsetX=0,this.offsetY=0,this.loop=false,this._vbuffer=0,this._coord=0,this.visible=true,this.intensity=1,this.xy=new Float32Array([]),this.numPoints=0,this.color=new y(0,0,0,1),this.webglNumPoints=0}};var v=class extends w{currentIndex=0;constructor(e,t){super(),this.webglNumPoints=t,this.numPoints=t,this.color=e,this.xy=new Float32Array(2*this.webglNumPoints)}setX(e,t){this.xy[e*2]=t}setY(e,t){this.xy[e*2+1]=t}getX(e){return this.xy[e*2]}getY(e){return this.xy[e*2+1]}lineSpaceX(e,t){for(let l=0;l{let l={x:0,y:0};return l.x=u2.x+e.x*t,l.y=u2.y+e.y*t,l};var A=u2=>P(-u2.y,u2.x);var p=(u2,e)=>{let t=R(u2,e);return t=M(t),t};var T=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x+e.x,t.y=u2.y+e.y,t};var C=(u2,e)=>u2.x*e.x+u2.y*e.y;var M=u2=>{let e={x:0,y:0},t=u2.x*u2.x+u2.y*u2.y;return t>0&&(t=1/Math.sqrt(t),e.x=u2.x*t,e.y=u2.y*t),e};var P=(u2,e)=>{let t={x:0,y:0};return t.x=u2,t.y=e,t};var R=(u2,e)=>{let t={x:0,y:0};return t.x=u2.x-e.x,t.y=u2.y-e.y,t};var X=u2=>{let e,t={x:0,y:0},l={x:0,y:0},o=[],a=(s,r)=>{o.push({vec2:s,miterLength:r})},h=s=>({x:u2[s*2],y:u2[s*2+1]});t=p(h(1),h(0)),e=A(t),a(e,1);let n=u2.length/2;for(let s=1;s{let t=T(u2,e);return t=M(t),P(-t.y,t.x)};var N=(u2,e,t)=>{let l=P(-u2.y,u2.x);return t/C(e,l)};var d=class extends w{currentIndex=0;_linePoints;_thicknessRequested=0;_actualThickness=0;constructor(e,t,l){super(),this.webglNumPoints=t*2,this.numPoints=t,this.color=e,this._thicknessRequested=l,this._linePoints=new Float32Array(t*2),this.xy=new Float32Array(2*this.webglNumPoints)}convertToTriPoints(){let e=this._actualThickness/2,t=X(this._linePoints);for(let l=0;l{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(l.loop?t.LINE_LOOP:t.LINE_STRIP,0,l.webglNumPoints)}})}_drawSurfaces(e){let t=this.webgl;e.forEach(l=>{if(l.visible){t.useProgram(this._progLine);let o=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(o,false,new Float32Array([l.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,l.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let a=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(a,new Float32Array([l.offsetX+this.gOffsetX,l.offsetY+this.gOffsetY]));let h=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(h,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let n=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(n,[l.color.r,l.color.g,l.color.b,l.color.a]),t.bufferData(t.ARRAY_BUFFER,l.xy,t.STREAM_DRAW),t.drawArrays(t.TRIANGLE_STRIP,0,l.webglNumPoints)}})}_drawTriangles(e){let t=this.webgl;t.bufferData(t.ARRAY_BUFFER,e.xy,t.STREAM_DRAW),t.useProgram(this._progLine);let l=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(l,false,new Float32Array([e.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,e.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let o=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(o,new Float32Array([e.offsetX+this.gOffsetX,e.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([0,0]));let h=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(h,[e.color.r,e.color.g,e.color.b,e.color.a]),t.drawArrays(t.TRIANGLE_STRIP,0,e.xy.length/2)}_drawThickLines(){this._thickLines.forEach(e=>{if(e.visible){let t=Math.min(this.gScaleX,this.gScaleY);e.setActualThickness(e.getThickness()/t),e.convertToTriPoints(),this._drawTriangles(e)}})}update(){this.clear(),this.draw()}draw(){this._drawLines(this.linesData),this._drawLines(this.linesAux),this._drawThickLines(),this._drawSurfaces(this.surfaces)}clear(){this.webgl.clear(this.webgl.COLOR_BUFFER_BIT)}_addLine(e){e._vbuffer=this.webgl.createBuffer(),this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER,e._vbuffer),this.webgl.bufferData(this.webgl.ARRAY_BUFFER,e.xy,this.webgl.STREAM_DRAW),e._coord=this.webgl.getAttribLocation(this._progLine,"coordinates"),this.webgl.vertexAttribPointer(e._coord,2,this.webgl.FLOAT,false,0,0),this.webgl.enableVertexAttribArray(e._coord)}addDataLine(e){this._addLine(e),this.linesData.push(e)}addLine=this.addDataLine;addAuxLine(e){this._addLine(e),this.linesAux.push(e)}addThickLine(e){this._addLine(e),this._thickLines.push(e)}addSurface(e){this._addLine(e),this.surfaces.push(e)}initThinLineProgram(){let e=` - attribute vec2 coordinates; - uniform mat2 uscale; - uniform vec2 uoffset; - uniform ivec2 is_log; - - void main(void) { - float x = (is_log[0]==1) ? log(coordinates.x) : coordinates.x; - float y = (is_log[1]==1) ? log(coordinates.y) : coordinates.y; - vec2 line = vec2(x, y); - gl_Position = vec4(uscale*line + uoffset, 0.0, 1.0); - }`,t=this.webgl.createShader(this.webgl.VERTEX_SHADER);this.webgl.shaderSource(t,e),this.webgl.compileShader(t);let l=` - precision mediump float; - uniform highp vec4 uColor; - void main(void) { - gl_FragColor = uColor; - }`,o=this.webgl.createShader(this.webgl.FRAGMENT_SHADER);this.webgl.shaderSource(o,l),this.webgl.compileShader(o),this._progLine=this.webgl.createProgram(),this.webgl.attachShader(this._progLine,t),this.webgl.attachShader(this._progLine,o),this.webgl.linkProgram(this._progLine)}popDataLine(){this.linesData.pop()}removeAllLines(){this._linesData=[],this._linesAux=[],this._thickLines=[],this._surfaces=[]}removeDataLines(){this._linesData=[]}removeAuxLines(){this._linesAux=[]}viewport(e,t,l,o){this.webgl.viewport(e,t,l,o)}log(e){this.debug&&console.log("[webgl-plot]:"+e)}};var S=class u{constructor(){this.plots={};this.renderOverlay=(e,t,l,o,a,h=1,n=0)=>{if(typeof l.settings.overlay=="object"&&(o.useOverlay||!("useOverlay"in o))){let s=l.settings.nLines-o.position-1,r=e.height*s/l.settings.nLines,i=e.height*(s+1)/l.settings.nLines;if(t.clearRect(0,r,e.width,i),l.settings.mode==="sweep"){t.strokeStyle=l.settings.sweepColor?l.settings.sweepColor:"rgba(0,255,0,0.8)",t.beginPath();let f=e.width*o.ct/o.values.length;t.moveTo(f,r),t.lineTo(f,i),t.stroke()}if(t.fillStyle=l.settings.overlayColor?l.settings.overlayColor:"white",a&&t.fillText(a,20,e.height*(s+.2)/l.settings.nLines),o.nSec){let f=this.formatTime(o.nSec);t.fillText(`${f}`,l.settings.mode==="sweep"?e.width-35:20,e.height*(s+.9)/l.settings.nLines),t.fillText("0:00",l.settings.mode==="sweep"?20:e.width-35,e.height*(s+.9)/l.settings.nLines)}typeof h=="number"&&t.fillText(`${Math.floor(h)===h?h:h?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.2)/l.settings.nLines),typeof n=="number"&&t.fillText(`${Math.floor(n)===n?n:n?.toFixed(5)} ${o.units?o.units:""}`,e.width-100,e.height*(s+.8)/l.settings.nLines)}}}initPlot(e,t){if(t||(t=new x2(e.canvas,e.webglOptions)),!e._id)e._id=`plot${Math.floor(Math.random()*1e15)}`;else if(this.plots[e._id]){let r=this.plots[e._id].initial;if(e.lines){for(let i in e.lines)if(r.lines[i]&&Array.isArray(e.lines[i])){let f=e.lines[i];e.lines[i]=r.lines[i]}}e=Object.assign(r,e)}e.overlay&&(typeof e.overlay!="object"&&(e.overlay=document.createElement("canvas"),e.overlay.style.position="absolute",e.overlay.width=e.canvas.width,e.overlay.height=e.canvas.height,e.canvas.appendChild(e.overlay)),e.overlayCtx||(e.overlayCtx=e.overlay.getContext("2d"))),e.width&&(e.canvas.width=e.width,e.canvas.style&&(e.canvas.style.width=e.width+"px"),typeof e.overlay=="object"&&(e.overlay.width=e.width,e.overlay.style&&(e.overlay.style.width=e.width+"px"))),e.height&&(e.canvas.height=e.height,e.canvas.style&&(e.canvas.style.height=e.height+"px"),typeof e.overlay=="object"&&(e.overlay.height=e.height,e.overlay.style&&(e.overlay.style.height=e.height+"px"))),e.lines?.timestamp&&delete e.lines.timestamp,e.lines||(e.lines={});let l={};for(let r in e.lines)l[r]=Object.assign({},l[r]),"viewing"in e.lines[r]||(e.lines[r].viewing=true),l[r].viewing=e.lines[r].viewing,l[r].sps=e.lines[r].sps,l[r].nSec=e.lines[r].nSec,l[r].nPoints=e.lines[r].nPoints,l[r].ymin=e.lines[r].ymin,l[r].ymax=e.lines[r].ymax,l[r].units=e.lines[r].units;let o={plot:t,settings:e,initial:Object.assign(Object.assign({},e),{lines:l}),anim:()=>{t.update()}};this.plots[e._id]=o;let a=0,h=0;Object.keys(e.lines).forEach(r=>{e.lines[r]?.viewing!==false&&h++}),e.nLines=h;let n,s;typeof e.overlay=="object"&&(n=e.overlay,s=e.overlayCtx,s.clearRect(0,0,e.overlay.width,e.overlay.height),s.font=e.overlayFont?e.overlayFont:"1em Courier",s.fillStyle=e.overlayColor?e.overlayColor:"white");for(let r in e.lines){let i=e.lines[r];if(Array.isArray(i)&&(i={values:i},e.lines[r]=i),"viewing"in i||(i.viewing=true),i.color)Array.isArray(i.color)&&(i.color=new y(...i.color));else{let m=u.HSLToRGB(360*(a/h)%360,100,50,1);o.initial.lines[r].color=[...m,1],i.color=new y(...m,1)}let f;if(i.nSec&&i.sps?f=Math.ceil(i.nSec*i.sps):i.nPoints?f=i.nPoints:i.points?f=i.points:e.linePoints?f=e.linePoints:i.values?f=i.values.length:f=1e3,i.points=f,e.lines[r].viewing===false)continue;if((i.width||e.lineWidth)&&i.width!==0){let m=e.lineWidth;m||(m=i.width),i.width?i.line=new d(i.color,f,i.width):e.lineWidth&&(i.line=new d(i.color,f,e.lineWidth)),i.line.lineSpaceX(-1,2/i.line.numPoints)}else i.line=new v(i.color,f),i.line.arrangeX();i.values?.length===i.points?i.values.length!==f&&(i.interpolate?i.values.length>f?i.values=u.downsample(i.values,f):i.values.lengthi.points?i.values=i.values.slice(i.values.length-i.points):i.values=[...new Array(i.points-i.values.length).fill(0),...i.values]):Array.isArray(i.values)?i.values.length>f?i.values=i.values.slice(i.values.length-f):i.values.lengthg){let m=c;g=c,c=m}let _=Math.abs(c);if(i.absmax=_>g?_:g,"autoscale"in i||(i.autoscale=true),i.position||(i.position=e.nLines-a-1),i.autoscale?i.autoscale===2?("clamp"in i||(i.clamp=true),i.scaled=u.autoscale(i.values,i.position,h,i.centerZero,c,g,i.clamp)):(i.scaled=i.values,i.line.scaleY=u.getYScalar(i.values,h,i.centerZero,c,g),i.line.offsetY=u.getYOffset(i.position,h,c,i.line.scaleY)):i.scaled=i.values,i.scaled.forEach((m,L)=>i.line.setY(L,m)),i.line instanceof d?t.addThickLine(i.line):i.line instanceof v&&t.addDataLine(i.line),"xAxis"in i||(i.xAxis=true),i.xAxis){i.xColor?Array.isArray(i.xColor)&&(i.xColor=new y(...i.xColor)):i.xColor=new y(1,1,1,.3);let m=new v(i.xColor,2),L=i.autoscale?(a+1)*2/h-1-1/h:0;m.constY(L),m.arrangeX(),m.xy[2]=1,i.x=m,t.addAuxLine(m)}if(h>1&&i.autoscale&&a!==h-1){e.dividerColor?Array.isArray(e.dividerColor)&&(e.dividerColor=new y(...e.dividerColor)):e.dividerColor=new y(1,1,1,1);let m=new v(e.dividerColor,2);m.constY(i.autoscale?(a+1)*2/h-1:1),m.arrangeX(),m.xy[2]=1,i.divider=m,t.addAuxLine(m)}if(typeof e.overlay=="object"&&(i.useOverlay||!("useOverlay"in i))){let m=e.nLines-i.position-1;s.fillText(r,20,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(g)===g?g:g?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.2)/e.nLines),s.fillText(`${Math.floor(c)===c?c:c?.toFixed(5)} ${i.units?i.units:""}`,n.width-100,n.height*(m+.9)/e.nLines)}a++}return requestAnimationFrame(o.anim),this.plots[e._id]}deinitPlot(e){return typeof e=="string"&&(e=this.plots[e]),e.plot.clear(),e.plot.removeAllLines(),true}reinitPlot(e,t){if(typeof e=="string"){let l=e;e=this.plots[e],t._id||(t._id=l)}if(e.plot)return e.plot.clear(),e.plot.removeAllLines(),e.settings.overlayCtx&&e.settings.overlayCtx.clearRect(0,0,e.settings.overlay?.width,e.settings.overlay?.height),this.initPlot(t,e.plot)}getChartSettings(e,t){let l=this.plots[e];if(l){let o=Object.assign({},l.initial);for(let a in l.initial.lines)typeof l.initial.lines[a]?.ymax!="number"&&(o.lines[a].ymax=l.settings.lines[a]?.ymax),typeof l.initial.lines[a]?.ymin!="number"&&(o.lines[a].ymin=l.settings.lines[a]?.ymin),t&&(o.lines[a].values=l.settings.lines[a].values);return delete o.canvas,delete o.overlay,delete o.overlayCtx,o}}update(e,t,l=true){if(typeof e=="string"&&(e=this.plots[e]),!e)return false;let o,a;if(typeof e.settings.overlay=="object"&&(o=e.settings.overlay,a=e.settings.overlayCtx,a.font=e.settings.overlayFont?e.settings.overlayFont:"1em Courier",a.fillStyle=e.settings.overlayColor?e.settings.overlayColor:"white"),t){let h=false;for(let n in t)if(e.settings.lines[n]&&e.settings.lines[n].line){if(e.settings.lines[n]?.viewing===false)continue;let s=e.settings.lines[n];if(s.values){if(e.settings.mode&&e.settings.mode==="sweep"){"ct"in s||(s.ct=0);let g=b=>{s.ct>s.values.length&&(s.ct=0),s.values[s.ct]=b,s.ct++};Array.isArray(t[n])?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n][t[n].length-1])),t[n].forEach(g)):typeof t[n]=="number"?(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n])),g(t[n])):t[n].values&&(s.ct===0&&(s.values=new Array(s.values.length).fill(t[n].values[t[n].values.length-1])),t[n].values.forEach(g))}else Array.isArray(t[n])&&s.values?.length<1e5?(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n][t[n].length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n][t[n].length-1]),s.firstWrite=true),t[n].length===s.values.length?s.values=t[n]:u.circularBuffer(s.values,t[n])):typeof t[n]=="number"?(s.firstWrite||(s.values.fill(t[n]),s.firstWrite=true),s.values.push(t[n]),s.values.shift()):t[n]?.values&&(s.values.length===0?(s.values.length=s.points?s.points:1e3,s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true):s.firstWrite||(s.values.fill(t[n].values[t[n].values.length-1]),s.firstWrite=true),t[n].values.length===s.values.length?s.values=t[n].values:u.circularBuffer(s.values,t[n].values));s.values.length!==s.points&&(s.interpolate?s.values.length>s.points?s.values=u.downsample(s.values,s.points):s.scaled.lengths.points?s.values.splice(0,s.values.length-s.points):s.values=new Array(s.points).fill(0).splice(s.points-s.values.length,0,s.values));let r=s.ymin,i=s.ymax,f=s.values.length<=1e5;if(r===i?(i=f?Math.max(...s.values):1,r=f?Math.min(...s.values):0):isNaN(i)&&(i=f?Math.max(...s.values):1),isNaN(r)&&(r=f?Math.min(...s.values):0),r>i){let g=r;i=r,r=g}let c=Math.abs(r);s.absmax=c>i?c:i,s.autoscale?s.autoscale===2?s.scaled=u.autoscale(s.values,s.position,e.settings.nLines,s.centerZero,r,i,s.clamp):(s.scaled=s.values,s.line.scaleY=u.getYScalar(s.values,e.settings.nLines,s.centerZero,r,i),s.line.offsetY=u.getYOffset(s.position,e.settings.nLines,r,s.line.scaleY)):s.scaled=s.values,s.scaled.forEach((g,b)=>{!s.autoscale&&s.absmax>1?s.line.setY(b,g/s.absmax):s.line.setY(b,g)}),this.renderOverlay(o,a,e,s,n,i,r)}}else e.settings.generateNewLines&&!n.includes("timestamp")&&(Array.isArray(t[n])&&(t[n]={values:t[n]}),!t[n].nSec&&!t[n].nPoints&&!e.settings.linePoints&&(t[n].nPoints=1e3),h=true);if(h)return e.settings.cleanGeneration||Object.keys(e.initial.lines).forEach(n=>{t[n]?t[n]=Object.assign(e.initial.lines[n],t[n]):t[n]=e.initial.lines[n]}),this.reinitPlot(e,{_id:e.settings._id,lines:t}),true}else for(let h in e.settings.lines){let n=e.settings.lines[h];this.renderOverlay(o,a,e,n,h,n.ymax,n.ymin)}return l&&requestAnimationFrame(e.anim),true}updateLine(e,t,l,o,a,h,n){return e.numPoints!==t.length&&(l?e.numPoints>t.length?t=u.downsample(t,e.numPoints):e.numPointse.numPoints?t=t.slice(t.length-e.numPoints):t=[...new Array(t.length).fill(0),...t]),o&&(t=u.autoscale(t,a,h,n)),t.forEach((s,r)=>e.setY(r,s)),true}formatTime(e){let t=Math.floor(e/60),l=Math.floor(t/60);t=t%60,e=e%60;let o="";return l>0&&(o+=l+":",t<10&&(o+="0")),o+=t+":",e>0&&(e<10&&(o+="0"),o+=e),o}static autoscale(e,t=0,l=1,o=false,a,h,n){if(e?.length===0)return e;let s=typeof h=="number"?h:e.length<=1e5?Math.max(...e):1,r=typeof a=="number"?a:e.length<=1e5?Math.min(...e):0,i=1/l,f=1;if(o){let c=Math.max(Math.abs(r),Math.abs(s));return c!==0&&(f=i/c),e.map(g=>(n&&(gs&&(g=s)),g*f+(i*(t+1)*2-1-i)))}else return s===r?s!==0?f=i/s:r!==0&&(f=i/Math.abs(r)):f=i/(s-r),e.map(c=>(n&&(cs&&(c=s)),2*((c-r)*f-1/(2*l))+(i*(t+1)*2-1-i)))}static getYScalar(e,t=1,l=false,o,a){if(e?.length===0)return e;let h=typeof a=="number"?a:e.length<=1e5?Math.max(...e):1,n=typeof o=="number"?o:e.length<=1e5?Math.min(...e):0,s=1/t,r=1;if(l){let i=Math.max(Math.abs(n),Math.abs(h));return i!==0&&(r=s/i),2*r}else return h===n?h!==0?r=s/h:n!==0&&(r=s/Math.abs(n)):r=s/(h-n),2*r}static getYOffset(e=0,t=1,l=0,o=1){let a=1/t,h=a*(e+1)*2-1-a;return l!==0?h-=l*o+1/t:h-=o+1/t,h}static absmax(e){return Math.max(Math.abs(Math.min(...e)),Math.max(...e))}static downsample(e,t,l=1){if(e.length>t){let o=new Array(t),a=e.length/t,h=e.length-1,n=0,s=0;for(let r=a;rh&&(i=h);for(let f=n;ft?u.downsample(e,t,l):e.lengthe.length){let l=e.length;e.splice(0,l,...t.slice(t.length-l))}else e.splice(0,e.length,...t);return e}static formatDataForCharts(e,t){if(Array.isArray(e)){if(Array.isArray(e[0])){let l={};if(e.forEach((o,a)=>{l[a]=o}),e=l,isNaN(e[0][0]))return}else if(t){if(e={[t]:e},isNaN(e[t][0]))return}else if(e={0:e},isNaN(e[0][0]))return}else if(typeof e=="object"){for(let l in e)if(typeof e[l]=="number"?e[l]=[e[l]]:e[l]?.values&&typeof e[l].values=="number"&&(e[l].values=[e[l].values]),isNaN(e[l][0]))return}else if(typeof e=="string"){let l;if(e.includes(`\r -`)){let o=e.split(`\r -`);e={},o.forEach((a,h)=>{a.includes(" ")?l=a.split(" "):a.includes(",")?l=a.split(","):a.includes("|")&&(l=a.split("|")),l&&l.forEach((n,s)=>{if(n.includes(":")){let[r,i]=n.split(":"),f=parseFloat(i);isNaN(f)||(e[r]=[f])}else{let r=parseFloat(n);isNaN(r)||(e[s]=[r])}})})}else e.includes(" ")?l=e.split(" "):e.includes(",")?l=e.split(","):e.includes("|")&&(l=e.split("|"));e={},l&&l.forEach((o,a)=>{if(o.includes(":")){let[h,n]=o.split(":"),s=parseFloat(n);isNaN(s)||(e[h]=[s])}else{let h=parseFloat(o);isNaN(h)||(e[a]=[h])}})}else typeof e=="number"&&(t?e={[t]:[e]}:e={0:[e]});return e}static padTime(e,t,l,o){let a=(e[0]-t)/l/o;return[...new Array(o-e.length).map((n,s)=>t+a*(s+1)),...e]}static interpolateForTime(e,t,l){return u.interpolate(e,Math.ceil(l*t))}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new S;return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new S;return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` - - - - - - - - - - - - - - `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` - - - - - - - - - - - - - - - `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var Math2=class _Math2{constructor(){}static TWO_PI=Math.PI*2;static C=299792458;static G=66743e-15;static h=662607015e-42;static R=8314.32;static Ra=287;static H=69.3;static kbar=1054571817e-43;static kB=1380649e-29;static ke=89875517923e-1;static me=91093837015e-41;static mp=167262192369e-38;static mn=167492749804e-38;static P0=101325;static T0=288.15;static p0=1.225;static Na=60220978e16;static y=1.405;static M0=28.96643;static g0=9.80665;static Re=6378100;static B=1458e-9;static S=110.4;static Sigma=365e-12;static imgkernels={edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]};static HSLToRGB=(h,s,l,scalar=255)=>{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x22=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x22;b=0}else if(60<=h&&h<120){r=x22;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x22}else if(180<=h&&h<240){r=0;g=x22;b=c}else if(240<=h&&h<300){r=x22;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x22}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v2=>v2===a).length-arr.filter(v2=>v2===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean=void 0)=>{let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d2=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean=this.mean(arr);let std=this.std(arr,mean);let z=new Array(arr.length);for(let i=0;ia+(b-mean)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean=this.mean(arr);let std=this.std(arr,mean);return populationMean?std/populationMean:std/mean};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y2)=>acc+Math.pow(y2-meanY,2),0);const ssResidual=observed.reduce((acc,y2,i)=>acc+Math.pow(y2-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p2)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p2*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x22)=>sum+x22,0);const sumY=yCoords.reduce((sum,y2)=>sum+y2,0);const sumXY=xCoords.reduce((sum,x22,i)=>sum+x22*yCoords[i],0);const sumX2=xCoords.reduce((sum,x22)=>sum+x22*x22,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v2,i)=>{for(let j=1;j{return vec.map((v2,i)=>v2-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v2,i)=>v2/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v2,i)=>v2/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x22,y2,z)=>{var r=Math.sqrt(x22*x22+y2*y2+z*z);var theta=Math.atan2(y2,x22);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v2=>(v2-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x22=>{return Math.pow(x22,5)+x22*x22-x22-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y2=x22;return y2},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x22+y2;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w2=x22+y2+z;return w2},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x22;return y2},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x22=Math.cos(t);return x22},yFunc=t=>{let y2=Math.sin(t);return y2},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u2,v2)=>u2,yFunc=(u2,v2)=>v2,zFunc=(u2,v2)=>u2+v2,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u2=rangeU[0];u2{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v2,i,x22,y2)=>{return v2+x22+y2})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v2}, idx:${idx}, x:${i},y:${j}`);return v2+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x22,y2)=>{return[x22*10,y2*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value,index)=>{const row=Array(values.length).fill(0);row[index]=value;return row})};static householderMatrix=v2=>{const size=v2.length;const vvT=v2.map(rowVal=>v2.map(colVal=>rowVal*colVal));const vTv=this.normalize(v2)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A2,B)=>{return A2.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A2,B)=>{return A2.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix22*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value=>(value-min)/(max-min))};static garroteThreshold=(data,value)=>{return data.map(x22=>{if(Math.abs(x22)<=value){return 0}else{return x22-value*value/x22}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean1=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v2,i)=>(v2-mean1)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x22,x22),this.cov1d(x22,y2),this.cov1d(x22,z)],[this.cov1d(y2,x22),this.cov1d(y2,y2),this.cov1d(y2,z)],[this.cov1d(z,x22),this.cov1d(z,y2),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v2=>v2-mean)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N2=signalA.length;const M2=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{let result=[];for(let y2=0;y2{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N2=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N2;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x22,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x22,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x22,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x22=arr.filter((element,index)=>{return index%factor===0});return x22};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y2=>y2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x22)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A2,numIter=100)=>{let b=Array(A2.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A2[0].length>A2.length){A2=this.transpose(A2)}const m=A2.length;const n=A2[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A2);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x22):this.normalize(x22);const u2=this.vecsub(x22,e);const normU=this.normalize(u2);const v2=u2.map(val=>val/normU);const Qk=this.householderMatrix(v2);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p2=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p2[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p2[0]=this.matscale(p2[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p2[0]),p2[0]));p2[0]=this.matscale(p2[0],1/p_length);let t_new=this.matmul(mat,p2[0]);let pp=this.matmul(this.transpose(p2[0]),p2[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{ax=ax*this.accelConstant;ay=ay*this.accelConstant;az=az*this.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+this.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+this.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v2,i)=>{return apass(v2,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-this.lastGyroTime;this.lastGyroTime=timestamp;gx=gx*this.gyroConstant+this.gyroXError;gy=gy*this.gyroConstant+this.gyroYError;gz=gz*this.gyroConstant+this.gyroZError;this.gyroXAngle+=gx*elapsed;this.gyroYAngle+=gy*elapsed;this.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:this.gyroXAngle,pitch:this.gyroYAngle,yaw:this.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v2,i)=>{if(result){let r=gpass(v2,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v2,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(this.gyroXAngle||this.gyroYAngle||this.gyroZAngle){result.roll=result.roll*.04+this.gyroXAngle*.96;result.pitch=result.pitch*.04+this.gyroYAngle*.96;result.yaw=this.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-this.lastAccelTime;this.lastAccelTime=timestamp;this.px+=result2.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*.005555555555);this.py+=result2.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*.005555555555);this.pz+=result2.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*.005555555555);result2.px=this.px;result2.py=this.py;result2.pz=this.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{type;freq;sps;Q;dbGain;a0=0;a1=0;a2=0;b0=0;b1=0;b2=0;x1=0;x2=0;y1=0;y2=0;constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A2=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A2+A2);this[type](A2,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A2,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A2,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A2,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A2,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A2,sn,cs,alpha,beta){this.b0=1+alpha*A2;this.b1=-2*cs;this.b2=1-alpha*A2;this.a0=1+alpha/A2;this.a1=-2*cs;this.a2=1-alpha/A2}lowshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1-(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1-(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1+(A2+1)*cs+beta*sn;this.a1=2*(A2-1+(A2+1)*cs);this.a2=A2+1+(A2-1)*cs-beta*sn}highshelf(A2,sn,cs,alpha,beta){this.b0=A2*(A2+1+(A2-1)*cs+beta*sn);this.b1=2*A2*(A2-1+(A2+1)*cs);this.b2=A2*(A2+1-(A2-1)*cs-beta*sn);this.a0=A2+1-(A2+1)*cs-beta*sn;this.a1=2*(A2-1-(A2+1)*cs);this.a2=A2+1-(A2-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10,__onconnected:function(){if(!this.lowpass){let freq=this.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;this.lowpass=new Biquad("lowpass",this.maxFreq,this.sps);this.peakFinderWindow=Math.floor(this.sps/this.maxFreq);if(this.peakFinderWindow%2===0)this.peakFinderWindow+=1;if(this.peakFinderWindow<5)this.peakFinderWindow=5;this.midpoint=Math.round(this.peakFinderWindow*.5)}},__operator:function(data){if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*this.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){this.refdata.push(amplitude)}this.timestamp.push(timestamp);let beat;if(this.refdata.length>this.peakFinderWindow){this.refdata.shift();this.timestamp.shift()}this.smoothed.push(this.lowpass.applyFilter(this.refdata[this.refdata.length-1]));if(this.smoothed.length>this.peakFinderWindow){this.smoothed.shift()}if(this.smoothed.length===this.peakFinderWindow){if(Math2.isExtrema(this.smoothed,"valley")){this.valleys.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}else if(Math2.isExtrema(this.smoothed,"peak")){this.peaks.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}if(this.valleys.length>2&&this.peaks.length>2){if(this.valleys[this.valleys.length-1].timestamp1&&this.valley_distances.length>1){if(this.lastPeakthis.peak_distances[this.peak_distances.length-1].timestamp){let bpm,change=0;if(this.beats.length<1){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].distance+this.valley_distances[this.valley_distances.length-1].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-1].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].dt+this.valley_distances[this.valley_distances.length-1].dt));change=Math.abs(bpm-this.beats[this.beats.length-1].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-1].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-1].peak0-this.valley_distances[this.valley_distances.length-1].peak0,height1:this.peak_distances[this.peak_distances.length-1].peak1-this.valley_distances[this.valley_distances.length-1].peak1};this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}else{let bpm,change=0;if(this.beats.length<2){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-2].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance));change=Math.abs(bpm-this.beats[this.beats.length-2].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-2].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0,height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1};if(Array.isArray(beat.timestamp))beat.timestamp=beat.timestamp[0];this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}}}if(this.peaks.length>this.limit){this.peaks.shift()}if(this.valleys.length>this.limit){this.valleys.shift()}if(this.peak_distances.length>this.limit){this.peak_distances.shift()}if(this.valley_distances.length>this.limit){this.valley_distances.shift()}if(this.beats.length>this.limit){this.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)result=data.red.map((v2,i)=>{return pass(v2+data.ir[i],data.timestamp[i])}).filter(v2=>{if(v2)return true});else result=data.red.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v2,i)=>{return pass(v2,data.timestamp[i])}).filter(v2=>{if(v2)return true});return result}}};var blink_detect={sps:250,intervals:{},watch:["0"],tolerance:.2,__onconnected:node=>{node.watch.forEach(ch=>node.intervals[ch]={lowpass:new Biquad("lowpass",20,node.sps),filtered:[],averaged:[]})},__operator:function(data){let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=this.intervals[key].lowpass.applyFilter(n);this.intervals[key].filtered.push(next);this.intervals[key].averaged.push(next);if(this.intervals[key].filtered.length>checkCt){if(this.intervals[key].averaged.length>averageCt){this.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(this.intervals[key].averaged);if(Math.abs(Math.min(...this.intervals[key].filtered))>Math.abs(mean)+this.tolerance){this.intervals[key].filtered.length=0;passed=true;found[key]=true}}else this.intervals[key].filtered.shift()}};for(const key in this.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var ArrayManip=class _ArrayManip{static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,...newEntries.slice(newEntries.length-len))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d2={};data.forEach((arr,i)=>{d2[i]=arr});data=d2;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v2]=val.split(":");let fl=parseFloat(v2);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}static bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target};spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var rechk=/^([<>])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v2,o,c)=>String.fromCharCode(...new Uint8Array(v2.buffer,v2.byteOffset+o,c));var rts=(v2,o,c,s)=>new Uint8Array(v2.buffer,v2.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v2,o,c)=>str(v2,o+1,Math.min(v2.getUint8(o),c-1));var tsp=(v2,o,c,s)=>{v2.setUint8(o,s.length);rts(v2,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v2=>str(v2,o,1),p:(v2,c2)=>rts(v2,o,1,c2)})],"?":c=>[c,1,o=>({u:v2=>Boolean(v2.getUint8(o)),p:(v2,B)=>v2.setUint8(o,B)})],b:c=>[c,1,o=>({u:v2=>v2.getInt8(o),p:(v2,b)=>v2.setInt8(o,b)})],B:c=>[c,1,o=>({u:v2=>v2.getUint8(o),p:(v2,B)=>v2.setUint8(o,B)})],h:c=>[c,2,o=>({u:v2=>v2.getInt16(o,le),p:(v2,h)=>v2.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v2=>v2.getUint16(o,le),p:(v2,H)=>v2.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v2=>v2.getInt32(o,le),p:(v2,i)=>v2.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v2=>v2.getUint32(o,le),p:(v2,I)=>v2.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v2=>v2.getFloat32(o,le),p:(v2,f)=>v2.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v2=>v2.getFloat64(o,le),p:(v2,d2)=>v2.setFloat64(o,d2,le)})],s:c=>[1,c,o=>({u:v2=>str(v2,o,c),p:(v2,s)=>rts(v2,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v2=>pst(v2,o,c),p:(v2,s)=>tsp(v2,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var ByteParser=class _ByteParser extends ArrayManip{static codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x22){let int24=(255&x0)<<16|(255&x1)<<8|255&x22;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x22){return x0*65536+x1*256+x22}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x22,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x22)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x22,x3){return x0*16777216+x1*65536+x22*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M2=pattern.length;if(M2===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R2=256;var rightmost_positions=new Int32Array(R2);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v2=new DataView(arrb,offs|0);return fns.map(f=>f.u(v2))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v2,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var rms={sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{},__operator:function(data){this.watch.forEach(key=>{if(data[key]){if(!this.data[key]){if(Array.isArray(data[key])){this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0])}else this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key])}ByteParser.circularBuffer(this.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){this.rms.timestamp=data.timestamp[data.timestamp.length-1]}else this.rms.timestamp=data.timestamp}else this.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(this.watch.map(async key=>{if(this.data[key])this.rms[key]=Math.sqrt(Math.abs(this.data[key].reduce((p2,v2,i)=>p2+v2*v2)/this.data[key].length));else delete this.rms[key]}));res(this.rms)})}};var circularBuffer2d={bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false,__onconnected:function(node){for(const key in node.watch){node.data[key]=new Array(node.bufferSize).fill(0)}},__operator:function(data){let buffer2d=[];this.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(this.data[key],data[key]);buffer2d.push(this.data[key])}});return buffer2d}};var algorithms={beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d};algorithms["breath"].maxFreq=.2;})(); diff --git a/src/extras/dist/index.services.node.js b/src/extras/dist/index.services.node.js deleted file mode 100644 index fd7961ad..00000000 --- a/src/extras/dist/index.services.node.js +++ /dev/null @@ -1,32 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var require_bson=__commonJS({"struct/datastructures/bson.cjs"(exports2){"use strict";var BSON_MAJOR_VERSION=5;var BSON_INT32_MAX=2147483647;var BSON_INT32_MIN=-2147483648;var BSON_INT64_MAX=Math.pow(2,63)-1;var BSON_INT64_MIN=-Math.pow(2,63);var JS_INT_MAX=Math.pow(2,53);var JS_INT_MIN=-Math.pow(2,53);var BSON_DATA_NUMBER=1;var BSON_DATA_STRING=2;var BSON_DATA_OBJECT=3;var BSON_DATA_ARRAY=4;var BSON_DATA_BINARY=5;var BSON_DATA_UNDEFINED=6;var BSON_DATA_OID=7;var BSON_DATA_BOOLEAN=8;var BSON_DATA_DATE=9;var BSON_DATA_NULL=10;var BSON_DATA_REGEXP=11;var BSON_DATA_DBPOINTER=12;var BSON_DATA_CODE=13;var BSON_DATA_SYMBOL=14;var BSON_DATA_CODE_W_SCOPE=15;var BSON_DATA_INT=16;var BSON_DATA_TIMESTAMP=17;var BSON_DATA_LONG=18;var BSON_DATA_DECIMAL128=19;var BSON_DATA_MIN_KEY=255;var BSON_DATA_MAX_KEY=127;var BSON_BINARY_SUBTYPE_DEFAULT=0;var BSON_BINARY_SUBTYPE_UUID_NEW=4;var BSONType=Object.freeze({double:1,string:2,object:3,array:4,binData:5,undefined:6,objectId:7,bool:8,date:9,null:10,regex:11,dbPointer:12,javascript:13,symbol:14,javascriptWithScope:15,int:16,timestamp:17,long:18,decimal:19,minKey:-1,maxKey:127});var BSONError=class extends Error{get bsonError(){return true}get name(){return"BSONError"}constructor(message){super(message)}static isBSONError(value){return value!=null&&typeof value==="object"&&"bsonError"in value&&value.bsonError===true&&"name"in value&&"message"in value&&"stack"in value}};var BSONVersionError=class extends BSONError{get name(){return"BSONVersionError"}constructor(){super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`)}};var BSONRuntimeError=class extends BSONError{get name(){return"BSONRuntimeError"}constructor(message){super(message)}};function nodejsMathRandomBytes(byteLength){return nodeJsByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var nodejsRandomBytes=(()=>{try{return require("crypto").randomBytes}catch{return nodejsMathRandomBytes}})();var nodeJsByteUtils={toLocalBufferType(potentialBuffer){if(Buffer.isBuffer(potentialBuffer)){return potentialBuffer}if(ArrayBuffer.isView(potentialBuffer)){return Buffer.from(potentialBuffer.buffer,potentialBuffer.byteOffset,potentialBuffer.byteLength)}const stringTag=potentialBuffer?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialBuffer);if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return Buffer.from(potentialBuffer)}throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`)},allocate(size){return Buffer.alloc(size)},equals(a,b){return nodeJsByteUtils.toLocalBufferType(a).equals(b)},fromNumberArray(array){return Buffer.from(array)},fromBase64(base64){return Buffer.from(base64,"base64")},toBase64(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64")},fromISO88591(codePoints){return Buffer.from(codePoints,"binary")},toISO88591(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary")},fromHex(hex){return Buffer.from(hex,"hex")},toHex(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex")},fromUTF8(text){return Buffer.from(text,"utf8")},toUTF8(buffer2){return nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8")},utf8ByteLength(input){return Buffer.byteLength(input,"utf8")},encodeUTF8Into(buffer2,source,byteOffset){return nodeJsByteUtils.toLocalBufferType(buffer2).write(source,byteOffset,void 0,"utf8")},randomBytes:nodejsRandomBytes};function isReactNative(){const{navigator}=globalThis;return typeof navigator==="object"&&navigator.product==="ReactNative"}function webMathRandomBytes(byteLength){if(byteLength<0){throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`)}return webByteUtils.fromNumberArray(Array.from({length:byteLength},()=>Math.floor(Math.random()*256)))}var webRandomBytes=(()=>{const{crypto}=globalThis;if(crypto!=null&&typeof crypto.getRandomValues==="function"){return byteLength=>{return crypto.getRandomValues(webByteUtils.allocate(byteLength))}}else{if(isReactNative()){const{console:console2}=globalThis;console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.")}return webMathRandomBytes}})();var HEX_DIGIT=/(\d|[a-f])/i;var webByteUtils={toLocalBufferType(potentialUint8array){const stringTag=potentialUint8array?.[Symbol.toStringTag]??Object.prototype.toString.call(potentialUint8array);if(stringTag==="Uint8Array"){return potentialUint8array}if(ArrayBuffer.isView(potentialUint8array)){return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset,potentialUint8array.byteOffset+potentialUint8array.byteLength))}if(stringTag==="ArrayBuffer"||stringTag==="SharedArrayBuffer"||stringTag==="[object ArrayBuffer]"||stringTag==="[object SharedArrayBuffer]"){return new Uint8Array(potentialUint8array)}throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`)},allocate(size){if(typeof size!=="number"){throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`)}return new Uint8Array(size)},equals(a,b){if(a.byteLength!==b.byteLength){return false}for(let i=0;ic.charCodeAt(0))},toBase64(uint8array){return btoa(webByteUtils.toISO88591(uint8array))},fromISO88591(codePoints){return Uint8Array.from(codePoints,c=>c.charCodeAt(0)&255)},toISO88591(uint8array){return Array.from(Uint16Array.from(uint8array),b=>String.fromCharCode(b)).join("")},fromHex(hex){const evenLengthHex=hex.length%2===0?hex:hex.slice(0,hex.length-1);const buffer2=[];for(let i=0;ibyte.toString(16).padStart(2,"0")).join("")},fromUTF8(text){return new TextEncoder().encode(text)},toUTF8(uint8array){return new TextDecoder("utf8",{fatal:false}).decode(uint8array)},utf8ByteLength(input){return webByteUtils.fromUTF8(input).byteLength},encodeUTF8Into(buffer2,source,byteOffset){const bytes=webByteUtils.fromUTF8(source);buffer2.set(bytes,byteOffset);return bytes.byteLength},randomBytes:webRandomBytes};var hasGlobalBuffer=typeof Buffer==="function"&&Buffer.prototype?._isBuffer!==true;var ByteUtils=hasGlobalBuffer?nodeJsByteUtils:webByteUtils;var BSONDataView=class extends DataView{static fromUint8Array(input){return new DataView(input.buffer,input.byteOffset,input.byteLength)}};var VALIDATION_REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;var uuidValidateString=str2=>typeof str2==="string"&&VALIDATION_REGEX.test(str2);var uuidHexStringToBuffer=hexString=>{if(!uuidValidateString(hexString)){throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".')}const sanitizedHexString=hexString.replace(/-/g,"");return ByteUtils.fromHex(sanitizedHexString)};function bufferToUuidHexString(buffer2,includeDashes=true){if(includeDashes){return[ByteUtils.toHex(buffer2.subarray(0,4)),ByteUtils.toHex(buffer2.subarray(4,6)),ByteUtils.toHex(buffer2.subarray(6,8)),ByteUtils.toHex(buffer2.subarray(8,10)),ByteUtils.toHex(buffer2.subarray(10,16))].join("-")}return ByteUtils.toHex(buffer2)}function isAnyArrayBuffer(value){return["[object ArrayBuffer]","[object SharedArrayBuffer]"].includes(Object.prototype.toString.call(value))}function isUint8Array(value){return Object.prototype.toString.call(value)==="[object Uint8Array]"}function isRegExp(d){return Object.prototype.toString.call(d)==="[object RegExp]"}function isMap(d){return Object.prototype.toString.call(d)==="[object Map]"}function isDate(d){return Object.prototype.toString.call(d)==="[object Date]"}var BSONValue=class{get[Symbol.for("@@mdb.bson.version")](){return BSON_MAJOR_VERSION}};var Binary=class _Binary extends BSONValue{get _bsontype(){return"Binary"}constructor(buffer2,subType){super();if(!(buffer2==null)&&!(typeof buffer2==="string")&&!ArrayBuffer.isView(buffer2)&&!(buffer2 instanceof ArrayBuffer)&&!Array.isArray(buffer2)){throw new BSONError("Binary can only be constructed from string, Buffer, TypedArray, or Array")}this.sub_type=subType??_Binary.BSON_BINARY_SUBTYPE_DEFAULT;if(buffer2==null){this.buffer=ByteUtils.allocate(_Binary.BUFFER_SIZE);this.position=0}else{if(typeof buffer2==="string"){this.buffer=ByteUtils.fromISO88591(buffer2)}else if(Array.isArray(buffer2)){this.buffer=ByteUtils.fromNumberArray(buffer2)}else{this.buffer=ByteUtils.toLocalBufferType(buffer2)}this.position=this.buffer.byteLength}}put(byteValue){if(typeof byteValue==="string"&&byteValue.length!==1){throw new BSONError("only accepts single character String")}else if(typeof byteValue!=="number"&&byteValue.length!==1)throw new BSONError("only accepts single character Uint8Array or Array");let decodedByte;if(typeof byteValue==="string"){decodedByte=byteValue.charCodeAt(0)}else if(typeof byteValue==="number"){decodedByte=byteValue}else{decodedByte=byteValue[0]}if(decodedByte<0||decodedByte>255){throw new BSONError("only accepts number in a valid unsigned byte range 0-255")}if(this.buffer.byteLength>this.position){this.buffer[this.position++]=decodedByte}else{const newSpace=ByteUtils.allocate(_Binary.BUFFER_SIZE+this.buffer.length);newSpace.set(this.buffer,0);this.buffer=newSpace;this.buffer[this.position++]=decodedByte}}write(sequence,offset){offset=typeof offset==="number"?offset:this.position;if(this.buffer.byteLengththis.position?offset+sequence.length:this.position}else if(typeof sequence==="string"){const bytes=ByteUtils.fromISO88591(sequence);this.buffer.set(bytes,offset);this.position=offset+sequence.length>this.position?offset+sequence.length:this.position}}read(position,length){length=length&&length>0?length:this.position;return this.buffer.slice(position,position+length)}value(asRaw){asRaw=!!asRaw;if(asRaw&&this.buffer.length===this.position){return this.buffer}if(asRaw){return this.buffer.slice(0,this.position)}return ByteUtils.toISO88591(this.buffer.subarray(0,this.position))}length(){return this.position}toJSON(){return ByteUtils.toBase64(this.buffer)}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.buffer);if(encoding==="base64")return ByteUtils.toBase64(this.buffer);if(encoding==="utf8"||encoding==="utf-8")return ByteUtils.toUTF8(this.buffer);return ByteUtils.toUTF8(this.buffer)}toExtendedJSON(options){options=options||{};const base64String=ByteUtils.toBase64(this.buffer);const subType=Number(this.sub_type).toString(16);if(options.legacy){return{$binary:base64String,$type:subType.length===1?"0"+subType:subType}}return{$binary:{base64:base64String,subType:subType.length===1?"0"+subType:subType}}}toUUID(){if(this.sub_type===_Binary.SUBTYPE_UUID){return new UUID(this.buffer.slice(0,this.position))}throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${_Binary.SUBTYPE_UUID}" is currently supported.`)}static fromExtendedJSON(doc,options){options=options||{};let data;let type;if("$binary"in doc){if(options.legacy&&typeof doc.$binary==="string"&&"$type"in doc){type=doc.$type?parseInt(doc.$type,16):0;data=ByteUtils.fromBase64(doc.$binary)}else{if(typeof doc.$binary!=="string"){type=doc.$binary.subType?parseInt(doc.$binary.subType,16):0;data=ByteUtils.fromBase64(doc.$binary.base64)}}}else if("$uuid"in doc){type=4;data=uuidHexStringToBuffer(doc.$uuid)}if(!data){throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`)}return type===BSON_BINARY_SUBTYPE_UUID_NEW?new UUID(data):new _Binary(data,type)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`}};Binary.BSON_BINARY_SUBTYPE_DEFAULT=0;Binary.BUFFER_SIZE=256;Binary.SUBTYPE_DEFAULT=0;Binary.SUBTYPE_FUNCTION=1;Binary.SUBTYPE_BYTE_ARRAY=2;Binary.SUBTYPE_UUID_OLD=3;Binary.SUBTYPE_UUID=4;Binary.SUBTYPE_MD5=5;Binary.SUBTYPE_ENCRYPTED=6;Binary.SUBTYPE_COLUMN=7;Binary.SUBTYPE_USER_DEFINED=128;var UUID_BYTE_LENGTH=16;var UUID=class _UUID extends Binary{constructor(input){let bytes;let hexStr;if(input==null){bytes=_UUID.generate()}else if(input instanceof _UUID){bytes=ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));hexStr=input.__id}else if(ArrayBuffer.isView(input)&&input.byteLength===UUID_BYTE_LENGTH){bytes=ByteUtils.toLocalBufferType(input)}else if(typeof input==="string"){bytes=uuidHexStringToBuffer(input)}else{throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).")}super(bytes,BSON_BINARY_SUBTYPE_UUID_NEW);this.__id=hexStr}get id(){return this.buffer}set id(value){this.buffer=value;if(_UUID.cacheHexString){this.__id=bufferToUuidHexString(value)}}toHexString(includeDashes=true){if(_UUID.cacheHexString&&this.__id){return this.__id}const uuidHexString=bufferToUuidHexString(this.id,includeDashes);if(_UUID.cacheHexString){this.__id=uuidHexString}return uuidHexString}toString(encoding){if(encoding==="hex")return ByteUtils.toHex(this.id);if(encoding==="base64")return ByteUtils.toBase64(this.id);return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(!otherId){return false}if(otherId instanceof _UUID){return ByteUtils.equals(otherId.id,this.id)}try{return ByteUtils.equals(new _UUID(otherId).id,this.id)}catch{return false}}toBinary(){return new Binary(this.id,Binary.SUBTYPE_UUID)}static generate(){const bytes=ByteUtils.randomBytes(UUID_BYTE_LENGTH);bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;return bytes}static isValid(input){if(!input){return false}if(input instanceof _UUID){return true}if(typeof input==="string"){return uuidValidateString(input)}if(isUint8Array(input)){if(input.byteLength!==UUID_BYTE_LENGTH){return false}return(input[6]&240)===64&&(input[8]&128)===128}return false}static createFromHexString(hexString){const buffer2=uuidHexStringToBuffer(hexString);return new _UUID(buffer2)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new UUID("${this.toHexString()}")`}};var Code=class _Code extends BSONValue{get _bsontype(){return"Code"}constructor(code,scope){super();this.code=code.toString();this.scope=scope??null}toJSON(){if(this.scope!=null){return{code:this.code,scope:this.scope}}return{code:this.code}}toExtendedJSON(){if(this.scope){return{$code:this.code,$scope:this.scope}}return{$code:this.code}}static fromExtendedJSON(doc){return new _Code(doc.$code,doc.$scope)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const codeJson=this.toJSON();return`new Code("${String(codeJson.code)}"${codeJson.scope!=null?`, ${JSON.stringify(codeJson.scope)}`:""})`}};function isDBRefLike(value){return value!=null&&typeof value==="object"&&"$id"in value&&value.$id!=null&&"$ref"in value&&typeof value.$ref==="string"&&(!("$db"in value)||"$db"in value&&typeof value.$db==="string")}var DBRef=class _DBRef extends BSONValue{get _bsontype(){return"DBRef"}constructor(collection,oid,db,fields){super();const parts=collection.split(".");if(parts.length===2){db=parts.shift();collection=parts.shift()}this.collection=collection;this.oid=oid;this.db=db;this.fields=fields||{}}get namespace(){return this.collection}set namespace(value){this.collection=value}toJSON(){const o=Object.assign({$ref:this.collection,$id:this.oid},this.fields);if(this.db!=null)o.$db=this.db;return o}toExtendedJSON(options){options=options||{};let o={$ref:this.collection,$id:this.oid};if(options.legacy){return o}if(this.db)o.$db=this.db;o=Object.assign(o,this.fields);return o}static fromExtendedJSON(doc){const copy=Object.assign({},doc);delete copy.$ref;delete copy.$id;delete copy.$db;return new _DBRef(doc.$ref,doc.$id,doc.$db,copy)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){const oid=this.oid===void 0||this.oid.toString===void 0?this.oid:this.oid.toString();return`new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db?`, "${this.db}"`:""})`}};var wasm=void 0;try{wasm=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}var TWO_PWR_16_DBL=1<<16;var TWO_PWR_24_DBL=1<<24;var TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL;var TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL;var TWO_PWR_63_DBL=TWO_PWR_64_DBL/2;var INT_CACHE={};var UINT_CACHE={};var MAX_INT64_STRING_LENGTH=20;var DECIMAL_REG_EX=/^(\+?0|(\+|-)?[1-9][0-9]*)$/;var Long=class _Long extends BSONValue{get _bsontype(){return"Long"}get __isLong__(){return true}constructor(low=0,high,unsigned){super();if(typeof low==="bigint"){Object.assign(this,_Long.fromBigInt(low,!!high))}else if(typeof low==="string"){Object.assign(this,_Long.fromString(low,!!high))}else{this.low=low|0;this.high=high|0;this.unsigned=!!unsigned}}static fromBits(lowBits,highBits,unsigned){return new _Long(lowBits,highBits,unsigned)}static fromInt(value,unsigned){let obj,cachedObj,cache;if(unsigned){value>>>=0;if(cache=0<=value&&value<256){cachedObj=UINT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,(value|0)<0?-1:0,true);if(cache)UINT_CACHE[value]=obj;return obj}else{value|=0;if(cache=-128<=value&&value<128){cachedObj=INT_CACHE[value];if(cachedObj)return cachedObj}obj=_Long.fromBits(value,value<0?-1:0,false);if(cache)INT_CACHE[value]=obj;return obj}}static fromNumber(value,unsigned){if(isNaN(value))return unsigned?_Long.UZERO:_Long.ZERO;if(unsigned){if(value<0)return _Long.UZERO;if(value>=TWO_PWR_64_DBL)return _Long.MAX_UNSIGNED_VALUE}else{if(value<=-TWO_PWR_63_DBL)return _Long.MIN_VALUE;if(value+1>=TWO_PWR_63_DBL)return _Long.MAX_VALUE}if(value<0)return _Long.fromNumber(-value,unsigned).neg();return _Long.fromBits(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0,unsigned)}static fromBigInt(value,unsigned){return _Long.fromString(value.toString(),unsigned)}static fromString(str2,unsigned,radix){if(str2.length===0)throw new BSONError("empty string");if(str2==="NaN"||str2==="Infinity"||str2==="+Infinity"||str2==="-Infinity")return _Long.ZERO;if(typeof unsigned==="number"){radix=unsigned,unsigned=false}else{unsigned=!!unsigned}radix=radix||10;if(radix<2||360)throw new BSONError("interior hyphen");else if(p===0){return _Long.fromString(str2.substring(1),unsigned,radix).neg()}const radixToPower=_Long.fromNumber(Math.pow(radix,8));let result=_Long.ZERO;for(let i=0;i>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=addend.high>>>16;const b32=addend.high&65535;const b16=addend.low>>>16;const b00=addend.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00+b00;c16+=c00>>>16;c00&=65535;c16+=a16+b16;c32+=c16>>>16;c16&=65535;c32+=a32+b32;c48+=c32>>>16;c32&=65535;c48+=a48+b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}and(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low&other.low,this.high&other.high,this.unsigned)}compare(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.eq(other))return 0;const thisNeg=this.isNegative(),otherNeg=other.isNegative();if(thisNeg&&!otherNeg)return-1;if(!thisNeg&&otherNeg)return 1;if(!this.unsigned)return this.sub(other).isNegative()?-1:1;return other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}comp(other){return this.compare(other)}divide(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(divisor.isZero())throw new BSONError("division by zero");if(wasm){if(!this.unsigned&&this.high===-2147483648&&divisor.low===-1&&divisor.high===-1){return this}const low=(this.unsigned?wasm.div_u:wasm.div_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?_Long.UZERO:_Long.ZERO;let approx,rem,res;if(!this.unsigned){if(this.eq(_Long.MIN_VALUE)){if(divisor.eq(_Long.ONE)||divisor.eq(_Long.NEG_ONE))return _Long.MIN_VALUE;else if(divisor.eq(_Long.MIN_VALUE))return _Long.ONE;else{const halfThis=this.shr(1);approx=halfThis.div(divisor).shl(1);if(approx.eq(_Long.ZERO)){return divisor.isNegative()?_Long.ONE:_Long.NEG_ONE}else{rem=this.sub(divisor.mul(approx));res=approx.add(rem.div(divisor));return res}}}else if(divisor.eq(_Long.MIN_VALUE))return this.unsigned?_Long.UZERO:_Long.ZERO;if(this.isNegative()){if(divisor.isNegative())return this.neg().div(divisor.neg());return this.neg().div(divisor).neg()}else if(divisor.isNegative())return this.div(divisor.neg()).neg();res=_Long.ZERO}else{if(!divisor.unsigned)divisor=divisor.toUnsigned();if(divisor.gt(this))return _Long.UZERO;if(divisor.gt(this.shru(1)))return _Long.UONE;res=_Long.UZERO}rem=this;while(rem.gte(divisor)){approx=Math.max(1,Math.floor(rem.toNumber()/divisor.toNumber()));const log2=Math.ceil(Math.log(approx)/Math.LN2);const delta=log2<=48?1:Math.pow(2,log2-48);let approxRes=_Long.fromNumber(approx);let approxRem=approxRes.mul(divisor);while(approxRem.isNegative()||approxRem.gt(rem)){approx-=delta;approxRes=_Long.fromNumber(approx,this.unsigned);approxRem=approxRes.mul(divisor)}if(approxRes.isZero())approxRes=_Long.ONE;res=res.add(approxRes);rem=rem.sub(approxRem)}return res}div(divisor){return this.divide(divisor)}equals(other){if(!_Long.isLong(other))other=_Long.fromValue(other);if(this.unsigned!==other.unsigned&&this.high>>>31===1&&other.high>>>31===1)return false;return this.high===other.high&&this.low===other.low}eq(other){return this.equals(other)}getHighBits(){return this.high}getHighBitsUnsigned(){return this.high>>>0}getLowBits(){return this.low}getLowBitsUnsigned(){return this.low>>>0}getNumBitsAbs(){if(this.isNegative()){return this.eq(_Long.MIN_VALUE)?64:this.neg().getNumBitsAbs()}const val=this.high!==0?this.high:this.low;let bit;for(bit=31;bit>0;bit--)if((val&1<0}gt(other){return this.greaterThan(other)}greaterThanOrEqual(other){return this.comp(other)>=0}gte(other){return this.greaterThanOrEqual(other)}ge(other){return this.greaterThanOrEqual(other)}isEven(){return(this.low&1)===0}isNegative(){return!this.unsigned&&this.high<0}isOdd(){return(this.low&1)===1}isPositive(){return this.unsigned||this.high>=0}isZero(){return this.high===0&&this.low===0}lessThan(other){return this.comp(other)<0}lt(other){return this.lessThan(other)}lessThanOrEqual(other){return this.comp(other)<=0}lte(other){return this.lessThanOrEqual(other)}modulo(divisor){if(!_Long.isLong(divisor))divisor=_Long.fromValue(divisor);if(wasm){const low=(this.unsigned?wasm.rem_u:wasm.rem_s)(this.low,this.high,divisor.low,divisor.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}return this.sub(this.div(divisor).mul(divisor))}mod(divisor){return this.modulo(divisor)}rem(divisor){return this.modulo(divisor)}multiply(multiplier){if(this.isZero())return _Long.ZERO;if(!_Long.isLong(multiplier))multiplier=_Long.fromValue(multiplier);if(wasm){const low=wasm.mul(this.low,this.high,multiplier.low,multiplier.high);return _Long.fromBits(low,wasm.get_high(),this.unsigned)}if(multiplier.isZero())return _Long.ZERO;if(this.eq(_Long.MIN_VALUE))return multiplier.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(multiplier.eq(_Long.MIN_VALUE))return this.isOdd()?_Long.MIN_VALUE:_Long.ZERO;if(this.isNegative()){if(multiplier.isNegative())return this.neg().mul(multiplier.neg());else return this.neg().mul(multiplier).neg()}else if(multiplier.isNegative())return this.mul(multiplier.neg()).neg();if(this.lt(_Long.TWO_PWR_24)&&multiplier.lt(_Long.TWO_PWR_24))return _Long.fromNumber(this.toNumber()*multiplier.toNumber(),this.unsigned);const a48=this.high>>>16;const a32=this.high&65535;const a16=this.low>>>16;const a00=this.low&65535;const b48=multiplier.high>>>16;const b32=multiplier.high&65535;const b16=multiplier.low>>>16;const b00=multiplier.low&65535;let c48=0,c32=0,c16=0,c00=0;c00+=a00*b00;c16+=c00>>>16;c00&=65535;c16+=a16*b00;c32+=c16>>>16;c16&=65535;c16+=a00*b16;c32+=c16>>>16;c16&=65535;c32+=a32*b00;c48+=c32>>>16;c32&=65535;c32+=a16*b16;c48+=c32>>>16;c32&=65535;c32+=a00*b32;c48+=c32>>>16;c32&=65535;c48+=a48*b00+a32*b16+a16*b32+a00*b48;c48&=65535;return _Long.fromBits(c16<<16|c00,c48<<16|c32,this.unsigned)}mul(multiplier){return this.multiply(multiplier)}negate(){if(!this.unsigned&&this.eq(_Long.MIN_VALUE))return _Long.MIN_VALUE;return this.not().add(_Long.ONE)}neg(){return this.negate()}not(){return _Long.fromBits(~this.low,~this.high,this.unsigned)}notEquals(other){return!this.equals(other)}neq(other){return this.notEquals(other)}ne(other){return this.notEquals(other)}or(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low|other.low,this.high|other.high,this.unsigned)}shiftLeft(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();if((numBits&=63)===0)return this;else if(numBits<32)return _Long.fromBits(this.low<>>32-numBits,this.unsigned);else return _Long.fromBits(0,this.low<>>numBits|this.high<<32-numBits,this.high>>numBits,this.unsigned);else return _Long.fromBits(this.high>>numBits-32,this.high>=0?0:-1,this.unsigned)}shr(numBits){return this.shiftRight(numBits)}shiftRightUnsigned(numBits){if(_Long.isLong(numBits))numBits=numBits.toInt();numBits&=63;if(numBits===0)return this;else{const high=this.high;if(numBits<32){const low=this.low;return _Long.fromBits(low>>>numBits|high<<32-numBits,high>>>numBits,this.unsigned)}else if(numBits===32)return _Long.fromBits(high,0,this.unsigned);else return _Long.fromBits(high>>>numBits-32,0,this.unsigned)}}shr_u(numBits){return this.shiftRightUnsigned(numBits)}shru(numBits){return this.shiftRightUnsigned(numBits)}subtract(subtrahend){if(!_Long.isLong(subtrahend))subtrahend=_Long.fromValue(subtrahend);return this.add(subtrahend.neg())}sub(subtrahend){return this.subtract(subtrahend)}toInt(){return this.unsigned?this.low>>>0:this.low}toNumber(){if(this.unsigned)return(this.high>>>0)*TWO_PWR_32_DBL+(this.low>>>0);return this.high*TWO_PWR_32_DBL+(this.low>>>0)}toBigInt(){return BigInt(this.toString())}toBytes(le){return le?this.toBytesLE():this.toBytesBE()}toBytesLE(){const hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}toBytesBE(){const hi=this.high,lo=this.low;return[hi>>>24,hi>>>16&255,hi>>>8&255,hi&255,lo>>>24,lo>>>16&255,lo>>>8&255,lo&255]}toSigned(){if(!this.unsigned)return this;return _Long.fromBits(this.low,this.high,false)}toString(radix){radix=radix||10;if(radix<2||36>>0;let digits=intval.toString(radix);rem=remDiv;if(rem.isZero()){return digits+result}else{while(digits.length<6)digits="0"+digits;result=""+digits+result}}}toUnsigned(){if(this.unsigned)return this;return _Long.fromBits(this.low,this.high,true)}xor(other){if(!_Long.isLong(other))other=_Long.fromValue(other);return _Long.fromBits(this.low^other.low,this.high^other.high,this.unsigned)}eqz(){return this.isZero()}le(other){return this.lessThanOrEqual(other)}toExtendedJSON(options){if(options&&options.relaxed)return this.toNumber();return{$numberLong:this.toString()}}static fromExtendedJSON(doc,options){const{useBigInt64=false,relaxed=true}={...options};if(doc.$numberLong.length>MAX_INT64_STRING_LENGTH){throw new BSONError("$numberLong string is too long")}if(!DECIMAL_REG_EX.test(doc.$numberLong)){throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`)}if(useBigInt64){const bigIntResult=BigInt(doc.$numberLong);return BigInt.asIntN(64,bigIntResult)}const longResult=_Long.fromString(doc.$numberLong);if(relaxed){return longResult.toNumber()}return longResult}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Long("${this.toString()}"${this.unsigned?", true":""})`}};Long.TWO_PWR_24=Long.fromInt(TWO_PWR_24_DBL);Long.MAX_UNSIGNED_VALUE=Long.fromBits(4294967295|0,4294967295|0,true);Long.ZERO=Long.fromInt(0);Long.UZERO=Long.fromInt(0,true);Long.ONE=Long.fromInt(1);Long.UONE=Long.fromInt(1,true);Long.NEG_ONE=Long.fromInt(-1);Long.MAX_VALUE=Long.fromBits(4294967295|0,2147483647|0,false);Long.MIN_VALUE=Long.fromBits(0,2147483648|0,false);var PARSE_STRING_REGEXP=/^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;var PARSE_INF_REGEXP=/^(\+|-)?(Infinity|inf)$/i;var PARSE_NAN_REGEXP=/^(\+|-)?NaN$/i;var EXPONENT_MAX=6111;var EXPONENT_MIN=-6176;var EXPONENT_BIAS=6176;var MAX_DIGITS=34;var NAN_BUFFER=ByteUtils.fromNumberArray([124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_NEGATIVE_BUFFER=ByteUtils.fromNumberArray([248,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var INF_POSITIVE_BUFFER=ByteUtils.fromNumberArray([120,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0].reverse());var EXPONENT_REGEX=/^([-+])?(\d+)?$/;var COMBINATION_MASK=31;var EXPONENT_MASK=16383;var COMBINATION_INFINITY=30;var COMBINATION_NAN=31;function isDigit(value){return!isNaN(parseInt(value,10))}function divideu128(value){const DIVISOR=Long.fromNumber(1e3*1e3*1e3);let _rem=Long.fromNumber(0);if(!value.parts[0]&&!value.parts[1]&&!value.parts[2]&&!value.parts[3]){return{quotient:value,rem:_rem}}for(let i=0;i<=3;i++){_rem=_rem.shiftLeft(32);_rem=_rem.add(new Long(value.parts[i],0));value.parts[i]=_rem.div(DIVISOR).low;_rem=_rem.modulo(DIVISOR)}return{quotient:value,rem:_rem}}function multiply64x2(left,right){if(!left&&!right){return{high:Long.fromNumber(0),low:Long.fromNumber(0)}}const leftHigh=left.shiftRightUnsigned(32);const leftLow=new Long(left.getLowBits(),0);const rightHigh=right.shiftRightUnsigned(32);const rightLow=new Long(right.getLowBits(),0);let productHigh=leftHigh.multiply(rightHigh);let productMid=leftHigh.multiply(rightLow);const productMid2=leftLow.multiply(rightHigh);let productLow=leftLow.multiply(rightLow);productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productMid=new Long(productMid.getLowBits(),0).add(productMid2).add(productLow.shiftRightUnsigned(32));productHigh=productHigh.add(productMid.shiftRightUnsigned(32));productLow=productMid.shiftLeft(32).add(new Long(productLow.getLowBits(),0));return{high:productHigh,low:productLow}}function lessThan(left,right){const uhleft=left.high>>>0;const uhright=right.high>>>0;if(uhleft>>0;const ulright=right.low>>>0;if(ulleft=7e3){throw new BSONError(""+representation+" not a valid Decimal128 string")}const stringMatch=representation.match(PARSE_STRING_REGEXP);const infMatch=representation.match(PARSE_INF_REGEXP);const nanMatch=representation.match(PARSE_NAN_REGEXP);if(!stringMatch&&!infMatch&&!nanMatch||representation.length===0){throw new BSONError(""+representation+" not a valid Decimal128 string")}if(stringMatch){const unsignedNumber=stringMatch[2];const e=stringMatch[4];const expSign=stringMatch[5];const expNumber=stringMatch[6];if(e&&expNumber===void 0)invalidErr(representation,"missing exponent power");if(e&&unsignedNumber===void 0)invalidErr(representation,"missing exponent base");if(e===void 0&&(expSign||expNumber)){invalidErr(representation,"missing e before exponent")}}if(representation[index]==="+"||representation[index]==="-"){isNegative=representation[index++]==="-"}if(!isDigit(representation[index])&&representation[index]!=="."){if(representation[index]==="i"||representation[index]==="I"){return new _Decimal128(isNegative?INF_NEGATIVE_BUFFER:INF_POSITIVE_BUFFER)}else if(representation[index]==="N"){return new _Decimal128(NAN_BUFFER)}}while(isDigit(representation[index])||representation[index]==="."){if(representation[index]==="."){if(sawRadix)invalidErr(representation,"contains multiple periods");sawRadix=true;index=index+1;continue}if(nDigitsStored<34){if(representation[index]!=="0"||foundNonZero){if(!foundNonZero){firstNonZero=nDigitsRead}foundNonZero=true;digits[digitsInsert++]=parseInt(representation[index],10);nDigitsStored=nDigitsStored+1}}if(foundNonZero)nDigits=nDigits+1;if(sawRadix)radixPosition=radixPosition+1;nDigitsRead=nDigitsRead+1;index=index+1}if(sawRadix&&!nDigitsRead)throw new BSONError(""+representation+" not a valid Decimal128 string");if(representation[index]==="e"||representation[index]==="E"){const match=representation.substr(++index).match(EXPONENT_REGEX);if(!match||!match[2])return new _Decimal128(NAN_BUFFER);exponent=parseInt(match[0],10);index=index+match[0].length}if(representation[index])return new _Decimal128(NAN_BUFFER);firstDigit=0;if(!nDigitsStored){firstDigit=0;lastDigit=0;digits[0]=0;nDigits=1;nDigitsStored=1;significantDigits=0}else{lastDigit=nDigitsStored-1;significantDigits=nDigits;if(significantDigits!==1){while(digits[firstNonZero+significantDigits-1]===0){significantDigits=significantDigits-1}}}if(exponent<=radixPosition&&radixPosition-exponent>1<<14){exponent=EXPONENT_MIN}else{exponent=exponent-radixPosition}while(exponent>EXPONENT_MAX){lastDigit=lastDigit+1;if(lastDigit-firstDigit>MAX_DIGITS){const digitsString=digits.join("");if(digitsString.match(/^0+$/)){exponent=EXPONENT_MAX;break}invalidErr(representation,"overflow")}exponent=exponent-1}while(exponent=5){roundBit=1;if(roundDigit===5){roundBit=digits[lastDigit]%2===1?1:0;for(i=firstNonZero+lastDigit+2;i=0;dIdx--){if(++digits[dIdx]>9){digits[dIdx]=0;if(dIdx===0){if(exponent>8&255;buffer2[index++]=dec.low.low>>16&255;buffer2[index++]=dec.low.low>>24&255;buffer2[index++]=dec.low.high&255;buffer2[index++]=dec.low.high>>8&255;buffer2[index++]=dec.low.high>>16&255;buffer2[index++]=dec.low.high>>24&255;buffer2[index++]=dec.high.low&255;buffer2[index++]=dec.high.low>>8&255;buffer2[index++]=dec.high.low>>16&255;buffer2[index++]=dec.high.low>>24&255;buffer2[index++]=dec.high.high&255;buffer2[index++]=dec.high.high>>8&255;buffer2[index++]=dec.high.high>>16&255;buffer2[index++]=dec.high.high>>24&255;return new _Decimal128(buffer2)}toString(){let biased_exponent;let significand_digits=0;const significand=new Array(36);for(let i=0;i>26&COMBINATION_MASK;if(combination>>3===3){if(combination===COMBINATION_INFINITY){return string.join("")+"Infinity"}else if(combination===COMBINATION_NAN){return"NaN"}else{biased_exponent=high>>15&EXPONENT_MASK;significand_msb=8+(high>>14&1)}}else{significand_msb=high>>14&7;biased_exponent=high>>17&EXPONENT_MASK}const exponent=biased_exponent-EXPONENT_BIAS;significand128.parts[0]=(high&16383)+((significand_msb&15)<<14);significand128.parts[1]=midh;significand128.parts[2]=midl;significand128.parts[3]=low;if(significand128.parts[0]===0&&significand128.parts[1]===0&&significand128.parts[2]===0&&significand128.parts[3]===0){is_zero=true}else{for(k=3;k>=0;k--){let least_digits=0;const result=divideu128(significand128);significand128=result.quotient;least_digits=result.rem.low;if(!least_digits)continue;for(j=8;j>=0;j--){significand[k*9+j]=least_digits%10;least_digits=Math.floor(least_digits/10)}}}if(is_zero){significand_digits=1;significand[index]=0}else{significand_digits=36;while(!significand[index]){significand_digits=significand_digits-1;index=index+1}}const scientific_exponent=significand_digits-1+exponent;if(scientific_exponent>=34||scientific_exponent<=-7||exponent>0){if(significand_digits>34){string.push(`${0}`);if(exponent>0)string.push(`E+${exponent}`);else if(exponent<0)string.push(`E${exponent}`);return string.join("")}string.push(`${significand[index++]}`);significand_digits=significand_digits-1;if(significand_digits){string.push(".")}for(let i=0;i0){string.push(`+${scientific_exponent}`)}else{string.push(`${scientific_exponent}`)}}else{if(exponent>=0){for(let i=0;i0){for(let i=0;i>8&255;buffer2[9]=inc>>16&255;return buffer2}toString(encoding){if(encoding==="base64")return ByteUtils.toBase64(this.id);if(encoding==="hex")return this.toHexString();return this.toHexString()}toJSON(){return this.toHexString()}equals(otherId){if(otherId===void 0||otherId===null){return false}if(otherId instanceof _ObjectId){return this[kId][11]===otherId[kId][11]&&ByteUtils.equals(this[kId],otherId[kId])}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12&&isUint8Array(this.id)){return ByteUtils.equals(this.id,ByteUtils.fromISO88591(otherId))}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===24){return otherId.toLowerCase()===this.toHexString()}if(typeof otherId==="string"&&_ObjectId.isValid(otherId)&&otherId.length===12){return ByteUtils.equals(ByteUtils.fromUTF8(otherId),this.id)}if(typeof otherId==="object"&&"toHexString"in otherId&&typeof otherId.toHexString==="function"){const otherIdString=otherId.toHexString();const thisIdString=this.toHexString().toLowerCase();return typeof otherIdString==="string"&&otherIdString.toLowerCase()===thisIdString}return false}getTimestamp(){const timestamp=new Date;const time=BSONDataView.fromUint8Array(this.id).getUint32(0,false);timestamp.setTime(Math.floor(time)*1e3);return timestamp}static createPk(){return new _ObjectId}static createFromTime(time){const buffer2=ByteUtils.fromNumberArray([0,0,0,0,0,0,0,0,0,0,0,0]);BSONDataView.fromUint8Array(buffer2).setUint32(0,time,false);return new _ObjectId(buffer2)}static createFromHexString(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new BSONError("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}return new _ObjectId(ByteUtils.fromHex(hexString))}static isValid(id){if(id==null)return false;try{new _ObjectId(id);return true}catch{return false}}toExtendedJSON(){if(this.toHexString)return{$oid:this.toHexString()};return{$oid:this.toString("hex")}}static fromExtendedJSON(doc){return new _ObjectId(doc.$oid)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new ObjectId("${this.toHexString()}")`}};ObjectId2.index=Math.floor(Math.random()*16777215);function internalCalculateObjectSize(object,serializeFunctions,ignoreUndefined){let totalLength=4+1;if(Array.isArray(object)){for(let i=0;i=JS_INT_MIN&&value<=JS_INT_MAX){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(4+1)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}case"undefined":if(isArray||!ignoreUndefined)return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1;return 0;case"boolean":return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+1);case"object":if(value!=null&&typeof value._bsontype==="string"&&value[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(value==null||value._bsontype==="MinKey"||value._bsontype==="MaxKey"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1}else if(value._bsontype==="ObjectId"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(12+1)}else if(value instanceof Date||isDate(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(ArrayBuffer.isView(value)||value instanceof ArrayBuffer||isAnyArrayBuffer(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(1+4+1)+value.byteLength}else if(value._bsontype==="Long"||value._bsontype==="Double"||value._bsontype==="Timestamp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(8+1)}else if(value._bsontype==="Decimal128"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(16+1)}else if(value._bsontype==="Code"){if(value.scope!=null&&Object.keys(value.scope).length>0){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+4+ByteUtils.utf8ByteLength(value.code.toString())+1+internalCalculateObjectSize(value.scope,serializeFunctions,ignoreUndefined)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.code.toString())+1}}else if(value._bsontype==="Binary"){const binary=value;if(binary.sub_type===Binary.SUBTYPE_BYTE_ARRAY){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1+4)}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+(binary.position+1+4+1)}}else if(value._bsontype==="Symbol"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+ByteUtils.utf8ByteLength(value.value)+4+1+1}else if(value._bsontype==="DBRef"){const ordered_values=Object.assign({$ref:value.collection,$id:value.oid},value.fields);if(value.db!=null){ordered_values["$db"]=value.db}return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+internalCalculateObjectSize(ordered_values,serializeFunctions,ignoreUndefined)}else if(value instanceof RegExp||isRegExp(value)){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.source)+1+(value.global?1:0)+(value.ignoreCase?1:0)+(value.multiline?1:0)+1}else if(value._bsontype==="BSONRegExp"){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+ByteUtils.utf8ByteLength(value.pattern)+1+ByteUtils.utf8ByteLength(value.options)+1}else{return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+internalCalculateObjectSize(value,serializeFunctions,ignoreUndefined)+1}case"function":if(serializeFunctions){return(name!=null?ByteUtils.utf8ByteLength(name)+1:0)+1+4+ByteUtils.utf8ByteLength(value.toString())+1}}return 0}function alphabetize(str2){return str2.split("").sort().join("")}var BSONRegExp=class _BSONRegExp extends BSONValue{get _bsontype(){return"BSONRegExp"}constructor(pattern,options){super();this.pattern=pattern;this.options=alphabetize(options??"");if(this.pattern.indexOf("\0")!==-1){throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`)}if(this.options.indexOf("\0")!==-1){throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`)}for(let i=0;i4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max")}if(low.i>4294967295){throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max")}super(low.i.valueOf(),low.t.valueOf(),true)}else{throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }")}}toJSON(){return{$timestamp:this.toString()}}static fromInt(value){return new _Timestamp(Long.fromInt(value,true))}static fromNumber(value){return new _Timestamp(Long.fromNumber(value,true))}static fromBits(lowBits,highBits){return new _Timestamp({i:lowBits,t:highBits})}static fromString(str2,optRadix){return new _Timestamp(Long.fromString(str2,true,optRadix))}toExtendedJSON(){return{$timestamp:{t:this.high>>>0,i:this.low>>>0}}}static fromExtendedJSON(doc){const i=Long.isLong(doc.$timestamp.i)?doc.$timestamp.i.getLowBitsUnsigned():doc.$timestamp.i;const t=Long.isLong(doc.$timestamp.t)?doc.$timestamp.t.getLowBitsUnsigned():doc.$timestamp.t;return new _Timestamp({t,i})}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`}};Timestamp.MAX_VALUE=Long.MAX_UNSIGNED_VALUE;var FIRST_BIT=128;var FIRST_TWO_BITS=192;var FIRST_THREE_BITS=224;var FIRST_FOUR_BITS=240;var FIRST_FIVE_BITS=248;var TWO_BIT_CHAR=192;var THREE_BIT_CHAR=224;var FOUR_BIT_CHAR=240;var CONTINUING_CHAR=128;function validateUtf8(bytes,start,end){let continuation=0;for(let i=start;i= 5, is ${size}`)}if(options.allowObjectSmallerThanBufferSize&&buffer2.length= bson size ${size}`)}if(!options.allowObjectSmallerThanBufferSize&&buffer2.length!==size){throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`)}if(size+index>buffer2.byteLength){throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer2.byteLength})`)}if(buffer2[index+size-1]!==0){throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00")}return deserializeObject(buffer2,index,options,isArray)}var allowedDBRefKeys=/^\$ref$|^\$id$|^\$db$/;function deserializeObject(buffer2,index,options,isArray=false){const fieldsAsRaw=options["fieldsAsRaw"]==null?null:options["fieldsAsRaw"];const raw=options["raw"]==null?false:options["raw"];const bsonRegExp=typeof options["bsonRegExp"]==="boolean"?options["bsonRegExp"]:false;const promoteBuffers=options.promoteBuffers??false;const promoteLongs=options.promoteLongs??true;const promoteValues=options.promoteValues??true;const useBigInt64=options.useBigInt64??false;if(useBigInt64&&!promoteValues){throw new BSONError("Must either request bigint or Long for int64 deserialization")}if(useBigInt64&&!promoteLongs){throw new BSONError("Must either request bigint or Long for int64 deserialization")}const validation=options.validation==null?{utf8:true}:options.validation;let globalUTFValidation=true;let validationSetting;const utf8KeysSet=new Set;const utf8ValidatedKeys=validation.utf8;if(typeof utf8ValidatedKeys==="boolean"){validationSetting=utf8ValidatedKeys}else{globalUTFValidation=false;const utf8ValidationValues=Object.keys(utf8ValidatedKeys).map(function(key){return utf8ValidatedKeys[key]});if(utf8ValidationValues.length===0){throw new BSONError("UTF-8 validation setting cannot be empty")}if(typeof utf8ValidationValues[0]!=="boolean"){throw new BSONError("Invalid UTF-8 validation option, must specify boolean values")}validationSetting=utf8ValidationValues[0];if(!utf8ValidationValues.every(item=>item===validationSetting)){throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false")}}if(!globalUTFValidation){for(const key of Object.keys(utf8ValidatedKeys)){utf8KeysSet.add(key)}}const startIndex=index;if(buffer2.length<5)throw new BSONError("corrupt bson message < 5 bytes long");const size=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(size<5||size>buffer2.length)throw new BSONError("corrupt bson message");const object=isArray?[]:{};let arrayIndex=0;const done=false;let isPossibleDBRef=isArray?false:null;const dataview=new DataView(buffer2.buffer,buffer2.byteOffset,buffer2.byteLength);while(!done){const elementType=buffer2[index++];if(elementType===0)break;let i=index;while(buffer2[i]!==0&&i=buffer2.byteLength)throw new BSONError("Bad BSON Document: illegal CString");const name=isArray?arrayIndex++:ByteUtils.toUTF8(buffer2.subarray(index,i));let shouldValidateKey=true;if(globalUTFValidation||utf8KeysSet.has(name)){shouldValidateKey=validationSetting}else{shouldValidateKey=!validationSetting}if(isPossibleDBRef!==false&&name[0]==="$"){isPossibleDBRef=allowedDBRefKeys.test(name)}let value;index=i+1;if(elementType===BSON_DATA_STRING){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}value=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize}else if(elementType===BSON_DATA_OID){const oid=ByteUtils.allocate(12);oid.set(buffer2.subarray(index,index+12));value=new ObjectId2(oid);index=index+12}else if(elementType===BSON_DATA_INT&&promoteValues===false){value=new Int32(buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24)}else if(elementType===BSON_DATA_INT){value=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24}else if(elementType===BSON_DATA_NUMBER&&promoteValues===false){value=new Double(dataview.getFloat64(index,true));index=index+8}else if(elementType===BSON_DATA_NUMBER){value=dataview.getFloat64(index,true);index=index+8}else if(elementType===BSON_DATA_DATE){const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;value=new Date(new Long(lowBits,highBits).toNumber())}else if(elementType===BSON_DATA_BOOLEAN){if(buffer2[index]!==0&&buffer2[index]!==1)throw new BSONError("illegal boolean type value");value=buffer2[index++]===1}else if(elementType===BSON_DATA_OBJECT){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;if(objectSize<=0||objectSize>buffer2.length-index)throw new BSONError("bad embedded document length in bson");if(raw){value=buffer2.slice(index,index+objectSize)}else{let objectOptions=options;if(!globalUTFValidation){objectOptions={...options,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,objectOptions,false)}index=index+objectSize}else if(elementType===BSON_DATA_ARRAY){const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;let arrayOptions=options;const stopIndex=index+objectSize;if(fieldsAsRaw&&fieldsAsRaw[name]){arrayOptions={...options,raw:true}}if(!globalUTFValidation){arrayOptions={...arrayOptions,validation:{utf8:shouldValidateKey}}}value=deserializeObject(buffer2,_index,arrayOptions,true);index=index+objectSize;if(buffer2[index-1]!==0)throw new BSONError("invalid array terminator byte");if(index!==stopIndex)throw new BSONError("corrupted array bson")}else if(elementType===BSON_DATA_UNDEFINED){value=void 0}else if(elementType===BSON_DATA_NULL){value=null}else if(elementType===BSON_DATA_LONG){const dataview2=BSONDataView.fromUint8Array(buffer2.subarray(index,index+8));const lowBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const highBits=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const long=new Long(lowBits,highBits);if(useBigInt64){value=dataview2.getBigInt64(0,true)}else if(promoteLongs&&promoteValues===true){value=long.lessThanOrEqual(JS_INT_MAX_LONG)&&long.greaterThanOrEqual(JS_INT_MIN_LONG)?long.toNumber():long}else{value=long}}else if(elementType===BSON_DATA_DECIMAL128){const bytes=ByteUtils.allocate(16);bytes.set(buffer2.subarray(index,index+16),0);index=index+16;value=new Decimal128(bytes)}else if(elementType===BSON_DATA_BINARY){let binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;const totalBinarySize=binarySize;const subType=buffer2[index++];if(binarySize<0)throw new BSONError("Negative binary type element size found");if(binarySize>buffer2.byteLength)throw new BSONError("Binary type size larger than document size");if(buffer2["slice"]!=null){if(subType===Binary.SUBTYPE_BYTE_ARRAY){binarySize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(binarySize<0)throw new BSONError("Negative binary type element size found for subtype 0x02");if(binarySize>totalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySizetotalBinarySize-4)throw new BSONError("Binary type with subtype 0x02 contains too long binary size");if(binarySize=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;const optionsArray=new Array(regExpOptions.length);for(i=0;i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const source=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;i=index;while(buffer2[i]!==0&&i=buffer2.length)throw new BSONError("Bad BSON Document: illegal CString");const regExpOptions=ByteUtils.toUTF8(buffer2.subarray(index,i));index=i+1;value=new BSONRegExp(source,regExpOptions)}else if(elementType===BSON_DATA_SYMBOL){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const symbol=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=promoteValues?symbol:new BSONSymbol(symbol);index=index+stringSize}else if(elementType===BSON_DATA_TIMESTAMP){const i2=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);const t=buffer2[index++]+buffer2[index++]*(1<<8)+buffer2[index++]*(1<<16)+buffer2[index++]*(1<<24);value=new Timestamp({i:i2,t})}else if(elementType===BSON_DATA_MIN_KEY){value=new MinKey}else if(elementType===BSON_DATA_MAX_KEY){value=new MaxKey}else if(elementType===BSON_DATA_CODE){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);value=new Code(functionString);index=index+stringSize}else if(elementType===BSON_DATA_CODE_W_SCOPE){const totalSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(totalSize<4+4+4+1){throw new BSONError("code_w_scope total size shorter minimum expected length")}const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0){throw new BSONError("bad string length in bson")}const functionString=getValidatedString(buffer2,index,index+stringSize-1,shouldValidateKey);index=index+stringSize;const _index=index;const objectSize=buffer2[index]|buffer2[index+1]<<8|buffer2[index+2]<<16|buffer2[index+3]<<24;const scopeObject=deserializeObject(buffer2,_index,options,false);index=index+objectSize;if(totalSize<4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too short, truncating scope")}if(totalSize>4+4+objectSize+stringSize){throw new BSONError("code_w_scope total size is too long, clips outer document")}value=new Code(functionString,scopeObject)}else if(elementType===BSON_DATA_DBPOINTER){const stringSize=buffer2[index++]|buffer2[index++]<<8|buffer2[index++]<<16|buffer2[index++]<<24;if(stringSize<=0||stringSize>buffer2.length-index||buffer2[index+stringSize-1]!==0)throw new BSONError("bad string length in bson");if(validation!=null&&validation.utf8){if(!validateUtf8(buffer2,index,index+stringSize-1)){throw new BSONError("Invalid UTF-8 string in BSON document")}}const namespace=ByteUtils.toUTF8(buffer2.subarray(index,index+stringSize-1));index=index+stringSize;const oidBuffer=ByteUtils.allocate(12);oidBuffer.set(buffer2.subarray(index,index+12),0);const oid=new ObjectId2(oidBuffer);index=index+12;value=new DBRef(namespace,oid)}else{throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`)}if(name==="__proto__"){Object.defineProperty(object,name,{value,writable:true,enumerable:true,configurable:true})}else{object[name]=value}}if(size!==index-startIndex){if(isArray)throw new BSONError("corrupt array bson");throw new BSONError("corrupt object bson")}if(!isPossibleDBRef)return object;if(isDBRefLike(object)){const copy=Object.assign({},object);delete copy.$ref;delete copy.$id;delete copy.$db;return new DBRef(object.$ref,object.$id,object.$db,copy)}return object}function getValidatedString(buffer2,start,end,shouldValidateUtf8){const value=ByteUtils.toUTF8(buffer2.subarray(start,end));if(shouldValidateUtf8){for(let i=0;i>24&255;buffer2[index+2]=size+1>>16&255;buffer2[index+1]=size+1>>8&255;buffer2[index]=size+1&255;index=index+4+size;buffer2[index++]=0;return index}var NUMBER_SPACE=new DataView(new ArrayBuffer(8),0,8);var FOUR_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,4);var EIGHT_BYTE_VIEW_ON_NUMBER=new Uint8Array(NUMBER_SPACE.buffer,0,8);function serializeNumber(buffer2,key,value,index){const isNegativeZero=Object.is(value,-0);const type=!isNegativeZero&&Number.isSafeInteger(value)&&value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN?BSON_DATA_INT:BSON_DATA_NUMBER;if(type===BSON_DATA_INT){NUMBER_SPACE.setInt32(0,value,true)}else{NUMBER_SPACE.setFloat64(0,value,true)}const bytes=type===BSON_DATA_INT?FOUR_BYTE_VIEW_ON_NUMBER:EIGHT_BYTE_VIEW_ON_NUMBER;buffer2[index++]=type;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(bytes,index);index+=bytes.byteLength;return index}function serializeBigInt(buffer2,key,value,index){buffer2[index++]=BSON_DATA_LONG;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index+=numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setBigInt64(0,value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index+=EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;return index}function serializeNull(buffer2,key,_,index){buffer2[index++]=BSON_DATA_NULL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeBoolean(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BOOLEAN;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value?1:0;return index}function serializeDate(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DATE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const dateInMilis=Long.fromNumber(value.getTime());const lowBits=dateInMilis.getLowBits();const highBits=dateInMilis.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.source&&value.source.match(regexp)!=null){throw new BSONError("value "+value.source+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.source,index);buffer2[index++]=0;if(value.ignoreCase)buffer2[index++]=105;if(value.global)buffer2[index++]=115;if(value.multiline)buffer2[index++]=109;buffer2[index++]=0;return index}function serializeBSONRegExp(buffer2,key,value,index){buffer2[index++]=BSON_DATA_REGEXP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(value.pattern.match(regexp)!=null){throw new BSONError("pattern "+value.pattern+" must not contain null bytes")}index=index+ByteUtils.encodeUTF8Into(buffer2,value.pattern,index);buffer2[index++]=0;const sortedOptions=value.options.split("").sort().join("");index=index+ByteUtils.encodeUTF8Into(buffer2,sortedOptions,index);buffer2[index++]=0;return index}function serializeMinMax(buffer2,key,value,index){if(value===null){buffer2[index++]=BSON_DATA_NULL}else if(value._bsontype==="MinKey"){buffer2[index++]=BSON_DATA_MIN_KEY}else{buffer2[index++]=BSON_DATA_MAX_KEY}const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;return index}function serializeObjectId(buffer2,key,value,index){buffer2[index++]=BSON_DATA_OID;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;if(isUint8Array(value.id)){buffer2.set(value.id.subarray(0,12),index)}else{throw new BSONError("object ["+JSON.stringify(value)+"] is not a valid ObjectId")}return index+12}function serializeBuffer(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=value.length;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=BSON_BINARY_SUBTYPE_DEFAULT;buffer2.set(value,index);index=index+size;return index}function serializeObject(buffer2,key,value,index,checkKeys,depth,serializeFunctions,ignoreUndefined,path){if(path.has(value)){throw new BSONError("Cannot convert circular structure to BSON")}path.add(value);buffer2[index++]=Array.isArray(value)?BSON_DATA_ARRAY:BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const endIndex=serializeInto(buffer2,value,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);path.delete(value);return endIndex}function serializeDecimal128(buffer2,key,value,index){buffer2[index++]=BSON_DATA_DECIMAL128;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2.set(value.bytes.subarray(0,16),index);return index+16}function serializeLong(buffer2,key,value,index){buffer2[index++]=value._bsontype==="Long"?BSON_DATA_LONG:BSON_DATA_TIMESTAMP;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const lowBits=value.getLowBits();const highBits=value.getHighBits();buffer2[index++]=lowBits&255;buffer2[index++]=lowBits>>8&255;buffer2[index++]=lowBits>>16&255;buffer2[index++]=lowBits>>24&255;buffer2[index++]=highBits&255;buffer2[index++]=highBits>>8&255;buffer2[index++]=highBits>>16&255;buffer2[index++]=highBits>>24&255;return index}function serializeInt32(buffer2,key,value,index){value=value.valueOf();buffer2[index++]=BSON_DATA_INT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;buffer2[index++]=value&255;buffer2[index++]=value>>8&255;buffer2[index++]=value>>16&255;buffer2[index++]=value>>24&255;return index}function serializeDouble(buffer2,key,value,index){buffer2[index++]=BSON_DATA_NUMBER;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;NUMBER_SPACE.setFloat64(0,value.value,true);buffer2.set(EIGHT_BYTE_VIEW_ON_NUMBER,index);index=index+8;return index}function serializeFunction(buffer2,key,value,index){buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeCode(buffer2,key,value,index,checkKeys=false,depth=0,serializeFunctions=false,ignoreUndefined=true,path){if(value.scope&&typeof value.scope==="object"){buffer2[index++]=BSON_DATA_CODE_W_SCOPE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;const functionString=value.code;index=index+4;const codeSize=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=codeSize&255;buffer2[index+1]=codeSize>>8&255;buffer2[index+2]=codeSize>>16&255;buffer2[index+3]=codeSize>>24&255;buffer2[index+4+codeSize-1]=0;index=index+codeSize+4;const endIndex=serializeInto(buffer2,value.scope,checkKeys,index,depth+1,serializeFunctions,ignoreUndefined,path);index=endIndex-1;const totalSize=endIndex-startIndex;buffer2[startIndex++]=totalSize&255;buffer2[startIndex++]=totalSize>>8&255;buffer2[startIndex++]=totalSize>>16&255;buffer2[startIndex++]=totalSize>>24&255;buffer2[index++]=0}else{buffer2[index++]=BSON_DATA_CODE;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const functionString=value.code.toString();const size=ByteUtils.encodeUTF8Into(buffer2,functionString,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0}return index}function serializeBinary(buffer2,key,value,index){buffer2[index++]=BSON_DATA_BINARY;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const data=value.buffer;let size=value.position;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY)size=size+4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255;buffer2[index++]=value.sub_type;if(value.sub_type===Binary.SUBTYPE_BYTE_ARRAY){size=size-4;buffer2[index++]=size&255;buffer2[index++]=size>>8&255;buffer2[index++]=size>>16&255;buffer2[index++]=size>>24&255}buffer2.set(data,index);index=index+value.position;return index}function serializeSymbol(buffer2,key,value,index){buffer2[index++]=BSON_DATA_SYMBOL;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;const size=ByteUtils.encodeUTF8Into(buffer2,value.value,index+4)+1;buffer2[index]=size&255;buffer2[index+1]=size>>8&255;buffer2[index+2]=size>>16&255;buffer2[index+3]=size>>24&255;index=index+4+size-1;buffer2[index++]=0;return index}function serializeDBRef(buffer2,key,value,index,depth,serializeFunctions,path){buffer2[index++]=BSON_DATA_OBJECT;const numberOfWrittenBytes=ByteUtils.encodeUTF8Into(buffer2,key,index);index=index+numberOfWrittenBytes;buffer2[index++]=0;let startIndex=index;let output={$ref:value.collection||value.namespace,$id:value.oid};if(value.db!=null){output.$db=value.db}output=Object.assign(output,value.fields);const endIndex=serializeInto(buffer2,output,false,index,depth+1,serializeFunctions,true,path);const size=endIndex-startIndex;buffer2[startIndex++]=size&255;buffer2[startIndex++]=size>>8&255;buffer2[startIndex++]=size>>16&255;buffer2[startIndex++]=size>>24&255;return endIndex}function serializeInto(buffer2,object,checkKeys,startingIndex,depth,serializeFunctions,ignoreUndefined,path){if(path==null){if(object==null){buffer2[0]=5;buffer2[1]=0;buffer2[2]=0;buffer2[3]=0;buffer2[4]=0;return 5}if(Array.isArray(object)){throw new BSONError("serialize does not support an array as the root input")}if(typeof object!=="object"){throw new BSONError("serialize does not support non-object as the root input")}else if("_bsontype"in object&&typeof object._bsontype==="string"){throw new BSONError(`BSON types cannot be serialized as a document`)}else if(isDate(object)||isRegExp(object)||isUint8Array(object)||isAnyArrayBuffer(object)){throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`)}path=new Set}path.add(object);let index=startingIndex+4;if(Array.isArray(object)){for(let i=0;i>8&255;buffer2[startingIndex++]=size>>16&255;buffer2[startingIndex++]=size>>24&255;return index}function isBSONType(value){return value!=null&&typeof value==="object"&&"_bsontype"in value&&typeof value._bsontype==="string"}var keysToCodecs={$oid:ObjectId2,$binary:Binary,$uuid:Binary,$symbol:BSONSymbol,$numberInt:Int32,$numberDecimal:Decimal128,$numberDouble:Double,$numberLong:Long,$minKey:MinKey,$maxKey:MaxKey,$regex:BSONRegExp,$regularExpression:BSONRegExp,$timestamp:Timestamp};function deserializeValue(value,options={}){if(typeof value==="number"){const in32BitRange=value<=BSON_INT32_MAX&&value>=BSON_INT32_MIN;const in64BitRange=value<=BSON_INT64_MAX&&value>=BSON_INT64_MIN;if(options.relaxed||options.legacy){return value}if(Number.isInteger(value)&&!Object.is(value,-0)){if(in32BitRange){return new Int32(value)}if(in64BitRange){if(options.useBigInt64){return BigInt(value)}return Long.fromNumber(value)}}return new Double(value)}if(value==null||typeof value!=="object")return value;if(value.$undefined)return null;const keys=Object.keys(value).filter(k=>k.startsWith("$")&&value[k]!=null);for(let i=0;ik.startsWith("$"));let valid=true;dollarKeys.forEach(k=>{if(["$ref","$id","$db"].indexOf(k)===-1)valid=false});if(valid)return DBRef.fromExtendedJSON(v)}return value}function serializeArray(array,options){return array.map((v,index)=>{options.seenObjects.push({propertyName:`index ${index}`,obj:null});try{return serializeValue(v,options)}finally{options.seenObjects.pop()}})}function getISOString(date){const isoStr=date.toISOString();return date.getUTCMilliseconds()!==0?isoStr:isoStr.slice(0,-5)+"Z"}function serializeValue(value,options){if(value instanceof Map||isMap(value)){const obj=Object.create(null);for(const[k,v]of value){if(typeof k!=="string"){throw new BSONError("Can only serialize maps with string keys")}obj[k]=v}return serializeValue(obj,options)}if((typeof value==="object"||typeof value==="function")&&value!==null){const index=options.seenObjects.findIndex(entry=>entry.obj===value);if(index!==-1){const props=options.seenObjects.map(entry=>entry.propertyName);const leadingPart=props.slice(0,index).map(prop=>`${prop} -> `).join("");const alreadySeen=props[index];const circularPart=" -> "+props.slice(index+1,props.length-1).map(prop=>`${prop} -> `).join("");const current=props[props.length-1];const leadingSpace=" ".repeat(leadingPart.length+alreadySeen.length/2);const dashes="-".repeat(circularPart.length+(alreadySeen.length+current.length)/2-1);throw new BSONError(`Converting circular structure to EJSON: - ${leadingPart}${alreadySeen}${circularPart}${current} - ${leadingSpace}\\${dashes}/`)}options.seenObjects[options.seenObjects.length-1].obj=value}if(Array.isArray(value))return serializeArray(value,options);if(value===void 0)return null;if(value instanceof Date||isDate(value)){const dateNum=value.getTime(),inRange=dateNum>-1&&dateNum<2534023188e5;if(options.legacy){return options.relaxed&&inRange?{$date:value.getTime()}:{$date:getISOString(value)}}return options.relaxed&&inRange?{$date:getISOString(value)}:{$date:{$numberLong:value.getTime().toString()}}}if(typeof value==="number"&&(!options.relaxed||!isFinite(value))){if(Number.isInteger(value)&&!Object.is(value,-0)){if(value>=BSON_INT32_MIN&&value<=BSON_INT32_MAX){return{$numberInt:value.toString()}}if(value>=BSON_INT64_MIN&&value<=BSON_INT64_MAX){return{$numberLong:value.toString()}}}return{$numberDouble:Object.is(value,-0)?"-0.0":value.toString()}}if(typeof value==="bigint"){if(!options.relaxed){return{$numberLong:BigInt.asIntN(64,value).toString()}}return Number(BigInt.asIntN(64,value))}if(value instanceof RegExp||isRegExp(value)){let flags=value.flags;if(flags===void 0){const match=value.toString().match(/[gimuy]*$/);if(match){flags=match[0]}}const rx=new BSONRegExp(value.source,flags);return rx.toExtendedJSON(options)}if(value!=null&&typeof value==="object")return serializeDocument(value,options);return value}var BSON_TYPE_MAPPINGS={Binary:o=>new Binary(o.value(),o.sub_type),Code:o=>new Code(o.code,o.scope),DBRef:o=>new DBRef(o.collection||o.namespace,o.oid,o.db,o.fields),Decimal128:o=>new Decimal128(o.bytes),Double:o=>new Double(o.value),Int32:o=>new Int32(o.value),Long:o=>Long.fromBits(o.low!=null?o.low:o.low_,o.low!=null?o.high:o.high_,o.low!=null?o.unsigned:o.unsigned_),MaxKey:()=>new MaxKey,MinKey:()=>new MinKey,ObjectId:o=>new ObjectId2(o),BSONRegExp:o=>new BSONRegExp(o.pattern,o.options),BSONSymbol:o=>new BSONSymbol(o.value),Timestamp:o=>Timestamp.fromBits(o.low,o.high)};function serializeDocument(doc,options){if(doc==null||typeof doc!=="object")throw new BSONError("not an object instance");const bsontype=doc._bsontype;if(typeof bsontype==="undefined"){const _doc={};for(const name of Object.keys(doc)){options.seenObjects.push({propertyName:name,obj:null});try{const value=serializeValue(doc[name],options);if(name==="__proto__"){Object.defineProperty(_doc,name,{value,writable:true,enumerable:true,configurable:true})}else{_doc[name]=value}}finally{options.seenObjects.pop()}}return _doc}else if(doc!=null&&typeof doc==="object"&&typeof doc._bsontype==="string"&&doc[Symbol.for("@@mdb.bson.version")]!==BSON_MAJOR_VERSION){throw new BSONVersionError}else if(isBSONType(doc)){let outDoc=doc;if(typeof outDoc.toExtendedJSON!=="function"){const mapper=BSON_TYPE_MAPPINGS[doc._bsontype];if(!mapper){throw new BSONError("Unrecognized or invalid _bsontype: "+doc._bsontype)}outDoc=mapper(outDoc)}if(bsontype==="Code"&&outDoc.scope){outDoc=new Code(outDoc.code,serializeValue(outDoc.scope,options))}else if(bsontype==="DBRef"&&outDoc.oid){outDoc=new DBRef(serializeValue(outDoc.collection,options),serializeValue(outDoc.oid,options),serializeValue(outDoc.db,options),serializeValue(outDoc.fields,options))}return outDoc.toExtendedJSON(options)}else{throw new BSONError("_bsontype must be a string, but was: "+typeof bsontype)}}function parse(text,options){const ejsonOptions={useBigInt64:options?.useBigInt64??false,relaxed:options?.relaxed??true,legacy:options?.legacy??false};return JSON.parse(text,(key,value)=>{if(key.indexOf("\0")!==-1){throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`)}return deserializeValue(value,ejsonOptions)})}function stringify(value,replacer,space,options){if(space!=null&&typeof space==="object"){options=space;space=0}if(replacer!=null&&typeof replacer==="object"&&!Array.isArray(replacer)){options=replacer;replacer=void 0;space=0}const serializeOptions=Object.assign({relaxed:true,legacy:false},options,{seenObjects:[{propertyName:"(root)",obj:null}]});const doc=serializeValue(value,serializeOptions);return JSON.stringify(doc,replacer,space)}function EJSONserialize(value,options){options=options||{};return JSON.parse(stringify(value,options))}function EJSONdeserialize(ejson,options){options=options||{};return parse(JSON.stringify(ejson),options)}var EJSON=Object.create(null);EJSON.parse=parse;EJSON.stringify=stringify;EJSON.serialize=EJSONserialize;EJSON.deserialize=EJSONdeserialize;Object.freeze(EJSON);var MAXSIZE=1024*1024*17;var buffer=ByteUtils.allocate(MAXSIZE);function setInternalBufferSize(size){if(buffer.lengthStructBackend,StructFrontend:()=>StructFrontend,Systems:()=>Systems,WebglLinePlotInfo:()=>void 0,WebglLinePlotProps:()=>void 0,WebglLinePlotUtil:()=>void 0,WebglLineProps:()=>void 0,algorithms:()=>algorithms,defaultSpecifiers:()=>defaultSpecifiers,genTimeSpecifiers:()=>genTimeSpecifiers,genTimestampFromString:()=>genTimestampFromString,getStringId:()=>getStringId,pseudoObjectId:()=>pseudoObjectId,randomId:()=>randomId,setSignalControls:()=>setSignalControls,toObjectId:()=>toObjectId,webglPlotRoutes:()=>webglPlotRoutes});module.exports=__toCommonJS(index_services_exports);var DataStructures_exports={};__export(DataStructures_exports,{AuthorizationStruct:()=>AuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}onCollectionSet=(type,collection)=>{};runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b){if(a.timestamp&&b.timestamp)return a.timestamp-b.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_,__,___=this.data){}onSorted(_=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var defaultSpecifiers=["now","minute","5 minutes","30 minutes","hour","6 hours","12 hours","day","3 days","week","2 weeks","month","6 months","year","5 years","decade"];function genTimeSpecifiers(specifiers=defaultSpecifiers){let result=["now"];specifiers.forEach(s=>{if(s!=="now")result.push(`last ${s}`);else result.push(s)});return result}function genTimestampFromString(specifier){const now=new Date;if(specifier==="now"){}else if(specifier==="last minute"){now.setMinutes(now.getMinutes()-1)}else if(specifier==="last hour"){now.setHours(now.getHours()-1)}else if(specifier==="last day"){now.setDate(now.getDate()-1)}else if(specifier==="last week"){now.setDate(now.getDate()-7)}else if(specifier==="last month"){now.setMonth(now.getMonth()-1)}else if(specifier==="last year"){now.setFullYear(now.getFullYear()-1)}else if(specifier==="last decade"){now.setFullYear(now.getFullYear()-1*10)}else if(specifier==="last century"){now.setFullYear(now.getFullYear()-1*100)}else if(specifier==="last millennium"){now.setFullYear(now.getFullYear()-1*1e3)}else if(specifier==="last microsecond"){now.setMilliseconds(now.getMilliseconds()-1)}else if(specifier==="last nanosecond"){now.setMilliseconds(now.getMilliseconds()-1*.001)}else if(specifier.startsWith("last")){const[,count,unit]=specifier.match(/last (\d+) (\w+)/)||[];if(count&&unit){const num=parseInt(count,10);if(unit.includes("minute")){now.setMinutes(now.getMinutes()-num)}else if(unit.includes("hour")){now.setHours(now.getHours()-num)}else if(unit.includes("day")){now.setDate(now.getDate()-num)}else if(unit.includes("week")){now.setDate(now.getDate()-num*7)}else if(unit.includes("month")){now.setMonth(now.getMonth()-num)}else if(unit.includes("year")){now.setFullYear(now.getFullYear()-num)}else if(unit.includes("decade")){now.setFullYear(now.getFullYear()-num*10)}else if(unit.includes("century")){now.setFullYear(now.getFullYear()-num*100)}else if(unit.includes("millennium")){now.setFullYear(now.getFullYear()-num*1e3)}else if(unit.includes("microsecond")){now.setMilliseconds(now.getMilliseconds()-num)}else if(unit.includes("nanosecond")){now.setMilliseconds(now.getMilliseconds()-num*.001)}}}return now.getTime()}var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value)=>{this.data[key]=value;this.triggerEvent(key,value)};triggerEvent=(key,value)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub=>{return this.unsubscribeEvent(statesubKey,sub)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value=>{refObject[refKey]=value},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(sub===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeEvent(key,sub)};sub=this.subscribeEvent(key,changed);return sub};getEvent=(key,sub)=>{if(typeof sub!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value,receiver)}return Reflect.set(target,prop,value,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub}};__unsubscribe=(sub,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str2=this.__node.unique+"."+k;let inpstr=`${str2}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str2]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str2,res)}).catch(console.error)}else this.__node.state.triggerEvent(str2,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str2])this.__node.state.triggerEvent(str2,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value=>{obj[k]=value},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub;if(nd instanceof GraphNode){const doSub=()=>{sub=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)nd.__unsubscribe(sub,key,subInput);sub=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub!==void 0)node.__unsubscribe(sub,key,subInput);sub=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub};unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{name="structs";currentUser;tablet=new DataTablet;collections=this.tablet.collections;id=randomId();useAccessTokens=false;useRefreshTokens=false;constructor(options,user){super(options);this.load(this);if(options.useAccessTokens)this.useAccessTokens=options.useAccessTokens;if(options.useRefreshTokens)this.useRefreshTokens=options.useRefreshTokens;if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}getToken(user){if(this.useAccessTokens)return user.accessToken;else if(this.useRefreshTokens)return user.refreshToken}setupUser=async(userinfo,callback=currentUser=>{})=>{if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u;let newu=false;if(!user||!user._id){u=this.userStruct(userinfo,false);newu=true;let wasSet=await this.setUser(u);let structs=this.getLocalData(void 0,{"ownerId":u._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u)}else{u=user;let toUpdate={_id:userinfo._id,ownerId:userinfo._id};let struct=this.userStruct(userinfo,false);for(const key in struct){if(userinfo[key]&&user[key]!==userinfo[key]){toUpdate[key]=userinfo[key];user[key]=userinfo[key]}else if(struct[key]&&!user[key]){toUpdate[key]=struct[key];user[key]=struct[key]}}if(Object.keys(toUpdate).length>2)await this.setUser(toUpdate);if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u)}else{let data=await this.getAllUserData(u._id,void 0,[genTimestampFromString("last day"),Date.now()]);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u)}if(u){if(this.currentUser)Object.assign(this.currentUser,u);else this.currentUser=u;callback(this.currentUser);return this.currentUser}else{callback(u);return u}};baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}this.onResult(data)};structNotification=()=>{this.checkForNotifications()};structDeleted=struct=>{this.deleteLocalData([struct])};onResult=data=>{};randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}addStruct=async(structType="struct",props={},parentUser,parentStruct,updateServer=true)=>{let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct};getUser=async(info="",basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info,basicInfo,this.getToken(this.currentUser)]});callback(res);return res}};queryUsers=async(info,skip,limit,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"queryUsers",args:[this.currentUser._id,info,skip,limit,void 0,this.getToken(this.currentUser)]});callback(res);return res}};getUsers=async(ids=[],basicInfo,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids,basicInfo]});callback(res);return res}};getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};getAllUserData=async(ownerId,excluded=[],timeRange,callback=this.baseServerCallback)=>{if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[this.currentUser._id,ownerId,excluded,timeRange,this.getToken(this.currentUser)]});callback(res);return res}};query=async(collection,mongoQuery={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!mongoQuery)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,mongoQuery,findOne,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByTimeRange(collection,timeRange,ownerId,limit=0,skip=0,key){let query={};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1])}let range={$gt:timeRange[0],$lt:timeRange[1]};if(key)query[key]=range;else query.timestamp=range;return this.getData(collection,ownerId,query,limit,skip)}getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct?.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id,this.getToken(this.currentUser)];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};setUser=async(userStruct,callback=this.baseServerCallback)=>{if(userStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};updateServerData=this.setData;deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteUser=async(userId=this.currentUser._id,deleteData,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId,deleteData,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setGroup=async(groupStruct,callback=this.baseServerCallback)=>{if(groupStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};setAuthorization=async(authorizationStruct,callback=this.baseServerCallback)=>{if(authorizationStruct&&this.currentUser?.request){let res=await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct),this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=await this.currentUser.request({route:"deleteAuthorization",args:[this.currentUser._id,authorizationId,this.getToken(this.currentUser)]});if(typeof callback==="function")callback(res);return res}};checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent){toUpdate=[parent];allReplies.forEach(r=>{let idx=parent.replies?.indexOf(r._id);if(idx>-1)parent.replies.splice(idx,1);let idx2=parent.comments?.indexOf(r._id);if(idx2>-1)parent.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent?._id){let idx=replyTo.replies?.indexOf(parent._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u=authorizationStruct.authorizerId;if(u){return new Promise(async resolve=>{this.getUser(u,true,async data=>{let res;if(!collection)res=await this.getAllUserData(u,["notification"],void 0,callback);else res=await this.getData(collection,u,searchDict,limit,skip,callback);resolve(res);callback(res)})})}else return void 0};getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u=o.authorizerId;if(u){let data;let user=await this.getUser(u,true,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u,["notification"],void 0,callback);else data=await this.getData(collection,u,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return{};let result={};let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result[a.authorizedId]=true});return result};getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b)=>a*(typeof b==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(void 0,{_id:struct});if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop]===""||copy[prop].constructor.name==="Map"||copy[prop].constructor.name==="Set"||typeof copy[prop]==="function")delete copy[prop];else if(Array.isArray(copy[prop])&©[prop].length===0)delete copy[prop];else if(typeof copy[prop]==="object"&&Object.keys(copy[prop]).length===0)delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(!user.name&&user.firstName)user.name=user.firstName+" "+user.lastName;else if(user.name&&!user.firstName){let split=user.name.split(" ");user.firstName=split[0];user.lastName=split[split.length-1]}if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e15);user._id=user.id;user.ownerId=user.id;let dummy=DataStructures_exports.ProfileStruct();for(const prop in props){if(Object.keys(dummy).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};addEvent=async(parentUser,author="",event="",notes="",startTime=void 0,endTime=void 0,grade=void 0,value=void 0,units=void 0,location=void 0,attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.value=value;newEvent.units=units;newEvent.users=users;newEvent.location=location;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};addChatroom=async(parentUser,authorId="",message="",attachments=void 0,users=void 0,updateServer=true)=>{if(!parentUser)return void 0;if(users&&Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=void 0,updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res}};var import_bson=__toESM(require_bson());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectId=str2=>{return typeof str2==="string"&&str2.length===24?new import_bson.ObjectId(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{name="structs";debug=false;db;users={};collections={};mode="local";useAuths=true;useAccessTokens=false;useRefreshTokens=false;accessTokens=new Map;refreshTokens=new Map;constructor(options,dboptions){super(options);this.load(this);if(dboptions){this.initDB(dboptions)}}initDB=dboptions=>{this.db=dboptions.db;if(dboptions?.users)this.users=dboptions.users;if(dboptions.mode)this.mode=dboptions.mode;if(dboptions?.collections)this.collections=dboptions.collections;if(dboptions.debug)this.debug=dboptions.debug;if(dboptions.useAccessTokens)this.useAccessTokens=dboptions.useAccessTokens;if(dboptions.useRefreshTokens)this.useRefreshTokens=dboptions.useRefreshTokens;if("useAuths"in dboptions)this.useAuths=dboptions.useAuths;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})};query=async(requestingUserId,collection,queryObj,findOne,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip,token)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token);if(passed)return res}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}));return data}};getUser=async(requestingUserId,lookupId,basicInfo,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId,void 0,basicInfo,token)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:void 0};else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};setUser=async(requestingUserId,struct,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(struct.accessToken){this.accessTokens.set(requestingUserId,token)}if(struct.refreshToken){this.refreshTokens.set(requestingUserId,struct.refreshToken)}delete struct.accessToken;delete struct.refreshToken;delete user.accessToken;delete user.refreshToken;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct,token)}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};getUsersByIds=async(requestingUserId,userIds,basicInfo)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds,basicInfo)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct){if(basicInfo)data.push({_id:struct._id,username:struct.username,firstName:struct.firstName,lastName:struct.lastName,fullName:struct.fullName,pictureUrl:struct.pictureUrl});else data.push(struct)}}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};deleteUser=async(requestingUserId,userId,deleteData,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId,deleteData,token)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};setData=async(requestingUserId,structs,notify,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify,token)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};getData=async(requestingUserId,collection,ownerId,dict,limit,skip,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};getDataByIds=async(requestingUserId,structIds,ownerId,collection,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection,token)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};getAllData=async(requestingUserId,ownerId,excludedCollections,timeRange,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections,timeRange,token)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};deleteData=async(requestingUserId,structIds,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds,token)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};deleteGroup=async(requestingUserId,groupId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId,token)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};getAuthorizations=async(requestingUserId,ownerId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId,token)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};deleteAuthorization=async(requestingUserId,authId,token)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId,token)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};getToken=user=>{return this.useAccessTokens?this.accessTokens.get(user._id):this.useRefreshTokens?this.refreshTokens.get(user._id):void 0};notificationStruct=(parentStruct={})=>{let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct};checkToNotify=async(user,structs=[],mode=this.mode)=>{if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(struct.ownerId&&user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+struct.ownerId;newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id)+"_"+usr;newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d=>auths.push(d))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id)+"_"+auth.authorizedId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications,true,this.getToken(user))}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid]?.sendAll({route:"structNotification",args:true})}return true}else return false};queryMongo=async(user,collection,queryObj={},findOne=false,skip=0,token)=>{if(!collection&&!queryObj)return void 0;else if(findOne){let res=await this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res,"READ",token)}if(passed)return res;else return void 0}else{let res=this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];let arr=await res.toArray();if(arr.length>0){let passed=!this.useAuths;let checkedAuth="";for(const s of arr){if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)structs.push(s)}}return structs}};setMongoData=async(user,structs=[],notify=true,token)=>{let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]={};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType?struct.structType:"data").updateOne({_id:toObjectId(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType?struct.structType:"data").insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectId(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectId(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false};setMongoUser=async(user,struct,token)=>{if(struct._id){const _id=toObjectId(struct._id);let usersearch={_id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));copy._id=_id;if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false};setGroup=async(user,struct,mode=this.mode,token)=>{if(struct?._id){let uid=getStringId(user._id);let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(uid)<0))return false;if(uid!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token);if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u=>{allusers.push({email:u},{id:u},{username:u})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});let arr=cursor.toArray();if(arr.length>0){arr.forEach(user2=>{users[uid]=user2;ids[uid]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u=users[id];if(struct.admins[getStringId(u._id)]||struct.admins[u.email]||struct.admins[u.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u._id)])admins[getStringId(u._id)]=true}if(struct.peers[getStringId(u._id)]||struct.peers[u.email]||struct.peers[u.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u._id)])peers[getStringId(u._id)]=true}if(struct.clients[getStringId(u._id)]||struct.clients[u.email]||struct.clients[u.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u._id)])clients[getStringId(u._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType?struct.structType:"data").insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType?struct.structType:"data").findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectId(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false};getMongoUser=(user,info="",requireAuth=true,basicInfo=false,token)=>{return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectId(info)})}catch(e){console.log("error creating ObjectId with ",info)}let u=await this.collections.profile.instance.findOne({$or:query});if(!u||u==null)resolve(void 0);else{u._id=getStringId(u._id);if(!u.ownerId)u.ownerId=u._id;if(basicInfo){if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}let stripped={username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName,pictureUrl:u.pictureUrl,_id:u._id};u=stripped;resolve({user:u})}else if(requireAuth){if(getStringId(user._id)!==u._id||getStringId(user._id)===u._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u,"READ",token);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u._id});let aarr=await auths.toArray();if(auths.toArray().length>0){aarr.forEach(d=>authorizations.push(d))}let gs=this.collections.group.instance.find({users:{$all:[u._id]}});let arr=await gs.toArray();let groups=[];if(arr.length>0){arr.forEach(d=>groups.push(d))}resolve({user:u,authorizations,groups})}else{if(this.useAccessTokens||this.useRefreshTokens){if(this.getToken(user)!==token)resolve(void 0)}resolve({user:u})}}})};queryUsers=(user,info="",limit=0,skip=0,requireAuth=false,token)=>{if(typeof user==="string")user=this.users[user];if(!user)return;return new Promise(async resolve=>{let q={$regex:`^${info}`,$options:"i"};const query=[{email:q},{username:q},{firstName:q},{lastName:q},{name:q}];let arr;if(this.mode.includes("mongo")){let users=this.collections.profile.instance.find({$or:query},{projection:shallowqueryDummy}).skip(skip);if(limit>0)users.limit(limit);await users;arr=await users.toArray()}else{arr=[];for(let i=0;i{arr.push({firstName:u.firstName,lastName:u.lastName,fullName:u.fullName,username:u.username,pictureUrl:u.pictureUrl})})}else if(dat)arr.push({firstName:dat.firstName,lastName:dat.lastName,fullName:dat.fullName,username:dat.username,pictureUrl:dat.pictureUrl})}}if(requireAuth){let result=[];let strid=getStringId(user._id);for(let i=0;i{let usrs=[];userIds.forEach(u=>{try{usrs.push({_id:toObjectId(u)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});let arr=await users.toArray();if(arr.length>0){arr.forEach(u=>{if(basicInfo){found.push({username:u.username,firstName:u.firstName,lastName:u.lastName,fullName:u.fullName,pictureUrl:u.pictureUrl,_id:u._id})}else found.push(u)})}}return found};getMongoUsersByRole=async(user,role)=>{let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];let arr=await users.toArray();if(arr.length>0){arr.forEach(u=>{found.push(u)})}return found};getMongoDataByIds=async(user,structIds,ownerId,collection,token)=>{let uid=getStringId(user._id);if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectId(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});let arr=await cursor.toArray();if(arr.length>0){let passed=true;let checkedAuth="";for(let i=0;i0){let passed=true;let checkedAuth="";arr.forEach(async s=>{if(!s?.ownerId)passed=true;else if((uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s,"READ",token);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}};getMongoData=async(user,collection,ownerId,dict={},limit=0,skip=0,token)=>{if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectId(dict._id);let uid=getStringId(user._id);let structs=[];let passed=true;let checkedAuth="";let cursor;if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip)}else if(collection&&Object.keys(dict).length>0){if(ownerId)dict.ownerId=ownerId;cursor=await this.db.collection(collection).find(dict).sort({$natural:-1}).skip(skip)}if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{cursor=await this.db.collection(name).find(dict).sort({$natural:-1}).skip(skip);;if(cursor){if(limit>0)cursor.limit(limit);let arr=await cursor.toArray();if(arr.length>0){for(let i=0;i{let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let query={ownerId};if(timeRange){if(typeof timeRange[0]==="string")timeRange[0]=genTimestampFromString(timeRange[0]);if(typeof timeRange[1]==="string")timeRange[1]=genTimestampFromString(timeRange[1]);query.timestamp={$gt:timeRange[0],$lt:timeRange[1]}}let cursor=this.db.collection(name).find(query);let arr=await cursor.toArray();let count=arr.length;for(let k=0;k{let structs=[];if(structs.length>0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectId(ref._id)});if(struct){let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"READ",token);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs};getMongoAuthorizations=async(user,ownerId=getStringId(user._id),authId="",token)=>{let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectId(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0],"READ",token);if(!passed)return void 0}return auths};getMongoGroups=async(user,userId=getStringId(user._id),groupId="")=>{let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});let arr=await cursor.toArray();if(arr.length>0){arr.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectId(groupId),users:{$all:[userId]}}))}catch{}}return groups};deleteMongoData=async(user,structRefs=[],token)=>{let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectId(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=notifications.toArray().length;for(let i=0;i{let passed=true;if(!struct?.ownerId||struct.ownerId===user._id)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE",token)}if(passed){await this.db.collection(struct.structType?struct.structType:"data").deleteOne({_id:toObjectId(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(struct._id),structType:struct.structType}})}}}));return true};deleteMongoUser=async(user,userId,deleteData,token)=>{if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u,"WRITE",token);if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(deleteData){for(const key in this.collections){this.collections[key].instance.deleteMany({ownerId:userId});this.collections[key].instance.updateMany({users:{[userId]:true}},{$unset:{[`users.${userId}`]:""}})}}if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId]?.sendAll({route:"structDeleted",args:{_id:userId,structType:"profile"}});return true};deleteMongoGroup=async(user,groupId,token)=>{let s=await this.collections.group.instance.findOne({_id:toObjectId(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u=>{this.users[u]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}})})}await this.collections.group.instance.deleteOne({_id:toObjectId(groupId)});return true}else return false};deleteMongoAuthorization=async(user,authId,token)=>{let s=await this.collections.authorization.instance.findOne({_id:toObjectId(authId)});let uid=getStringId(user._id);if(s){if(uid!==s.ownerId||uid===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE",token);if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectId(s.associatedAuthId)});if(s.authorizerId!==uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}});else if(s.authorizedId!==uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s.associatedAuthId),structType:s.structType}})}await this.collections.authorization.instance.deleteOne({_id:toObjectId(authId)});if(s.authorizerId===uid)this.users[s.authorizerId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});else if(s.authorizedId===uid)this.users[s.authorizedId]?.sendAll({route:"structDeleted",args:{_id:getStringId(s._id),structType:s.structType}});return true}else return false};setAuthorization=async(user,authStruct,token)=>{let u1,u2;let mmode=this.mode.includes("mongo");if(mmode){u1=(await this.getMongoUser(user,authStruct.authorizedId,false)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,false)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})?.[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})?.[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.name)authStruct.authorizedName=u1.name;else if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u1.name)authStruct.authorizedName=u1.name;else if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE",token);if(!passed)return false}let auths=[];if(mmode){let s=await this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});let arr=await s.toArray();if(arr.length>0){arr.forEach(d=>auths.push(d))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d=>{if(d.authorizerId===authStruct.authorizerId)auths.push(d)})}}let otherAuthset;if(Array.isArray(auths)){for(let i=0;i{if(typeof user==="string"){if(this.users[user])user=this.users[user];else user={_id:user}}if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}return true}}if(this.useAccessTokens){if(!this.accessTokens.get(user._id)||this.accessTokens.get(user._id)!==token){return false}}else if(this.useRefreshTokens){if(!this.refreshTokens.get(user._id)||this.refreshTokens.get(user._id)!==token){return false}}let auth1,auth2;if(this.mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});if(!auth1)return false;auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(struct.ownerId)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(struct.ownerId)}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed};wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};overwriteLocalData=structs=>{if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}};setLocalData=structs=>{let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)};getLocalData=(collection,query)=>{let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result};deleteLocalData=struct=>{if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var shallowqueryDummy=DataStructures_exports.ProfileStruct();for(const key in shallowqueryDummy){if(key==="username"||key==="lastName"||key==="firstName"||key==="name"||key==="_id"||key==="pictureUrl")shallowqueryDummy[key]=1;else delete shallowqueryDummy[key]}var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u=(dot11*dot02-dot01*dot12)*_denom;let v=(dot00*dot12-dot01*dot02)*_denom;if(u>=0&&v>=0&&u+v<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v=>{let magnitude=0;for(const key in v){magnitude+=v[key]*v[key]}return Math.sqrt(magnitude)},normalize:v=>{let magnitude=Systems.collision.magnitude(v);let _mag=magnitude?1/magnitude:0;let vn={};for(const key in v){vn[key]=v[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new(void 0);return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new(void 0);return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` - - - - - - - - - - - - - - `;if(!line.viewing)viewingall=false;if(!filterSettings[prop]?.useScaling)scalingall=false;if(!filterSettings[prop]?.useNotch50)n50all=false;if(!filterSettings[prop]?.useNotch60)n60all=false;if(!filterSettings[prop]?.useDCBlock)dcall=false;if(!filterSettings[prop]?.useLowpass)lpall=false;if(!filterSettings[prop]?.useBandpass)bpall=false}let head=` - - - - - - - - - - - - - - - `;controls.innerHTML=head+body;let viewall=document.getElementById(plotId+"viewing");let usescalar=document.getElementById(plotId+"useScaling");let usen50=document.getElementById(plotId+"useNotch50");let usen60=document.getElementById(plotId+"useNotch60");let usedcb=document.getElementById(plotId+"useDCBlock");let uselp=document.getElementById(plotId+"useLowpass");let usebp=document.getElementById(plotId+"useBandpass");let headeronchange=(checked,idsuffix)=>{for(const prop in chartSettings.lines){let elm=document.getElementById(plotId+prop+idsuffix);if(elm?.checked!==checked)elm.click()}};viewall.onchange=ev2=>{headeronchange(ev2.target.checked,"viewing")};usescalar.onchange=ev2=>{headeronchange(ev2.target.checked,"useScaling")};usen50.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch50")};usen60.onchange=ev2=>{headeronchange(ev2.target.checked,"useNotch60")};usedcb.onchange=ev2=>{headeronchange(ev2.target.checked,"useDCBlock")};uselp.onchange=ev2=>{headeronchange(ev2.target.checked,"useLowpass")};usebp.onchange=ev2=>{headeronchange(ev2.target.checked,"useBandpass")};for(const prop in chartSettings.lines){let viewing=document.getElementById(plotId+prop+"viewing");let sps=document.getElementById(plotId+prop+"sps");let nSec=document.getElementById(plotId+prop+"nSec");let useScaling=document.getElementById(plotId+prop+"useScaling");let scalar=document.getElementById(plotId+prop+"scalar");let units=document.getElementById(plotId+prop+"units");let ymin=document.getElementById(plotId+prop+"ymin");let ymax=document.getElementById(plotId+prop+"ymax");let useNotch50=document.getElementById(plotId+prop+"useNotch50");let useNotch60=document.getElementById(plotId+prop+"useNotch60");let useDCBlock=document.getElementById(plotId+prop+"useDCBlock");let useLowpass=document.getElementById(plotId+prop+"useLowpass");let lowpassHz=document.getElementById(plotId+prop+"lowpassHz");let useBandpass=document.getElementById(plotId+prop+"useBandpass");let bandpassLower=document.getElementById(plotId+prop+"bandpassLower");let bandpassUpper=document.getElementById(plotId+prop+"bandpassUpper");viewing.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).viewing=viewing.checked;chartSettings.generateNewLines=false;chartworker.run("resetChart",[plotId,chartSettings])}};let filteronchange=()=>{let setting={[prop]:{sps:sps.value?parseFloat(sps.value):100,useScaling:useScaling.checked,scalar:scalar.value?parseFloat(scalar.value):1,useNotch50:useNotch50.checked,useNotch60:useNotch60.checked,useDCBlock:useDCBlock.checked,useLowpass:useLowpass.checked,lowpassHz:lowpassHz.value?parseFloat(lowpassHz.value):100,useBandpass:useBandpass.checked,bandpassLower:bandpassLower.value?parseFloat(bandpassLower.value):3,bandpassUpper:bandpassUpper.value?parseFloat(bandpassUpper.value):45,trimOutliers:filterSettings[prop]?.trimOutliers,outlierTolerance:filterSettings[prop]?.outlierTolerance}};streamworker.post("setFilters",setting)};sps.onchange=()=>{filteronchange();(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])};units.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).units=units.value;chartworker.run("resetChart",[plotId,chartSettings])}};ymax.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};ymin.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).ymax=ymax.value?parseFloat(ymax.value):1;(chartSettings.lines?.[prop]).ymin=ymin.value?parseFloat(ymin.value):0;chartworker.run("resetChart",[plotId,chartSettings])}};nSec.onchange=()=>{if(!Array.isArray(chartSettings.lines?.[prop])){(chartSettings.lines?.[prop]).sps=parseFloat(sps.value);(chartSettings.lines?.[prop]).nSec=parseFloat(nSec.value);delete(chartSettings.lines?.[prop]).points;delete(chartSettings.lines?.[prop]).nPoints;chartworker.run("resetChart",[plotId,chartSettings])}};useScaling.onchange=filteronchange;useNotch50.onchange=filteronchange;useNotch60.onchange=filteronchange;useDCBlock.onchange=filteronchange;useLowpass.onchange=filteronchange;useBandpass.onchange=filteronchange;lowpassHz.onchange=filteronchange;scalar.onchange=filteronchange;bandpassLower.onchange=filteronchange;bandpassUpper.onchange=filteronchange}}}var Math2=class _Math2{constructor(){}static TWO_PI=Math.PI*2;static C=299792458;static G=66743e-15;static h=662607015e-42;static R=8314.32;static Ra=287;static H=69.3;static kbar=1054571817e-43;static kB=1380649e-29;static ke=89875517923e-1;static me=91093837015e-41;static mp=167262192369e-38;static mn=167492749804e-38;static P0=101325;static T0=288.15;static p0=1.225;static Na=60220978e16;static y=1.405;static M0=28.96643;static g0=9.80665;static Re=6378100;static B=1458e-9;static S=110.4;static Sigma=365e-12;static imgkernels={edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]};static HSLToRGB=(h,s,l,scalar=255)=>{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean=void 0)=>{let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean=this.mean(arr);let std=this.std(arr,mean);let z=new Array(arr.length);for(let i=0;ia+(b-mean)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean=this.mean(arr);let std=this.std(arr,mean);return populationMean?std/populationMean:std/mean};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y)=>acc+Math.pow(y-meanY,2),0);const ssResidual=observed.reduce((acc,y,i)=>acc+Math.pow(y-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value)=>acc+Math.pow(value-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x2)=>sum+x2,0);const sumY=yCoords.reduce((sum,y)=>sum+y,0);const sumXY=xCoords.reduce((sum,x2,i)=>sum+x2*yCoords[i],0);const sumX2=xCoords.reduce((sum,x2)=>sum+x2*x2,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{return vec.map((v,i)=>v-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v,i)=>v/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v,i)=>v+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v,i)=>v-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v,i)=>v/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x2,y,z)=>{var r=Math.sqrt(x2*x2+y*y+z*z);var theta=Math.atan2(y,x2);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y=x2;return y},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x2=Math.cos(t);return x2},yFunc=t=>{let y=Math.sin(t);return y},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u,v)=>u,yFunc=(u,v)=>v,zFunc=(u,v)=>u+v,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u=rangeU[0];u{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value,index)=>{const row=Array(values.length).fill(0);row[index]=value;return row})};static householderMatrix=v=>{const size=v.length;const vvT=v.map(rowVal=>v.map(colVal=>rowVal*colVal));const vTv=this.normalize(v)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A,B)=>{return A.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value=>(value-min)/(max-min))};static garroteThreshold=(data,value)=>{return data.map(x2=>{if(Math.abs(x2)<=value){return 0}else{return x2-value*value/x2}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean1=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v,i)=>(v-mean1)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x2,x2),this.cov1d(x2,y),this.cov1d(x2,z)],[this.cov1d(y,x2),this.cov1d(y,y),this.cov1d(y,z)],[this.cov1d(z,x2),this.cov1d(z,y),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v=>v-mean)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N=signalA.length;const M=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x2=arr.filter((element,index)=>{return index%factor===0});return x2};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y=>y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x2)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A,numIter=100)=>{let b=Array(A.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A[0].length>A.length){A=this.transpose(A)}const m=A.length;const n=A[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x2):this.normalize(x2);const u=this.vecsub(x2,e);const normU=this.normalize(u);const v=u.map(val=>val/normU);const Qk=this.householderMatrix(v);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{ax=ax*this.accelConstant;ay=ay*this.accelConstant;az=az*this.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+this.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+this.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v,i)=>{return apass(v,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-this.lastGyroTime;this.lastGyroTime=timestamp;gx=gx*this.gyroConstant+this.gyroXError;gy=gy*this.gyroConstant+this.gyroYError;gz=gz*this.gyroConstant+this.gyroZError;this.gyroXAngle+=gx*elapsed;this.gyroYAngle+=gy*elapsed;this.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:this.gyroXAngle,pitch:this.gyroYAngle,yaw:this.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v,i)=>{if(result){let r=gpass(v,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(this.gyroXAngle||this.gyroYAngle||this.gyroZAngle){result.roll=result.roll*.04+this.gyroXAngle*.96;result.pitch=result.pitch*.04+this.gyroYAngle*.96;result.yaw=this.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-this.lastAccelTime;this.lastAccelTime=timestamp;this.px+=result2.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*.005555555555);this.py+=result2.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*.005555555555);this.pz+=result2.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*.005555555555);result2.px=this.px;result2.py=this.py;result2.pz=this.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{type;freq;sps;Q;dbGain;a0=0;a1=0;a2=0;b0=0;b1=0;b2=0;x1=0;x2=0;y1=0;y2=0;constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A+A);this[type](A,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A,sn,cs,alpha,beta){this.b0=1+alpha*A;this.b1=-2*cs;this.b2=1-alpha*A;this.a0=1+alpha/A;this.a1=-2*cs;this.a2=1-alpha/A}lowshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1-(A-1)*cs+beta*sn);this.b1=2*A*(A-1-(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1+(A+1)*cs+beta*sn;this.a1=2*(A-1+(A+1)*cs);this.a2=A+1+(A-1)*cs-beta*sn}highshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1+(A-1)*cs+beta*sn);this.b1=2*A*(A-1+(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1-(A+1)*cs-beta*sn;this.a1=2*(A-1-(A+1)*cs);this.a2=A+1-(A-1)*cs-beta*sn}applyFilter(signal_step){let y=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y;return y}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10,__onconnected:function(){if(!this.lowpass){let freq=this.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;this.lowpass=new Biquad("lowpass",this.maxFreq,this.sps);this.peakFinderWindow=Math.floor(this.sps/this.maxFreq);if(this.peakFinderWindow%2===0)this.peakFinderWindow+=1;if(this.peakFinderWindow<5)this.peakFinderWindow=5;this.midpoint=Math.round(this.peakFinderWindow*.5)}},__operator:function(data){if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now-refdata.length*this.sps*1e3,now];data.timestamp=Math2.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){this.refdata.push(amplitude)}this.timestamp.push(timestamp);let beat;if(this.refdata.length>this.peakFinderWindow){this.refdata.shift();this.timestamp.shift()}this.smoothed.push(this.lowpass.applyFilter(this.refdata[this.refdata.length-1]));if(this.smoothed.length>this.peakFinderWindow){this.smoothed.shift()}if(this.smoothed.length===this.peakFinderWindow){if(Math2.isExtrema(this.smoothed,"valley")){this.valleys.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}else if(Math2.isExtrema(this.smoothed,"peak")){this.peaks.push({value:this.smoothed[this.smoothed.length-this.midpoint?this.midpoint:1],timestamp:this.timestamp[this.timestamp.length-this.midpoint?this.midpoint:1]})}if(this.valleys.length>2&&this.peaks.length>2){if(this.valleys[this.valleys.length-1].timestamp1&&this.valley_distances.length>1){if(this.lastPeakthis.peak_distances[this.peak_distances.length-1].timestamp){let bpm,change=0;if(this.beats.length<1){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].distance+this.valley_distances[this.valley_distances.length-1].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-1].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-1].dt+this.valley_distances[this.valley_distances.length-1].dt));change=Math.abs(bpm-this.beats[this.beats.length-1].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-1].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-1].peak0-this.valley_distances[this.valley_distances.length-1].peak0,height1:this.peak_distances[this.peak_distances.length-1].peak1-this.valley_distances[this.valley_distances.length-1].peak1};this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}else{let bpm,change=0;if(this.beats.length<2){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance))}else if(this.beats[this.beats.length-1].timestamp!==this.peak_distances[this.peak_distances.length-2].timestamp){bpm=60/(5e-4*(this.peak_distances[this.peak_distances.length-2].distance+this.valley_distances[this.valley_distances.length-2].distance));change=Math.abs(bpm-this.beats[this.beats.length-2].bpm)}beat={timestamp:this.peak_distances[this.peak_distances.length-2].timestamp,change,bpm,height0:this.peak_distances[this.peak_distances.length-2].peak0-this.valley_distances[this.valley_distances.length-2].peak0,height1:this.peak_distances[this.peak_distances.length-2].peak1-this.valley_distances[this.valley_distances.length-2].peak1};if(Array.isArray(beat.timestamp))beat.timestamp=beat.timestamp[0];this.beats.push(beat);this.lastPeak=this.peaks[this.peaks.length-1].timestamp;this.lastValley=this.peaks[this.peaks.length-1].timestamp}}}if(this.peaks.length>this.limit){this.peaks.shift()}if(this.valleys.length>this.limit){this.valleys.shift()}if(this.peak_distances.length>this.limit){this.peak_distances.shift()}if(this.valley_distances.length>this.limit){this.valley_distances.shift()}if(this.beats.length>this.limit){this.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)result=data.red.map((v,i)=>{return pass(v+data.ir[i],data.timestamp[i])}).filter(v=>{if(v)return true});else result=data.red.map((v,i)=>{return pass(v,data.timestamp[i])}).filter(v=>{if(v)return true});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v,i)=>{return pass(v,data.timestamp[i])}).filter(v=>{if(v)return true});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v,i)=>{return pass(v,data.timestamp[i])}).filter(v=>{if(v)return true});return result}}};var blink_detect={sps:250,intervals:{},watch:["0"],tolerance:.2,__onconnected:node=>{node.watch.forEach(ch=>node.intervals[ch]={lowpass:new Biquad("lowpass",20,node.sps),filtered:[],averaged:[]})},__operator:function(data){let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=this.intervals[key].lowpass.applyFilter(n);this.intervals[key].filtered.push(next);this.intervals[key].averaged.push(next);if(this.intervals[key].filtered.length>checkCt){if(this.intervals[key].averaged.length>averageCt){this.intervals[key].averaged.splice(0,checkCt);let mean=Math2.mean(this.intervals[key].averaged);if(Math.abs(Math.min(...this.intervals[key].filtered))>Math.abs(mean)+this.tolerance){this.intervals[key].filtered.length=0;passed=true;found[key]=true}}else this.intervals[key].filtered.shift()}};for(const key in this.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var ArrayManip=class _ArrayManip{static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y=>{if(clamp){if(ymax)y=max}return y*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y=>{if(clamp){if(ymax)y=max}return 2*((y-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now=Date.now();let toInterp=[now-ct*1e3/sps,now];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,...newEntries.slice(newEntries.length-len))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d={};data.forEach((arr,i)=>{d[i]=arr});data=d;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}static bufferValues=(objects,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects[object_keys[0]][property]==="object"){keys=Object.keys(objects[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects){if(objects[key][property]){if(keys){for(let j=0;j{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target};spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var rechk=/^([<>])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v,o,c)=>String.fromCharCode(...new Uint8Array(v.buffer,v.byteOffset+o,c));var rts=(v,o,c,s)=>new Uint8Array(v.buffer,v.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v,o,c)=>str(v,o+1,Math.min(v.getUint8(o),c-1));var tsp=(v,o,c,s)=>{v.setUint8(o,s.length);rts(v,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v=>str(v,o,1),p:(v,c2)=>rts(v,o,1,c2)})],"?":c=>[c,1,o=>({u:v=>Boolean(v.getUint8(o)),p:(v,B)=>v.setUint8(o,B)})],b:c=>[c,1,o=>({u:v=>v.getInt8(o),p:(v,b)=>v.setInt8(o,b)})],B:c=>[c,1,o=>({u:v=>v.getUint8(o),p:(v,B)=>v.setUint8(o,B)})],h:c=>[c,2,o=>({u:v=>v.getInt16(o,le),p:(v,h)=>v.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v=>v.getUint16(o,le),p:(v,H)=>v.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v=>v.getInt32(o,le),p:(v,i)=>v.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v=>v.getUint32(o,le),p:(v,I)=>v.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v=>v.getFloat32(o,le),p:(v,f)=>v.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v=>v.getFloat64(o,le),p:(v,d)=>v.setFloat64(o,d,le)})],s:c=>[1,c,o=>({u:v=>str(v,o,c),p:(v,s)=>rts(v,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v=>pst(v,o,c),p:(v,s)=>tsp(v,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var ByteParser=class _ByteParser extends ArrayManip{static codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y){return[y&255,y>>8&255]}static bytesToInt24(x0,x1,x2){let int24=(255&x0)<<16|(255&x1)<<8|255&x2;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x2){return x0*65536+x1*256+x2}static Uint24ToBytes(y){return[y&255,y>>8&255,y>>16&255]}static bytesToInt32(x0,x1,x2,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x2)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x2,x3){return x0*16777216+x1*65536+x2*256+x3}static Uint32ToBytes(y){return[y&255,y>>8&255,y>>16&255,y>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M=pattern.length;if(M===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R=256;var rightmost_positions=new Int32Array(R);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v=new DataView(arrb,offs|0);return fns.map(f=>f.u(v))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var rms={sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{},__operator:function(data){this.watch.forEach(key=>{if(data[key]){if(!this.data[key]){if(Array.isArray(data[key])){this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key][0])}else this.data[key]=new Array(Math.floor(this.sps*this.nSec)).fill(data[key])}ByteParser.circularBuffer(this.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){this.rms.timestamp=data.timestamp[data.timestamp.length-1]}else this.rms.timestamp=data.timestamp}else this.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(this.watch.map(async key=>{if(this.data[key])this.rms[key]=Math.sqrt(Math.abs(this.data[key].reduce((p,v,i)=>p+v*v)/this.data[key].length));else delete this.rms[key]}));res(this.rms)})}};var circularBuffer2d={bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false,__onconnected:function(node){for(const key in node.watch){node.data[key]=new Array(node.bufferSize).fill(0)}},__operator:function(data){let buffer2d=[];this.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(this.data[key],data[key]);buffer2d.push(this.data[key])}});return buffer2d}};var algorithms={beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d};algorithms["breath"].maxFreq=.2;0&&(module.exports={StructBackend,StructFrontend,Systems,WebglLinePlotInfo,WebglLinePlotProps,WebglLinePlotUtil,WebglLineProps,algorithms,defaultSpecifiers,genTimeSpecifiers,genTimestampFromString,getStringId,pseudoObjectId,randomId,setSignalControls,toObjectId,webglPlotRoutes}); diff --git a/src/extras/dist/index.storage.services.esm.js b/src/extras/dist/index.storage.services.esm.js deleted file mode 100644 index 9d23db51..00000000 --- a/src/extras/dist/index.storage.services.esm.js +++ /dev/null @@ -1,16 +0,0 @@ -var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browserfs=__commonJS({"node_modules/browserfs/dist/browserfs.js"(exports,module){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["BrowserFS"]=factory();else root["BrowserFS"]=factory()})(exports,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module2=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__);module2.loaded=true;return module2.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module2,exports2,__webpack_require__){(function(Buffer2,global,module3,process){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var buffer=__webpack_require__(2);var path=__webpack_require__(9);var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2["EPERM"]=1]="EPERM";ErrorCode2[ErrorCode2["ENOENT"]=2]="ENOENT";ErrorCode2[ErrorCode2["EIO"]=5]="EIO";ErrorCode2[ErrorCode2["EBADF"]=9]="EBADF";ErrorCode2[ErrorCode2["EACCES"]=13]="EACCES";ErrorCode2[ErrorCode2["EBUSY"]=16]="EBUSY";ErrorCode2[ErrorCode2["EEXIST"]=17]="EEXIST";ErrorCode2[ErrorCode2["ENOTDIR"]=20]="ENOTDIR";ErrorCode2[ErrorCode2["EISDIR"]=21]="EISDIR";ErrorCode2[ErrorCode2["EINVAL"]=22]="EINVAL";ErrorCode2[ErrorCode2["EFBIG"]=27]="EFBIG";ErrorCode2[ErrorCode2["ENOSPC"]=28]="ENOSPC";ErrorCode2[ErrorCode2["EROFS"]=30]="EROFS";ErrorCode2[ErrorCode2["ENOTEMPTY"]=39]="ENOTEMPTY";ErrorCode2[ErrorCode2["ENOTSUP"]=95]="ENOTSUP"})(ErrorCode||(ErrorCode={}));var ErrorStrings={};ErrorStrings[ErrorCode.EPERM]="Operation not permitted.";ErrorStrings[ErrorCode.ENOENT]="No such file or directory.";ErrorStrings[ErrorCode.EIO]="Input/output error.";ErrorStrings[ErrorCode.EBADF]="Bad file descriptor.";ErrorStrings[ErrorCode.EACCES]="Permission denied.";ErrorStrings[ErrorCode.EBUSY]="Resource busy or locked.";ErrorStrings[ErrorCode.EEXIST]="File exists.";ErrorStrings[ErrorCode.ENOTDIR]="File is not a directory.";ErrorStrings[ErrorCode.EISDIR]="File is a directory.";ErrorStrings[ErrorCode.EINVAL]="Invalid argument.";ErrorStrings[ErrorCode.EFBIG]="File is too big.";ErrorStrings[ErrorCode.ENOSPC]="No space left on disk.";ErrorStrings[ErrorCode.EROFS]="Cannot modify a read-only file system.";ErrorStrings[ErrorCode.ENOTEMPTY]="Directory is not empty.";ErrorStrings[ErrorCode.ENOTSUP]="Operation is not supported.";var ApiError=function(Error2){function ApiError2(type,message,path$$1){if(message===void 0)message=ErrorStrings[type];Error2.call(this,message);this.syscall="";this.errno=type;this.code=ErrorCode[type];this.path=path$$1;this.stack=new Error2().stack;this.message="Error: "+this.code+": "+message+(this.path?", '"+this.path+"'":"")}if(Error2)ApiError2.__proto__=Error2;ApiError2.prototype=Object.create(Error2&&Error2.prototype);ApiError2.prototype.constructor=ApiError2;ApiError2.fromJSON=function fromJSON(json){var err=new ApiError2(0);err.errno=json.errno;err.code=json.code;err.path=json.path;err.stack=json.stack;err.message=json.message;return err};ApiError2.fromBuffer=function fromBuffer(buffer$$1,i2){if(i2===void 0)i2=0;return ApiError2.fromJSON(JSON.parse(buffer$$1.toString("utf8",i2+4,i2+4+buffer$$1.readUInt32LE(i2))))};ApiError2.FileError=function FileError(code,p){return new ApiError2(code,ErrorStrings[code],p)};ApiError2.ENOENT=function ENOENT(path$$1){return this.FileError(ErrorCode.ENOENT,path$$1)};ApiError2.EEXIST=function EEXIST(path$$1){return this.FileError(ErrorCode.EEXIST,path$$1)};ApiError2.EISDIR=function EISDIR(path$$1){return this.FileError(ErrorCode.EISDIR,path$$1)};ApiError2.ENOTDIR=function ENOTDIR(path$$1){return this.FileError(ErrorCode.ENOTDIR,path$$1)};ApiError2.EPERM=function EPERM(path$$1){return this.FileError(ErrorCode.EPERM,path$$1)};ApiError2.ENOTEMPTY=function ENOTEMPTY(path$$1){return this.FileError(ErrorCode.ENOTEMPTY,path$$1)};ApiError2.prototype.toString=function toString(){return this.message};ApiError2.prototype.toJSON=function toJSON(){return{errno:this.errno,code:this.code,path:this.path,stack:this.stack,message:this.message}};ApiError2.prototype.writeToBuffer=function writeToBuffer(buffer$$1,i2){if(buffer$$1===void 0)buffer$$1=Buffer2.alloc(this.bufferSize());if(i2===void 0)i2=0;var bytesWritten=buffer$$1.write(JSON.stringify(this.toJSON()),i2+4);buffer$$1.writeUInt32LE(bytesWritten,i2);return buffer$$1};ApiError2.prototype.bufferSize=function bufferSize(){return 4+Buffer2.byteLength(JSON.stringify(this.toJSON()))};return ApiError2}(Error);var api_error=Object.freeze({get ErrorCode(){return ErrorCode},ErrorStrings,ApiError});var ActionType;(function(ActionType2){ActionType2[ActionType2["NOP"]=0]="NOP";ActionType2[ActionType2["THROW_EXCEPTION"]=1]="THROW_EXCEPTION";ActionType2[ActionType2["TRUNCATE_FILE"]=2]="TRUNCATE_FILE";ActionType2[ActionType2["CREATE_FILE"]=3]="CREATE_FILE"})(ActionType||(ActionType={}));var FileFlag=function FileFlag2(flagStr){this.flagStr=flagStr;if(FileFlag2.validFlagStrs.indexOf(flagStr)<0){throw new ApiError(ErrorCode.EINVAL,"Invalid flag: "+flagStr)}};FileFlag.getFileFlag=function getFileFlag(flagStr){if(FileFlag.flagCache.hasOwnProperty(flagStr)){return FileFlag.flagCache[flagStr]}return FileFlag.flagCache[flagStr]=new FileFlag(flagStr)};FileFlag.prototype.getFlagString=function getFlagString(){return this.flagStr};FileFlag.prototype.isReadable=function isReadable(){return this.flagStr.indexOf("r")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isWriteable=function isWriteable(){return this.flagStr.indexOf("w")!==-1||this.flagStr.indexOf("a")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isTruncating=function isTruncating(){return this.flagStr.indexOf("w")!==-1};FileFlag.prototype.isAppendable=function isAppendable(){return this.flagStr.indexOf("a")!==-1};FileFlag.prototype.isSynchronous=function isSynchronous(){return this.flagStr.indexOf("s")!==-1};FileFlag.prototype.isExclusive=function isExclusive(){return this.flagStr.indexOf("x")!==-1};FileFlag.prototype.pathExistsAction=function pathExistsAction(){if(this.isExclusive()){return ActionType.THROW_EXCEPTION}else if(this.isTruncating()){return ActionType.TRUNCATE_FILE}else{return ActionType.NOP}};FileFlag.prototype.pathNotExistsAction=function pathNotExistsAction(){if((this.isWriteable()||this.isAppendable())&&this.flagStr!=="r+"){return ActionType.CREATE_FILE}else{return ActionType.THROW_EXCEPTION}};FileFlag.flagCache={};FileFlag.validFlagStrs=["r","r+","rs","rs+","w","wx","w+","wx+","a","ax","a+","ax+"];var FileType;(function(FileType2){FileType2[FileType2["FILE"]=32768]="FILE";FileType2[FileType2["DIRECTORY"]=16384]="DIRECTORY";FileType2[FileType2["SYMLINK"]=40960]="SYMLINK"})(FileType||(FileType={}));var Stats=function Stats2(itemType,size,mode,atime,mtime,ctime){if(atime===void 0)atime=new Date;if(mtime===void 0)mtime=new Date;if(ctime===void 0)ctime=new Date;this.size=size;this.atime=atime;this.mtime=mtime;this.ctime=ctime;this.dev=0;this.ino=0;this.rdev=0;this.nlink=1;this.blksize=4096;this.uid=0;this.gid=0;this.birthtime=new Date(0);this.fileData=null;if(!mode){switch(itemType){case FileType.FILE:this.mode=420;break;case FileType.DIRECTORY:default:this.mode=511}}else{this.mode=mode}this.blocks=Math.ceil(size/512);if(this.mode<4096){this.mode|=itemType}};Stats.fromBuffer=function fromBuffer(buffer$$1){var size=buffer$$1.readUInt32LE(0),mode=buffer$$1.readUInt32LE(4),atime=buffer$$1.readDoubleLE(8),mtime=buffer$$1.readDoubleLE(16),ctime=buffer$$1.readDoubleLE(24);return new Stats(mode&61440,size,mode&4095,new Date(atime),new Date(mtime),new Date(ctime))};Stats.prototype.toBuffer=function toBuffer(){var buffer$$1=Buffer2.alloc(32);buffer$$1.writeUInt32LE(this.size,0);buffer$$1.writeUInt32LE(this.mode,4);buffer$$1.writeDoubleLE(this.atime.getTime(),8);buffer$$1.writeDoubleLE(this.mtime.getTime(),16);buffer$$1.writeDoubleLE(this.ctime.getTime(),24);return buffer$$1};Stats.prototype.clone=function clone(){return new Stats(this.mode&61440,this.size,this.mode&4095,this.atime,this.mtime,this.ctime)};Stats.prototype.isFile=function isFile(){return(this.mode&61440)===FileType.FILE};Stats.prototype.isDirectory=function isDirectory(){return(this.mode&61440)===FileType.DIRECTORY};Stats.prototype.isSymbolicLink=function isSymbolicLink(){return(this.mode&61440)===FileType.SYMLINK};Stats.prototype.chmod=function chmod(mode){this.mode=this.mode&61440|mode};Stats.prototype.isSocket=function isSocket(){return false};Stats.prototype.isBlockDevice=function isBlockDevice(){return false};Stats.prototype.isCharacterDevice=function isCharacterDevice(){return false};Stats.prototype.isFIFO=function isFIFO(){return false};var wrapCb=function(cb,numArgs){return cb};function assertRoot(fs4){if(fs4){return fs4}throw new ApiError(ErrorCode.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function normalizeMode(mode,def){switch(typeof mode){case"number":return mode;case"string":var trueMode=parseInt(mode,8);if(!isNaN(trueMode)){return trueMode}return def;default:return def}}function normalizeTime(time){if(time instanceof Date){return time}else if(typeof time==="number"){return new Date(time*1e3)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid time.")}}function normalizePath(p){if(p.indexOf("\0")>=0){throw new ApiError(ErrorCode.EINVAL,"Path must be a string without null bytes.")}else if(p===""){throw new ApiError(ErrorCode.EINVAL,"Path must not be empty.")}return path.resolve(p)}function normalizeOptions(options,defEnc,defFlag,defMode){switch(typeof options){case"object":return{encoding:typeof options["encoding"]!=="undefined"?options["encoding"]:defEnc,flag:typeof options["flag"]!=="undefined"?options["flag"]:defFlag,mode:normalizeMode(options["mode"],defMode)};case"string":return{encoding:options,flag:defFlag,mode:defMode};default:return{encoding:defEnc,flag:defFlag,mode:defMode}}}function nopCb(){}var FS=function FS2(){this.F_OK=0;this.R_OK=4;this.W_OK=2;this.X_OK=1;this.root=null;this.fdMap={};this.nextFd=100};FS.prototype.initialize=function initialize3(rootFS){if(!rootFS.constructor.isAvailable()){throw new ApiError(ErrorCode.EINVAL,"Tried to instantiate BrowserFS with an unavailable file system.")}return this.root=rootFS};FS.prototype._toUnixTimestamp=function _toUnixTimestamp(time){if(typeof time==="number"){return time}else if(time instanceof Date){return time.getTime()/1e3}throw new Error("Cannot parse time: "+time)};FS.prototype.getRootFS=function getRootFS(){if(this.root){return this.root}else{return null}};FS.prototype.rename=function rename(oldPath,newPath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).rename(normalizePath(oldPath),normalizePath(newPath),newCb)}catch(e){newCb(e)}};FS.prototype.renameSync=function renameSync(oldPath,newPath){assertRoot(this.root).renameSync(normalizePath(oldPath),normalizePath(newPath))};FS.prototype.exists=function exists2(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).exists(normalizePath(path$$1),newCb)}catch(e){return newCb(false)}};FS.prototype.existsSync=function existsSync(path$$1){try{return assertRoot(this.root).existsSync(normalizePath(path$$1))}catch(e){return false}};FS.prototype.stat=function stat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),false,newCb)}catch(e){return newCb(e)}};FS.prototype.statSync=function statSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),false)};FS.prototype.lstat=function lstat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),true,newCb)}catch(e){return newCb(e)}};FS.prototype.lstatSync=function lstatSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),true)};FS.prototype.truncate=function truncate(path$$1,arg2,cb){if(arg2===void 0)arg2=0;if(cb===void 0)cb=nopCb;var len=0;if(typeof arg2==="function"){cb=arg2}else if(typeof arg2==="number"){len=arg2}var newCb=wrapCb(cb,1);try{if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncate(normalizePath(path$$1),len,newCb)}catch(e){return newCb(e)}};FS.prototype.truncateSync=function truncateSync(path$$1,len){if(len===void 0)len=0;if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncateSync(normalizePath(path$$1),len)};FS.prototype.unlink=function unlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).unlink(normalizePath(path$$1),newCb)}catch(e){return newCb(e)}};FS.prototype.unlinkSync=function unlinkSync(path$$1){return assertRoot(this.root).unlinkSync(normalizePath(path$$1))};FS.prototype.open=function open(path$$1,flag,arg2,cb){var this$1=this;if(cb===void 0)cb=nopCb;var mode=normalizeMode(arg2,420);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{assertRoot(this.root).open(normalizePath(path$$1),FileFlag.getFileFlag(flag),mode,function(e,file){if(file){newCb(e,this$1.getFdForFile(file))}else{newCb(e)}})}catch(e){newCb(e)}};FS.prototype.openSync=function openSync(path$$1,flag,mode){if(mode===void 0)mode=420;return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1),FileFlag.getFileFlag(flag),normalizeMode(mode,420)))};FS.prototype.readFile=function readFile2(filename,arg2,cb){if(arg2===void 0)arg2={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg2,null,"r",null);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{var flag=FileFlag.getFileFlag(options["flag"]);if(!flag.isReadable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading."))}return assertRoot(this.root).readFile(normalizePath(filename),options.encoding,flag,newCb)}catch(e){return newCb(e)}};FS.prototype.readFileSync=function readFileSync(filename,arg2){if(arg2===void 0)arg2={};var options=normalizeOptions(arg2,null,"r",null);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isReadable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading.")}return assertRoot(this.root).readFileSync(normalizePath(filename),options.encoding,flag)};FS.prototype.writeFile=function writeFile2(filename,data,arg3,cb){if(arg3===void 0)arg3={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","w",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing."))}return assertRoot(this.root).writeFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){return newCb(e)}};FS.prototype.writeFileSync=function writeFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","w",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing.")}return assertRoot(this.root).writeFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.appendFile=function appendFile3(filename,data,arg3,cb){if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","a",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending."))}assertRoot(this.root).appendFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){newCb(e)}};FS.prototype.appendFileSync=function appendFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","a",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending.")}return assertRoot(this.root).appendFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.fstat=function fstat(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{var file=this.fd2file(fd);file.stat(newCb)}catch(e){newCb(e)}};FS.prototype.fstatSync=function fstatSync(fd){return this.fd2file(fd).statSync()};FS.prototype.close=function close(fd,cb){var this$1=this;if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).close(function(e){if(!e){this$1.closeFd(fd)}newCb(e)})}catch(e){newCb(e)}};FS.prototype.closeSync=function closeSync(fd){this.fd2file(fd).closeSync();this.closeFd(fd)};FS.prototype.ftruncate=function ftruncate(fd,arg2,cb){if(cb===void 0)cb=nopCb;var length=typeof arg2==="number"?arg2:0;cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(length<0){throw new ApiError(ErrorCode.EINVAL)}file.truncate(length,newCb)}catch(e){newCb(e)}};FS.prototype.ftruncateSync=function ftruncateSync(fd,len){if(len===void 0)len=0;var file=this.fd2file(fd);if(len<0){throw new ApiError(ErrorCode.EINVAL)}file.truncateSync(len)};FS.prototype.fsync=function fsync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).sync(newCb)}catch(e){newCb(e)}};FS.prototype.fsyncSync=function fsyncSync(fd){this.fd2file(fd).syncSync()};FS.prototype.fdatasync=function fdatasync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).datasync(newCb)}catch(e){newCb(e)}};FS.prototype.fdatasyncSync=function fdatasyncSync(fd){this.fd2file(fd).datasyncSync()};FS.prototype.write=function write(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var buffer$$1,offset,length,position=null;if(typeof arg2==="string"){var encoding="utf8";switch(typeof arg3){case"function":cb=arg3;break;case"number":position=arg3;encoding=typeof arg4==="string"?arg4:"utf8";cb=typeof arg5==="function"?arg5:cb;break;default:cb=typeof arg4==="function"?arg4:typeof arg5==="function"?arg5:cb;return cb(new ApiError(ErrorCode.EINVAL,"Invalid arguments."))}buffer$$1=Buffer2.from(arg2,encoding);offset=0;length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null;cb=typeof arg5==="function"?arg5:cb}var newCb=wrapCb(cb,3);try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.write(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.writeSync=function writeSync(fd,arg2,arg3,arg4,arg5){var buffer$$1,offset=0,length,position;if(typeof arg2==="string"){position=typeof arg3==="number"?arg3:null;var encoding=typeof arg4==="string"?arg4:"utf8";offset=0;buffer$$1=Buffer2.from(arg2,encoding);length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}return file.writeSync(buffer$$1,offset,length,position)};FS.prototype.read=function read(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var position,offset,length,buffer$$1,newCb;if(typeof arg2==="number"){length=arg2;position=arg3;var encoding=arg4;cb=typeof arg5==="function"?arg5:cb;offset=0;buffer$$1=Buffer2.alloc(length);newCb=wrapCb(function(err,bytesRead,buf){if(err){return cb(err)}cb(err,buf.toString(encoding),bytesRead)},3)}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5;newCb=wrapCb(cb,3)}try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.read(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.readSync=function readSync(fd,arg2,arg3,arg4,arg5){var shenanigans=false;var buffer$$1,offset,length,position,encoding="utf8";if(typeof arg2==="number"){length=arg2;position=arg3;encoding=arg4;offset=0;buffer$$1=Buffer2.alloc(length);shenanigans=true}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}var rv=file.readSync(buffer$$1,offset,length,position);if(!shenanigans){return rv}else{return[buffer$$1.toString(encoding),rv]}};FS.prototype.fchown=function fchown(fd,uid,gid,callback){if(callback===void 0)callback=nopCb;var newCb=wrapCb(callback,1);try{this.fd2file(fd).chown(uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.fchownSync=function fchownSync(fd,uid,gid){this.fd2file(fd).chownSync(uid,gid)};FS.prototype.fchmod=function fchmod(fd,mode,cb){var newCb=wrapCb(cb,1);try{var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmod(numMode,newCb)}catch(e){newCb(e)}};FS.prototype.fchmodSync=function fchmodSync(fd,mode){var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmodSync(numMode)};FS.prototype.futimes=function futimes(fd,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(typeof atime==="number"){atime=new Date(atime*1e3)}if(typeof mtime==="number"){mtime=new Date(mtime*1e3)}file.utimes(atime,mtime,newCb)}catch(e){newCb(e)}};FS.prototype.futimesSync=function futimesSync(fd,atime,mtime){this.fd2file(fd).utimesSync(normalizeTime(atime),normalizeTime(mtime))};FS.prototype.rmdir=function rmdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).rmdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.rmdirSync=function rmdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).rmdirSync(path$$1)};FS.prototype.mkdir=function mkdir(path$$1,mode,cb){if(cb===void 0)cb=nopCb;if(typeof mode==="function"){cb=mode;mode=511}var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).mkdir(path$$1,mode,newCb)}catch(e){newCb(e)}};FS.prototype.mkdirSync=function mkdirSync(path$$1,mode){assertRoot(this.root).mkdirSync(normalizePath(path$$1),normalizeMode(mode,511))};FS.prototype.readdir=function readdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readdirSync=function readdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readdirSync(path$$1)};FS.prototype.link=function link(srcpath,dstpath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).link(srcpath,dstpath,newCb)}catch(e){newCb(e)}};FS.prototype.linkSync=function linkSync(srcpath,dstpath){srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).linkSync(srcpath,dstpath)};FS.prototype.symlink=function symlink(srcpath,dstpath,arg3,cb){if(cb===void 0)cb=nopCb;var type=typeof arg3==="string"?arg3:"file";cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{if(type!=="file"&&type!=="dir"){return newCb(new ApiError(ErrorCode.EINVAL,"Invalid type: "+type))}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).symlink(srcpath,dstpath,type,newCb)}catch(e){newCb(e)}};FS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(!type){type="file"}else if(type!=="file"&&type!=="dir"){throw new ApiError(ErrorCode.EINVAL,"Invalid type: "+type)}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).symlinkSync(srcpath,dstpath,type)};FS.prototype.readlink=function readlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readlink(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readlinkSync=function readlinkSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readlinkSync(path$$1)};FS.prototype.chown=function chown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,false,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.chownSync=function chownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,false,uid,gid)};FS.prototype.lchown=function lchown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,true,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.lchownSync=function lchownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,true,uid,gid)};FS.prototype.chmod=function chmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),false,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.chmodSync=function chmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}path$$1=normalizePath(path$$1);assertRoot(this.root).chmodSync(path$$1,false,numMode)};FS.prototype.lchmod=function lchmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),true,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.lchmodSync=function lchmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<1){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmodSync(normalizePath(path$$1),true,numMode)};FS.prototype.utimes=function utimes(path$$1,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).utimes(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime),newCb)}catch(e){newCb(e)}};FS.prototype.utimesSync=function utimesSync(path$$1,atime,mtime){assertRoot(this.root).utimesSync(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime))};FS.prototype.realpath=function realpath(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;var cache=typeof arg2==="object"?arg2:{};cb=typeof arg2==="function"?arg2:nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).realpath(path$$1,cache,newCb)}catch(e){newCb(e)}};FS.prototype.realpathSync=function realpathSync(path$$1,cache){if(cache===void 0)cache={};path$$1=normalizePath(path$$1);return assertRoot(this.root).realpathSync(path$$1,cache)};FS.prototype.watchFile=function watchFile(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.unwatchFile=function unwatchFile(filename,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.watch=function watch(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.access=function access(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.accessSync=function accessSync(path$$1,mode){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createReadStream=function createReadStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createWriteStream=function createWriteStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.wrapCallbacks=function wrapCallbacks(cbWrapper){wrapCb=cbWrapper};FS.prototype.getFdForFile=function getFdForFile(file){var fd=this.nextFd++;this.fdMap[fd]=file;return fd};FS.prototype.fd2file=function fd2file(fd){var rv=this.fdMap[fd];if(rv){return rv}else{throw new ApiError(ErrorCode.EBADF,"Invalid file descriptor.")}};FS.prototype.closeFd=function closeFd(fd){delete this.fdMap[fd]};FS.Stats=Stats;var fs3=new FS;var _fsMock={};var fsProto=FS.prototype;Object.keys(fsProto).forEach(function(key){if(typeof fs3[key]==="function"){_fsMock[key]=function(){return fs3[key].apply(fs3,arguments)}}else{_fsMock[key]=fs3[key]}});_fsMock["changeFSModule"]=function(newFs){fs3=newFs};_fsMock["getFSModule"]=function(){return fs3};_fsMock["FS"]=FS;function _min(d0,d1,d2,bx,ay){return d0d2?d2+1:d0+1:bx===ay?d1:d1+1}function levenshtein(a,b){if(a===b){return 0}if(a.length>b.length){var tmp=a;a=b;b=tmp}var la=a.length;var lb=b.length;while(la>0&&a.charCodeAt(la-1)===b.charCodeAt(lb-1)){la--;lb--}var offset=0;while(offsetdd?dd+1:dy$1+1:bx0$1===vector[la+y$2]?d0:d0+1;d0=dy$1}}return dd}function deprecationMessage(print,fsName,opts){if(print){console.warn("["+fsName+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+fsName+".Create("+JSON.stringify(opts)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}}var isIE=typeof navigator!=="undefined"&&!!(/(msie) ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||navigator.userAgent.indexOf("Trident")!==-1);var isWebWorker=typeof window==="undefined";function fail(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function mkdirpSync(p,mode,fs4){if(!fs4.existsSync(p)){mkdirpSync(path.dirname(p),mode,fs4);fs4.mkdirSync(p,mode)}}function buffer2ArrayBuffer(buff){var u8=buffer2Uint8array(buff),u8offset=u8.byteOffset,u8Len=u8.byteLength;if(u8offset===0&&u8Len===u8.buffer.byteLength){return u8.buffer}else{return u8.buffer.slice(u8offset,u8offset+u8Len)}}function buffer2Uint8array(buff){if(buff instanceof Uint8Array){return buff}else{return new Uint8Array(buff)}}function arrayish2Buffer(arr){if(arr instanceof Buffer2){return arr}else if(arr instanceof Uint8Array){return uint8Array2Buffer(arr)}else{return Buffer2.from(arr)}}function uint8Array2Buffer(u8){if(u8 instanceof Buffer2){return u8}else if(u8.byteOffset===0&&u8.byteLength===u8.buffer.byteLength){return arrayBuffer2Buffer(u8.buffer)}else{return Buffer2.from(u8.buffer,u8.byteOffset,u8.byteLength)}}function arrayBuffer2Buffer(ab){return Buffer2.from(ab)}function copyingSlice(buff,start,end){if(start===void 0)start=0;if(end===void 0)end=buff.length;if(start<0||end<0||end>buff.length||start>end){throw new TypeError("Invalid slice bounds on buffer of length "+buff.length+": ["+start+", "+end+"]")}if(buff.length===0){return emptyBuffer()}else{var u8=buffer2Uint8array(buff),s0=buff[0],newS0=(s0+1)%255;buff[0]=newS0;if(u8[0]===newS0){u8[0]=s0;return uint8Array2Buffer(u8.slice(start,end))}else{buff[0]=s0;return uint8Array2Buffer(u8.subarray(start,end))}}}var emptyBuff=null;function emptyBuffer(){if(emptyBuff){return emptyBuff}return emptyBuff=Buffer2.alloc(0)}function bufferValidator(v,cb){if(Buffer2.isBuffer(v)){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"option must be a Buffer."))}}function checkOptions(fsType,opts,cb){var optsInfo=fsType.Options;var fsName=fsType.Name;var pendingValidators=0;var callbackCalled=false;var loopEnded=false;function validatorCallback(e){if(!callbackCalled){if(e){callbackCalled=true;cb(e)}pendingValidators--;if(pendingValidators===0&&loopEnded){cb()}}}var loop=function(optName2){if(optsInfo.hasOwnProperty(optName2)){var opt=optsInfo[optName2];var providedValue=opts[optName2];if(providedValue===void 0||providedValue===null){if(!opt.optional){var incorrectOptions=Object.keys(opts).filter(function(o){return!(o in optsInfo)}).map(function(a){return{str:a,distance:levenshtein(optName2,a)}}).filter(function(o){return o.distance<5}).sort(function(a,b){return a.distance-b.distance});if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Required option '"+optName2+"' not provided."+(incorrectOptions.length>0?" You provided unrecognized option '"+incorrectOptions[0].str+"'; perhaps you meant to type '"+optName2+"'.":"")+"\nOption description: "+opt.description))}}}else{var typeMatches=false;if(Array.isArray(opt.type)){typeMatches=opt.type.indexOf(typeof providedValue)!==-1}else{typeMatches=typeof providedValue===opt.type}if(!typeMatches){if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Value provided for option "+optName2+" is not the proper type. Expected "+(Array.isArray(opt.type)?"one of {"+opt.type.join(", ")+"}":opt.type)+", but received "+typeof providedValue+"\nOption description: "+opt.description))}}else if(opt.validator){pendingValidators++;opt.validator(providedValue,validatorCallback)}}}};for(var optName in optsInfo){var returned=loop(optName);if(returned)return returned.v}loopEnded=true;if(pendingValidators===0&&!callbackCalled){cb()}}var BFSUtils=Object.freeze({deprecationMessage,isIE,isWebWorker,fail,mkdirpSync,buffer2ArrayBuffer,buffer2Uint8array,arrayish2Buffer,uint8Array2Buffer,arrayBuffer2Buffer,copyingSlice,emptyBuffer,bufferValidator,checkOptions});var BFSEmscriptenStreamOps=function BFSEmscriptenStreamOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenStreamOps.prototype.open=function open(stream){var path$$1=this.fs.realPath(stream.node);var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)){stream.nfd=this.nodefs.openSync(path$$1,this.fs.flagsToPermissionString(stream.flags))}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.close=function close(stream){var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)&&stream.nfd){this.nodefs.closeSync(stream.nfd)}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.read=function read(stream,buffer$$1,offset,length,position){try{return this.nodefs.readSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.write=function write(stream,buffer$$1,offset,length,position){try{return this.nodefs.writeSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.llseek=function llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(this.FS.isFile(stream.node.mode)){try{var stat=this.nodefs.fstatSync(stream.nfd);position+=stat.size}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}}if(position<0){throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL)}stream.position=position;return position};var BFSEmscriptenNodeOps=function BFSEmscriptenNodeOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenNodeOps.prototype.getattr=function getattr(node){var path$$1=this.fs.realPath(node);var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}};BFSEmscriptenNodeOps.prototype.setattr=function setattr(node,attr){var path$$1=this.fs.realPath(node);try{if(attr.mode!==void 0){this.nodefs.chmodSync(path$$1,attr.mode);node.mode=attr.mode}if(attr.timestamp!==void 0){var date=new Date(attr.timestamp);this.nodefs.utimesSync(path$$1,date,date)}}catch(e){if(!e.code){throw e}if(e.code!=="ENOTSUP"){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}if(attr.size!==void 0){try{this.nodefs.truncateSync(path$$1,attr.size)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}};BFSEmscriptenNodeOps.prototype.lookup=function lookup(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);var mode=this.fs.getMode(path$$1);return this.fs.createNode(parent,name,mode)};BFSEmscriptenNodeOps.prototype.mknod=function mknod(parent,name,mode,dev){var node=this.fs.createNode(parent,name,mode,dev);var path$$1=this.fs.realPath(node);try{if(this.FS.isDir(node.mode)){this.nodefs.mkdirSync(path$$1,node.mode)}else{this.nodefs.writeFileSync(path$$1,"",{mode:node.mode})}}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return node};BFSEmscriptenNodeOps.prototype.rename=function rename(oldNode,newDir,newName){var oldPath=this.fs.realPath(oldNode);var newPath=this.PATH.join2(this.fs.realPath(newDir),newName);try{this.nodefs.renameSync(oldPath,newPath);oldNode.name=newName;oldNode.parent=newDir}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.unlink=function unlink(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.unlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.rmdir=function rmdir(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.rmdirSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readdir=function readdir(node){var path$$1=this.fs.realPath(node);try{var contents=this.nodefs.readdirSync(path$$1);contents.push(".","..");return contents}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.symlink=function symlink(parent,newName,oldPath){var newPath=this.PATH.join2(this.fs.realPath(parent),newName);try{this.nodefs.symlinkSync(oldPath,newPath)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readlink=function readlink(node){var path$$1=this.fs.realPath(node);try{return this.nodefs.readlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};var BFSEmscriptenFS=function BFSEmscriptenFS2(_FS,_PATH,_ERRNO_CODES,nodefs){if(_FS===void 0)_FS=self["FS"];if(_PATH===void 0)_PATH=self["PATH"];if(_ERRNO_CODES===void 0)_ERRNO_CODES=self["ERRNO_CODES"];if(nodefs===void 0)nodefs=_fsMock;this.flagsToPermissionStringMap={0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"};this.nodefs=nodefs;this.FS=_FS;this.PATH=_PATH;this.ERRNO_CODES=_ERRNO_CODES;this.node_ops=new BFSEmscriptenNodeOps(this);this.stream_ops=new BFSEmscriptenStreamOps(this)};BFSEmscriptenFS.prototype.mount=function mount(m){return this.createNode(null,"/",this.getMode(m.opts.root),0)};BFSEmscriptenFS.prototype.createNode=function createNode(parent,name,mode,dev){var FS2=this.FS;if(!FS2.isDir(mode)&&!FS2.isFile(mode)&&!FS2.isLink(mode)){throw new FS2.ErrnoError(this.ERRNO_CODES.EINVAL)}var node=FS2.createNode(parent,name,mode);node.node_ops=this.node_ops;node.stream_ops=this.stream_ops;return node};BFSEmscriptenFS.prototype.getMode=function getMode(path$$1){var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return stat.mode};BFSEmscriptenFS.prototype.realPath=function realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return this.PATH.join.apply(null,parts)};BFSEmscriptenFS.prototype.flagsToPermissionString=function flagsToPermissionString(flags){var parsedFlags=typeof flags==="string"?parseInt(flags,10):flags;parsedFlags&=8191;if(parsedFlags in this.flagsToPermissionStringMap){return this.flagsToPermissionStringMap[parsedFlags]}else{return flags}};BFSEmscriptenFS.prototype.getNodeFS=function getNodeFS(){return this.nodefs};BFSEmscriptenFS.prototype.getFS=function getFS(){return this.FS};BFSEmscriptenFS.prototype.getPATH=function getPATH(){return this.PATH};BFSEmscriptenFS.prototype.getERRNO_CODES=function getERRNO_CODES(){return this.ERRNO_CODES};var BaseFileSystem=function BaseFileSystem2(){};BaseFileSystem.prototype.supportsLinks=function supportsLinks(){return false};BaseFileSystem.prototype.diskSpace=function diskSpace(p,cb){cb(0,0)};BaseFileSystem.prototype.openFile=function openFile(p,flag,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFile=function createFile(p,flag,mode,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.open=function open(p,flag,mode,cb){var this$1=this;var mustBeFile=function(e,stats){if(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.stat(path.dirname(p),false,function(e2,parentStats){if(e2){cb(e2)}else if(parentStats&&!parentStats.isDirectory()){cb(ApiError.ENOTDIR(path.dirname(p)))}else{this$1.createFile(p,flag,mode,cb)}});case ActionType.THROW_EXCEPTION:return cb(ApiError.ENOENT(p));default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}else{if(stats&&stats.isDirectory()){return cb(ApiError.EISDIR(p))}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:return cb(ApiError.EEXIST(p));case ActionType.TRUNCATE_FILE:return this$1.openFile(p,flag,function(e2,fd){if(e2){cb(e2)}else if(fd){fd.truncate(0,function(){fd.sync(function(){cb(null,fd)})})}else{fail()}});case ActionType.NOP:return this$1.openFile(p,flag,cb);default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}};this.stat(p,false,mustBeFile)};BaseFileSystem.prototype.rename=function rename(oldPath,newPath,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.renameSync=function renameSync(oldPath,newPath){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.stat=function stat(p,isLstat,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.statSync=function statSync(p,isLstat){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openFileSync=function openFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFileSync=function createFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openSync=function openSync(p,flag,mode){var stats;try{stats=this.statSync(p,false)}catch(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:var parentStats=this.statSync(path.dirname(p),false);if(!parentStats.isDirectory()){throw ApiError.ENOTDIR(path.dirname(p))}return this.createFileSync(p,flag,mode);case ActionType.THROW_EXCEPTION:throw ApiError.ENOENT(p);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}}if(stats.isDirectory()){throw ApiError.EISDIR(p)}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:throw ApiError.EEXIST(p);case ActionType.TRUNCATE_FILE:this.unlinkSync(p);return this.createFileSync(p,flag,stats.mode);case ActionType.NOP:return this.openFileSync(p,flag,mode);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}};BaseFileSystem.prototype.unlink=function unlink(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.unlinkSync=function unlinkSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.rmdir=function rmdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.rmdirSync=function rmdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.mkdir=function mkdir(p,mode,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.mkdirSync=function mkdirSync(p,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.readdir=function readdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.readdirSync=function readdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.exists=function exists2(p,cb){this.stat(p,null,function(err){cb(!err)})};BaseFileSystem.prototype.existsSync=function existsSync(p){try{this.statSync(p,true);return true}catch(e){return false}};BaseFileSystem.prototype.realpath=function realpath(p,cache,cb){if(this.supportsLinks()){var splitPath=p.split(path.sep);for(var i2=0;i2this._buffer.length){var buf=Buffer2.alloc(len-this._buffer.length,0);this.writeSync(buf,0,buf.length,this._buffer.length);if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}return}this._stat.size=len;var newBuff=Buffer2.alloc(len);this._buffer.copy(newBuff,0,0,len);this._buffer=newBuff;if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}};PreloadFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){this._dirty=true;if(position===void 0||position===null){position=this.getPos()}if(!this._flag.isWriteable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a writeable mode.")}var endFp=position+length;if(endFp>this._stat.size){this._stat.size=endFp;if(endFp>this._buffer.length){var newBuff=Buffer2.alloc(endFp);this._buffer.copy(newBuff);this._buffer=newBuff}}var len=buffer$$1.copy(this._buffer,position,offset,offset+length);this._stat.mtime=new Date;if(this._flag.isSynchronous()){this.syncSync();return len}this.setPos(position+len);return len};PreloadFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){if(!this._flag.isReadable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a readable mode.")}if(position===void 0||position===null){position=this.getPos()}var endRead=position+length;if(endRead>this._stat.size){length=this._stat.size-position}var rv=this._buffer.copy(buffer$$1,offset,position,position+length);this._stat.atime=new Date;this._pos=position+length;return rv};PreloadFile2.prototype.chmod=function chmod(mode,cb){try{this.chmodSync(mode);cb()}catch(e){cb(e)}};PreloadFile2.prototype.chmodSync=function chmodSync(mode){if(!this._fs.supportsProps()){throw new ApiError(ErrorCode.ENOTSUP)}this._dirty=true;this._stat.chmod(mode);this.syncSync()};PreloadFile2.prototype.isDirty=function isDirty(){return this._dirty};PreloadFile2.prototype.resetDirty=function resetDirty(){this._dirty=false};return PreloadFile2}(BaseFile);var NoSyncFile=function(PreloadFile2){function NoSyncFile2(_fs,_path,_flag,_stat,contents){PreloadFile2.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile2)NoSyncFile2.__proto__=PreloadFile2;NoSyncFile2.prototype=Object.create(PreloadFile2&&PreloadFile2.prototype);NoSyncFile2.prototype.constructor=NoSyncFile2;NoSyncFile2.prototype.sync=function sync(cb){cb()};NoSyncFile2.prototype.syncSync=function syncSync(){};NoSyncFile2.prototype.close=function close(cb){cb()};NoSyncFile2.prototype.closeSync=function closeSync(){};return NoSyncFile2}(PreloadFile);var MirrorFile=function(PreloadFile$$1){function MirrorFile2(fs4,path$$1,flag,stat,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,data)}if(PreloadFile$$1)MirrorFile2.__proto__=PreloadFile$$1;MirrorFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);MirrorFile2.prototype.constructor=MirrorFile2;MirrorFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};MirrorFile2.prototype.closeSync=function closeSync(){this.syncSync()};return MirrorFile2}(PreloadFile);var AsyncMirror=function(SynchronousFileSystem$$1){function AsyncMirror2(sync,async,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this._queue=[];this._queueRunning=false;this._isInitialized=false;this._initializeCallbacks=[];this._sync=sync;this._async=async;if(!sync.supportsSynch()){throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.")}deprecationMessage(deprecateMsg,AsyncMirror2.Name,{sync:"sync file system instance",async:"async file system instance"})}if(SynchronousFileSystem$$1)AsyncMirror2.__proto__=SynchronousFileSystem$$1;AsyncMirror2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);AsyncMirror2.prototype.constructor=AsyncMirror2;AsyncMirror2.Create=function Create(opts,cb){try{var fs4=new AsyncMirror2(opts.sync,opts.async,false);fs4.initialize(function(e){if(e){cb(e)}else{cb(null,fs4)}},false)}catch(e){cb(e)}};AsyncMirror2.isAvailable=function isAvailable(){return true};AsyncMirror2.prototype.getName=function getName(){return AsyncMirror2.Name};AsyncMirror2.prototype._syncSync=function _syncSync(fd){this._sync.writeFileSync(fd.getPath(),fd.getBuffer(),null,FileFlag.getFileFlag("w"),fd.getStats().mode);this.enqueueOp({apiMethod:"writeFile",arguments:[fd.getPath(),fd.getBuffer(),null,fd.getFlag(),fd.getStats().mode]})};AsyncMirror2.prototype.initialize=function initialize3(userCb,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.")}var callbacks=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbacks.forEach(function(cb){return cb(e)})};if(!this._isInitialized){if(callbacks.push(userCb)===1){var copyDirectory=function(p,mode,cb){if(p!=="/"){this$1._sync.mkdirSync(p,mode)}this$1._async.readdir(p,function(err,files){var i2=0;function copyNextFile(err2){if(err2){cb(err2)}else if(i20){var op2=this$1._queue.shift(),args=op2.arguments;args.push(doNextOp);this$1._async[op2.apiMethod].apply(this$1._async,args)}else{this$1._queueRunning=false}};doNextOp()}};return AsyncMirror2}(SynchronousFileSystem);AsyncMirror.Name="AsyncMirror";AsyncMirror.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var nativeMax=Math.max;function overRest$1(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}var breakLoop={};function noop(){}function once(fn){return function(){if(fn===null){return}var callFn=fn;fn=null;callFn.apply(this,arguments)}}var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index-1&&value%1==0&&value++numRun){switch(error.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){performOp(interceptCb)},timeoutDuration*1e3);break;default:cb.apply(null,arguments);break}}else{cb.apply(null,arguments)}};performOp(interceptCb)};CachedDropboxClient.prototype.getCachedInfo=function getCachedInfo(p){return this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.putCachedInfo=function putCachedInfo(p,cache){this._cache[p.toLowerCase()]=cache};CachedDropboxClient.prototype.deleteCachedInfo=function deleteCachedInfo(p){delete this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.getCachedDirInfo=function getCachedDirInfo(p){var info=this.getCachedInfo(p);if(isDirInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.getCachedFileInfo=function getCachedFileInfo(p){var info=this.getCachedInfo(p);if(isFileInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.updateCachedDirInfo=function updateCachedDirInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.contentHash!==null&&(cachedInfo===void 0||cachedInfo.stat.contentHash!==stat.contentHash)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedFileInfo=function updateCachedFileInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.versionTag!==null&&(cachedInfo===void 0||cachedInfo.stat.versionTag!==stat.versionTag)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedInfo=function updateCachedInfo(p,stat,contents){if(contents===void 0)contents=null;if(stat.isFile&&isArrayBuffer(contents)){this.updateCachedFileInfo(p,stat,contents)}else if(stat.isFolder&&Array.isArray(contents)){this.updateCachedDirInfo(p,stat,contents)}};var DropboxFile=function(PreloadFile$$1){function DropboxFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)DropboxFile2.__proto__=PreloadFile$$1;DropboxFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);DropboxFile2.prototype.constructor=DropboxFile2;DropboxFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){var buffer$$1=this.getBuffer(),arrayBuffer=buffer2ArrayBuffer(buffer$$1);this._fs._writeFileStrict(this.getPath(),arrayBuffer,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};DropboxFile2.prototype.close=function close(cb){this.sync(cb)};return DropboxFile2}(PreloadFile);var DropboxFileSystem=function(BaseFileSystem$$1){function DropboxFileSystem2(client,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._client=new CachedDropboxClient(client);deprecationMessage(deprecateMsg,DropboxFileSystem2.Name,{client:"authenticated dropbox client instance"});constructErrorCodeLookup()}if(BaseFileSystem$$1)DropboxFileSystem2.__proto__=BaseFileSystem$$1;DropboxFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);DropboxFileSystem2.prototype.constructor=DropboxFileSystem2;DropboxFileSystem2.Create=function Create(opts,cb){cb(null,new DropboxFileSystem2(opts.client,false))};DropboxFileSystem2.isAvailable=function isAvailable(){return typeof Dropbox!=="undefined"};DropboxFileSystem2.prototype.getName=function getName(){return DropboxFileSystem2.Name};DropboxFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};DropboxFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};DropboxFileSystem2.prototype.supportsProps=function supportsProps(){return false};DropboxFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};DropboxFileSystem2.prototype.empty=function empty(mainCb){var this$1=this;this._client.readdir("/",function(error,files){if(error){mainCb(this$1.convert(error,"/"))}else{var deleteFile2=function(file,cb){var p=path.join("/",file);this$1._client.remove(p,function(err){cb(err?this$1.convert(err,p):null)})};var finished=function(err){if(err){mainCb(err)}else{mainCb()}};eachLimit(files,deleteFile2,finished)}})};DropboxFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._client.move(oldPath,newPath,function(error){if(error){this$1._client.stat(newPath,function(error2,stat){if(error2||stat.isFolder){var missingPath=error.response.error.indexOf(oldPath)>-1?oldPath:newPath;cb(this$1.convert(error,missingPath))}else{this$1._client.remove(newPath,function(error22){if(error22){cb(this$1.convert(error22,newPath))}else{this$1.rename(oldPath,newPath,cb)}})}})}else{cb()}})};DropboxFileSystem2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;this._client.stat(path$$1,function(error,stat2){if(error){cb(this$1.convert(error,path$$1))}else if(stat2&&stat2.isRemoved){cb(ApiError.FileError(ErrorCode.ENOENT,path$$1))}else{var stats=new Stats(this$1._statType(stat2),stat2.size);return cb(null,stats)}})};DropboxFileSystem2.prototype.open=function open(path$$1,flags,mode,cb){var this$1=this;this._client.readFile(path$$1,function(error,content,dbStat){if(error){if(flags.isReadable()){cb(this$1.convert(error,path$$1))}else{switch(error.status){case Dropbox.ApiError.NOT_FOUND:var ab=new ArrayBuffer(0);return this$1._writeFileStrict(path$$1,ab,function(error2,stat){if(error2){cb(error2)}else{var file2=this$1._makeFile(path$$1,flags,stat,arrayBuffer2Buffer(ab));cb(null,file2)}});default:return cb(this$1.convert(error,path$$1))}}}else{var buffer$$1;if(content===null){buffer$$1=emptyBuffer()}else{buffer$$1=arrayBuffer2Buffer(content)}var file=this$1._makeFile(path$$1,flags,dbStat,buffer$$1);return cb(null,file)}})};DropboxFileSystem2.prototype._writeFileStrict=function _writeFileStrict(p,data,cb){var this$1=this;var parent=path.dirname(p);this.stat(parent,false,function(error,stat){if(error){cb(ApiError.FileError(ErrorCode.ENOENT,parent))}else{this$1._client.writeFile(p,data,function(error2,stat2){if(error2){cb(this$1.convert(error2,p))}else{cb(null,stat2)}})}})};DropboxFileSystem2.prototype._statType=function _statType(stat){return stat.isFile?FileType.FILE:FileType.DIRECTORY};DropboxFileSystem2.prototype._makeFile=function _makeFile(path$$1,flag,stat,buffer$$1){var type=this._statType(stat);var stats=new Stats(type,stat.size);return new DropboxFile(this,path$$1,flag,stats,buffer$$1)};DropboxFileSystem2.prototype._remove=function _remove(path$$1,cb,isFile){var this$1=this;this._client.stat(path$$1,function(error,stat){if(error){cb(this$1.convert(error,path$$1))}else{if(stat.isFile&&!isFile){cb(ApiError.FileError(ErrorCode.ENOTDIR,path$$1))}else if(!stat.isFile&&isFile){cb(ApiError.FileError(ErrorCode.EISDIR,path$$1))}else{this$1._client.remove(path$$1,function(error2){if(error2){cb(this$1.convert(error2,path$$1))}else{cb(null)}})}}})};DropboxFileSystem2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};DropboxFileSystem2.prototype.rmdir=function rmdir(path$$1,cb){this._remove(path$$1,cb,false)};DropboxFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;var parent=path.dirname(p);this._client.stat(parent,function(error,stat){if(error){cb(this$1.convert(error,parent))}else{this$1._client.mkdir(p,function(error2){if(error2){cb(ApiError.FileError(ErrorCode.EEXIST,p))}else{cb(null)}})}})};DropboxFileSystem2.prototype.readdir=function readdir(path$$1,cb){var this$1=this;this._client.readdir(path$$1,function(error,files){if(error){return cb(this$1.convert(error))}else{return cb(null,files)}})};DropboxFileSystem2.prototype.convert=function convert(err,path$$1){if(path$$1===void 0)path$$1=null;var errorCode=errorCodeLookup[err.status];if(errorCode===void 0){errorCode=ErrorCode.EIO}if(!path$$1){return new ApiError(errorCode)}else{return ApiError.FileError(errorCode,path$$1)}};return DropboxFileSystem2}(BaseFileSystem);DropboxFileSystem.Name="Dropbox";DropboxFileSystem.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(opt,cb){if(opt.isAuthenticated&&opt.isAuthenticated()){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}}};function convertError(e,path$$1){if(path$$1===void 0)path$$1="";var errno=e.errno;var parent=e.node;var paths=[];while(parent){paths.unshift(parent.name);if(parent===parent.parent){break}parent=parent.parent}return new ApiError(errno,ErrorStrings[errno],paths.length>0?"/"+paths.join("/"):path$$1)}var EmscriptenFile=function(BaseFile$$1){function EmscriptenFile2(_fs,_FS,_path,_stream){BaseFile$$1.call(this);this._fs=_fs;this._FS=_FS;this._path=_path;this._stream=_stream}if(BaseFile$$1)EmscriptenFile2.__proto__=BaseFile$$1;EmscriptenFile2.prototype=Object.create(BaseFile$$1&&BaseFile$$1.prototype);EmscriptenFile2.prototype.constructor=EmscriptenFile2;EmscriptenFile2.prototype.getPos=function getPos(){return void 0};EmscriptenFile2.prototype.close=function close(cb){var err=null;try{this.closeSync()}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.closeSync=function closeSync(){try{this._FS.close(this._stream)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.stat=function stat(cb){try{cb(null,this.statSync())}catch(e){cb(e)}};EmscriptenFile2.prototype.statSync=function statSync(){try{return this._fs.statSync(this._path,false)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.truncate=function truncate(len,cb){var err=null;try{this.truncateSync(len)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.truncateSync=function truncateSync(len){try{this._FS.ftruncate(this._stream.fd,len)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.write(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.read(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.sync=function sync(cb){cb()};EmscriptenFile2.prototype.syncSync=function syncSync(){};EmscriptenFile2.prototype.chown=function chown(uid,gid,cb){var err=null;try{this.chownSync(uid,gid)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chownSync=function chownSync(uid,gid){try{this._FS.fchown(this._stream.fd,uid,gid)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.chmod=function chmod(mode,cb){var err=null;try{this.chmodSync(mode)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chmodSync=function chmodSync(mode){try{this._FS.fchmod(this._stream.fd,mode)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.utimes=function utimes(atime,mtime,cb){var err=null;try{this.utimesSync(atime,mtime)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.utimesSync=function utimesSync(atime,mtime){this._fs.utimesSync(this._path,atime,mtime)};return EmscriptenFile2}(BaseFile);var EmscriptenFileSystem=function(SynchronousFileSystem$$1){function EmscriptenFileSystem2(_FS){SynchronousFileSystem$$1.call(this);this._FS=_FS}if(SynchronousFileSystem$$1)EmscriptenFileSystem2.__proto__=SynchronousFileSystem$$1;EmscriptenFileSystem2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);EmscriptenFileSystem2.prototype.constructor=EmscriptenFileSystem2;EmscriptenFileSystem2.Create=function Create(opts,cb){cb(null,new EmscriptenFileSystem2(opts.FS))};EmscriptenFileSystem2.isAvailable=function isAvailable(){return true};EmscriptenFileSystem2.prototype.getName=function getName(){return this._FS.DB_NAME()};EmscriptenFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};EmscriptenFileSystem2.prototype.supportsLinks=function supportsLinks(){return true};EmscriptenFileSystem2.prototype.supportsProps=function supportsProps(){return true};EmscriptenFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};EmscriptenFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){try{this._FS.rename(oldPath,newPath)}catch(e){if(e.errno===ErrorCode.ENOENT){throw convertError(e,this.existsSync(oldPath)?newPath:oldPath)}else{throw convertError(e)}}};EmscriptenFileSystem2.prototype.statSync=function statSync(p,isLstat){try{var stats=isLstat?this._FS.lstat(p):this._FS.stat(p);var itemType=this.modeToFileType(stats.mode);return new Stats(itemType,stats.size,stats.mode,stats.atime,stats.mtime,stats.ctime)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.openSync=function openSync(p,flag,mode){try{var stream=this._FS.open(p,flag.getFlagString(),mode);if(this._FS.isDir(stream.node.mode)){this._FS.close(stream);throw ApiError.EISDIR(p)}return new EmscriptenFile(this,this._FS,p,stream)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.unlinkSync=function unlinkSync(p){try{this._FS.unlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.rmdirSync=function rmdirSync(p){try{this._FS.rmdir(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){try{this._FS.mkdir(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readdirSync=function readdirSync(p){try{return this._FS.readdir(p).filter(function(p2){return p2!=="."&&p2!==".."})}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.truncateSync=function truncateSync(p,len){try{this._FS.truncate(p,len)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readFileSync=function readFileSync(p,encoding,flag){try{var data=this._FS.readFile(p,{flags:flag.getFlagString()});var buff=uint8Array2Buffer(data);if(encoding){return buff.toString(encoding)}else{return buff}}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.writeFileSync=function writeFileSync(p,data,encoding,flag,mode){try{if(encoding){data=Buffer2.from(data,encoding)}var u8=buffer2Uint8array(data);this._FS.writeFile(p,u8,{flags:flag.getFlagString(),encoding:"binary"});this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){try{isLchmod?this._FS.lchmod(p,mode):this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){try{isLchown?this._FS.lchown(p,uid,gid):this._FS.chown(p,uid,gid)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){try{this._FS.symlink(srcpath,dstpath)}catch(e){throw convertError(e)}};EmscriptenFileSystem2.prototype.readlinkSync=function readlinkSync(p){try{return this._FS.readlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.utimesSync=function utimesSync(p,atime,mtime){try{this._FS.utime(p,atime.getTime(),mtime.getTime())}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.modeToFileType=function modeToFileType(mode){if(this._FS.isDir(mode)){return FileType.DIRECTORY}else if(this._FS.isFile(mode)){return FileType.FILE}else if(this._FS.isLink(mode)){return FileType.SYMLINK}else{throw ApiError.EPERM("Invalid mode: "+mode)}};return EmscriptenFileSystem2}(SynchronousFileSystem);EmscriptenFileSystem.Name="EmscriptenFileSystem";EmscriptenFileSystem.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var FolderAdapter=function(BaseFileSystem$$1){function FolderAdapter2(folder,wrapped){BaseFileSystem$$1.call(this);this._folder=folder;this._wrapped=wrapped}if(BaseFileSystem$$1)FolderAdapter2.__proto__=BaseFileSystem$$1;FolderAdapter2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);FolderAdapter2.prototype.constructor=FolderAdapter2;FolderAdapter2.Create=function Create(opts,cb){cb(null,new FolderAdapter2(opts.folder,opts.wrapped))};FolderAdapter2.isAvailable=function isAvailable(){return true};FolderAdapter2.prototype.initialize=function initialize3(cb){var this$1=this;this._wrapped.exists(this._folder,function(exists2){if(exists2){cb()}else if(this$1._wrapped.isReadOnly()){cb(ApiError.ENOENT(this$1._folder))}else{this$1._wrapped.mkdir(this$1._folder,511,cb)}})};FolderAdapter2.prototype.getName=function getName(){return this._wrapped.getName()};FolderAdapter2.prototype.isReadOnly=function isReadOnly(){return this._wrapped.isReadOnly()};FolderAdapter2.prototype.supportsProps=function supportsProps(){return this._wrapped.supportsProps()};FolderAdapter2.prototype.supportsSynch=function supportsSynch(){return this._wrapped.supportsSynch()};FolderAdapter2.prototype.supportsLinks=function supportsLinks(){return false};return FolderAdapter2}(BaseFileSystem);FolderAdapter.Name="FolderAdapter";FolderAdapter.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}};function translateError(folder,e){if(e!==null&&typeof e==="object"){var err=e;var p=err.path;if(p){p="/"+path.relative(folder,p);err.message=err.message.replace(err.path,p);err.path=p}}return e}function wrapCallback(folder,cb){if(typeof cb==="function"){return function(err){if(arguments.length>0){arguments[0]=translateError(folder,err)}cb.apply(null,arguments)}}else{return cb}}function wrapFunction(name,wrapFirst,wrapSecond){if(name.slice(name.length-4)!=="Sync"){return function(){if(arguments.length>0){if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}arguments[arguments.length-1]=wrapCallback(this._folder,arguments[arguments.length-1])}return this._wrapped[name].apply(this._wrapped,arguments)}}else{return function(){try{if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}return this._wrapped[name].apply(this._wrapped,arguments)}catch(e){throw translateError(this._folder,e)}}}}["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,false)});["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,true)});var toExport;if(typeof window!=="undefined"){toExport=window}else if(typeof self!=="undefined"){toExport=self}else{toExport=global}var global$1=toExport;function isDirectoryEntry(entry){return entry.isDirectory}var _getFS=global$1.webkitRequestFileSystem||global$1.requestFileSystem||null;function _requestQuota(type,size,success,errorCallback){if(typeof navigator["webkitPersistentStorage"]!=="undefined"){switch(type){case global$1.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(size,success,errorCallback);break;case global$1.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(size,success,errorCallback);break;default:errorCallback(new TypeError("Invalid storage type: "+type));break}}else{global$1.webkitStorageInfo.requestQuota(type,size,success,errorCallback)}}function _toArray(list2){return Array.prototype.slice.call(list2||[],0)}function convertError$1(err,p,expectedDir){switch(err.name){case"PathExistsError":return ApiError.EEXIST(p);case"QuotaExceededError":return ApiError.FileError(ErrorCode.ENOSPC,p);case"NotFoundError":return ApiError.ENOENT(p);case"SecurityError":return ApiError.FileError(ErrorCode.EACCES,p);case"InvalidModificationError":return ApiError.FileError(ErrorCode.EPERM,p);case"TypeMismatchError":return ApiError.FileError(expectedDir?ErrorCode.ENOTDIR:ErrorCode.EISDIR,p);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return ApiError.FileError(ErrorCode.EINVAL,p)}}var HTML5FSFile=function(PreloadFile$$1){function HTML5FSFile2(fs4,entry,path$$1,flag,stat,contents){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,contents);this._entry=entry}if(PreloadFile$$1)HTML5FSFile2.__proto__=PreloadFile$$1;HTML5FSFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);HTML5FSFile2.prototype.constructor=HTML5FSFile2;HTML5FSFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){return cb()}this._entry.createWriter(function(writer){var buffer$$1=this$1.getBuffer();var blob=new Blob([buffer2ArrayBuffer(buffer$$1)]);var length=blob.size;writer.onwriteend=function(err){writer.onwriteend=null;writer.onerror=null;writer.truncate(length);this$1.resetDirty();cb()};writer.onerror=function(err){cb(convertError$1(err,this$1.getPath(),false))};writer.write(blob)})};HTML5FSFile2.prototype.close=function close(cb){this.sync(cb)};return HTML5FSFile2}(PreloadFile);var HTML5FS=function(BaseFileSystem$$1){function HTML5FS2(size,type,deprecateMsg){if(size===void 0)size=5;if(type===void 0)type=global$1.PERSISTENT;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this.size=1024*1024*size;this.type=type;deprecationMessage(deprecateMsg,HTML5FS2.Name,{size,type})}if(BaseFileSystem$$1)HTML5FS2.__proto__=BaseFileSystem$$1;HTML5FS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);HTML5FS2.prototype.constructor=HTML5FS2;HTML5FS2.Create=function Create(opts,cb){var fs4=new HTML5FS2(opts.size,opts.type,false);fs4.allocate(function(e){return e?cb(e):cb(null,fs4)},false)};HTML5FS2.isAvailable=function isAvailable(){return!!_getFS};HTML5FS2.prototype.getName=function getName(){return HTML5FS2.Name};HTML5FS2.prototype.isReadOnly=function isReadOnly(){return false};HTML5FS2.prototype.supportsSymlinks=function supportsSymlinks(){return false};HTML5FS2.prototype.supportsProps=function supportsProps(){return false};HTML5FS2.prototype.supportsSynch=function supportsSynch(){return false};HTML5FS2.prototype.allocate=function allocate(cb,deprecateMsg){var this$1=this;if(cb===void 0)cb=function(){};if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.")}var success=function(fs4){this$1.fs=fs4;cb()};var error=function(err){cb(convertError$1(err,"/",true))};if(this.type===global$1.PERSISTENT){_requestQuota(this.type,this.size,function(granted){_getFS(this$1.type,granted,success,error)},error)}else{_getFS(this.type,this.size,success,error)}};HTML5FS2.prototype.empty=function empty(mainCb){this._readdir("/",function(err,entries){if(err){console.error("Failed to empty FS");mainCb(err)}else{var finished=function(er){if(err){console.error("Failed to empty FS");mainCb(err)}else{mainCb()}};var deleteEntry=function(entry,cb){var succ=function(){cb()};var error=function(err2){cb(convertError$1(err2,entry.fullPath,!entry.isDirectory))};if(isDirectoryEntry(entry)){entry.removeRecursively(succ,error)}else{entry.remove(succ,error)}};eachLimit(entries,deleteEntry,finished)}})};HTML5FS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var semaphore=2;var successCount=0;var root2=this.fs.root;var currentPath=oldPath;var error=function(err){if(--semaphore<=0){cb(convertError$1(err,currentPath,false))}};var success=function(file){if(++successCount===2){return cb(new ApiError(ErrorCode.EINVAL,"Something was identified as both a file and a directory. This should never happen."))}if(oldPath===newPath){return cb()}currentPath=path.dirname(newPath);root2.getDirectory(currentPath,{},function(parentDir){currentPath=path.basename(newPath);file.moveTo(parentDir,currentPath,function(entry){cb()},function(err){if(file.isDirectory){currentPath=newPath;this$1.unlink(newPath,function(e){if(e){error(err)}else{this$1.rename(oldPath,newPath,cb)}})}else{error(err)}})},error)};root2.getFile(oldPath,{},success,error);root2.getDirectory(oldPath,{},success,error)};HTML5FS2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;var opts={create:false};var loadAsFile=function(entry){var fileFromEntry=function(file){var stat2=new Stats(FileType.FILE,file.size);cb(null,stat2)};entry.file(fileFromEntry,failedToLoad)};var loadAsDir=function(dir$$1){var size=4096;var stat2=new Stats(FileType.DIRECTORY,size);cb(null,stat2)};var failedToLoad=function(err){cb(convertError$1(err,path$$1,false))};var failedToLoadAsFile=function(){this$1.fs.root.getDirectory(path$$1,opts,loadAsDir,failedToLoad)};this.fs.root.getFile(path$$1,opts,loadAsFile,failedToLoadAsFile)};HTML5FS2.prototype.open=function open(p,flags,mode,cb){var this$1=this;var error=function(err){if(err.name==="InvalidModificationError"&&flags.isExclusive()){cb(ApiError.EEXIST(p))}else{cb(convertError$1(err,p,false))}};this.fs.root.getFile(p,{create:flags.pathNotExistsAction()===ActionType.CREATE_FILE,exclusive:flags.isExclusive()},function(entry){entry.file(function(file){var reader=new FileReader;reader.onloadend=function(event){var bfsFile=this$1._makeFile(p,entry,flags,file,reader.result);cb(null,bfsFile)};reader.onerror=function(ev){error(reader.error)};reader.readAsArrayBuffer(file)},error)},error)};HTML5FS2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};HTML5FS2.prototype.rmdir=function rmdir(path$$1,cb){var this$1=this;this.readdir(path$$1,function(e,files){if(e){cb(e)}else if(files.length>0){cb(ApiError.ENOTEMPTY(path$$1))}else{this$1._remove(path$$1,cb,false)}})};HTML5FS2.prototype.mkdir=function mkdir(path$$1,mode,cb){var opts={create:true,exclusive:true};var success=function(dir$$1){cb()};var error=function(err){cb(convertError$1(err,path$$1,true))};this.fs.root.getDirectory(path$$1,opts,success,error)};HTML5FS2.prototype.readdir=function readdir(path$$1,cb){this._readdir(path$$1,function(e,entries){if(entries){var rv=[];for(var i2=0,list2=entries;i20){throw ApiError.ENOTEMPTY(p)}else{this.removeEntry(p,true)}};SyncKeyValueFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data)};SyncKeyValueFileSystem2.prototype.readdirSync=function readdirSync(p){var tx=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(tx,p,this.findINode(tx,p)))};SyncKeyValueFileSystem2.prototype._syncSync=function _syncSync(p,data,stats){var tx=this.store.beginTransaction("readwrite"),fileInodeId=this._findINode(tx,path.dirname(p),path.basename(p)),fileInode=this.getINode(tx,p,fileInodeId),inodeChanged=fileInode.update(stats);try{tx.put(fileInode.id,data,true);if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true)}}catch(e){tx.abort();throw e}tx.commit()};SyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(){var tx=this.store.beginTransaction("readwrite");if(tx.get(ROOT_NODE_ID)===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false);tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false);tx.commit()}};SyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename){var this$1=this;var readDirectory=function(inode){var dirList=this$1.getDirListing(tx,parent,inode);if(dirList[filename]){return dirList[filename]}else{throw ApiError.ENOENT(path.resolve(parent,filename))}};if(parent==="/"){if(filename===""){return ROOT_NODE_ID}else{return readDirectory(this.getINode(tx,parent,ROOT_NODE_ID))}}else{return readDirectory(this.getINode(tx,parent+path.sep+filename,this._findINode(tx,path.dirname(parent),path.basename(parent))))}};SyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p){return this.getINode(tx,p,this._findINode(tx,path.dirname(p),path.basename(p)))};SyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id){var inode=tx.get(id);if(inode===void 0){throw ApiError.ENOENT(p)}return Inode.fromBuffer(inode)};SyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode){if(!inode.isDirectory()){throw ApiError.ENOTDIR(p)}var data=tx.get(inode.id);if(data===void 0){throw ApiError.ENOENT(p)}return JSON.parse(data.toString())};SyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data){var retries=0;var currId;while(retries<5){try{currId=GenerateRandomID();tx.put(currId,data,false);return currId}catch(e){}}throw new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store.")};SyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data){var parentDir=path.dirname(p),fname=path.basename(p),parentNode=this.findINode(tx,parentDir),dirListing=this.getDirListing(tx,parentDir,parentNode),currTime=new Date().getTime();if(p==="/"){throw ApiError.EEXIST(p)}if(dirListing[fname]){throw ApiError.EEXIST(p)}var fileNode;try{var dataId=this.addNewNode(tx,data);fileNode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);var fileNodeId=this.addNewNode(tx,fileNode.toBuffer());dirListing[fname]=fileNodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true)}catch(e){tx.abort();throw e}tx.commit();return fileNode};SyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir){var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),parentNode=this.findINode(tx,parent),parentListing=this.getDirListing(tx,parent,parentNode),fileName=path.basename(p);if(!parentListing[fileName]){throw ApiError.ENOENT(p)}var fileNodeId=parentListing[fileName];delete parentListing[fileName];var fileNode=this.getINode(tx,p,fileNodeId);if(!isDir&&fileNode.isDirectory()){throw ApiError.EISDIR(p)}else if(isDir&&!fileNode.isDirectory()){throw ApiError.ENOTDIR(p)}try{tx.del(fileNode.id);tx.del(fileNodeId);tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true)}catch(e){tx.abort();throw e}tx.commit()};return SyncKeyValueFileSystem2}(SynchronousFileSystem);var AsyncKeyValueFile=function(PreloadFile$$1){function AsyncKeyValueFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)AsyncKeyValueFile2.__proto__=PreloadFile$$1;AsyncKeyValueFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);AsyncKeyValueFile2.prototype.constructor=AsyncKeyValueFile2;AsyncKeyValueFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};AsyncKeyValueFile2.prototype.close=function close(cb){this.sync(cb)};return AsyncKeyValueFile2}(PreloadFile);var AsyncKeyValueFileSystem=function(BaseFileSystem$$1){function AsyncKeyValueFileSystem2(){BaseFileSystem$$1.apply(this,arguments)}if(BaseFileSystem$$1)AsyncKeyValueFileSystem2.__proto__=BaseFileSystem$$1;AsyncKeyValueFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);AsyncKeyValueFileSystem2.prototype.constructor=AsyncKeyValueFileSystem2;AsyncKeyValueFileSystem2.isAvailable=function isAvailable(){return true};AsyncKeyValueFileSystem2.prototype.init=function init(store,cb){this.store=store;this.makeRootDirectory(cb)};AsyncKeyValueFileSystem2.prototype.getName=function getName(){return this.store.name()};AsyncKeyValueFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};AsyncKeyValueFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};AsyncKeyValueFileSystem2.prototype.supportsProps=function supportsProps(){return false};AsyncKeyValueFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};AsyncKeyValueFileSystem2.prototype.empty=function empty(cb){var this$1=this;this.store.clear(function(e){if(noError(e,cb)){this$1.makeRootDirectory(cb)}})};AsyncKeyValueFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");var oldParent=path.dirname(oldPath),oldName=path.basename(oldPath);var newParent=path.dirname(newPath),newName=path.basename(newPath);var inodes={};var lists={};var errorOccurred=false;if((newParent+"/").indexOf(oldPath+"/")===0){return cb(new ApiError(ErrorCode.EBUSY,oldParent))}var theOleSwitcharoo=function(){if(errorOccurred||!lists.hasOwnProperty(oldParent)||!lists.hasOwnProperty(newParent)){return}var oldParentList=lists[oldParent],oldParentINode=inodes[oldParent],newParentList=lists[newParent],newParentINode=inodes[newParent];if(!oldParentList[oldName]){cb(ApiError.ENOENT(oldPath))}else{var fileId=oldParentList[oldName];delete oldParentList[oldName];var completeRename=function(){newParentList[newName]=fileId;tx.put(oldParentINode.id,Buffer2.from(JSON.stringify(oldParentList)),true,function(e){if(noErrorTx(e,tx,cb)){if(oldParent===newParent){tx.commit(cb)}else{tx.put(newParentINode.id,Buffer2.from(JSON.stringify(newParentList)),true,function(e2){if(noErrorTx(e2,tx,cb)){tx.commit(cb)}})}}})};if(newParentList[newName]){this$1.getINode(tx,newPath,newParentList[newName],function(e,inode){if(noErrorTx(e,tx,cb)){if(inode.isFile()){tx.del(inode.id,function(e2){if(noErrorTx(e2,tx,cb)){tx.del(newParentList[newName],function(e3){if(noErrorTx(e3,tx,cb)){completeRename()}})}})}else{tx.abort(function(e2){cb(ApiError.EPERM(newPath))})}}})}else{completeRename()}}};var processInodeAndListings=function(p){this$1.findINodeAndDirListing(tx,p,function(e,node,dirList){if(e){if(!errorOccurred){errorOccurred=true;tx.abort(function(){cb(e)})}}else{inodes[p]=node;lists[p]=dirList;theOleSwitcharoo()}})};processInodeAndListings(oldParent);if(oldParent!==newParent){processInodeAndListings(newParent)}};AsyncKeyValueFileSystem2.prototype.stat=function stat(p,isLstat,cb){var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){cb(null,inode.toStats())}})};AsyncKeyValueFileSystem2.prototype.createFile=function createFile(p,flag,mode,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),data=emptyBuffer();this.commitNewFile(tx,p,FileType.FILE,mode,data,function(e,newFile){if(noError(e,cb)){cb(null,new AsyncKeyValueFile(this$1,p,flag,newFile.toStats(),data))}})};AsyncKeyValueFileSystem2.prototype.openFile=function openFile(p,flag,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){tx.get(inode.id,function(e2,data){if(noError(e2,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,new AsyncKeyValueFile(this$1,p,flag,inode.toStats(),data))}}})}})};AsyncKeyValueFileSystem2.prototype.unlink=function unlink(p,cb){this.removeEntry(p,false,cb)};AsyncKeyValueFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;this.readdir(p,function(err,files){if(err){cb(err)}else if(files.length>0){cb(ApiError.ENOTEMPTY(p))}else{this$1.removeEntry(p,true,cb)}})};AsyncKeyValueFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data,cb)};AsyncKeyValueFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,dirListing){if(noError(e2,cb)){cb(null,Object.keys(dirListing))}})}})};AsyncKeyValueFileSystem2.prototype._sync=function _sync(p,data,stats,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");this._findINode(tx,path.dirname(p),path.basename(p),function(e,fileInodeId){if(noErrorTx(e,tx,cb)){this$1.getINode(tx,p,fileInodeId,function(e2,fileInode){if(noErrorTx(e2,tx,cb)){var inodeChanged=fileInode.update(stats);tx.put(fileInode.id,data,true,function(e3){if(noErrorTx(e3,tx,cb)){if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(cb)}})}else{tx.commit(cb)}}})}})}})};AsyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(cb){var tx=this.store.beginTransaction("readwrite");tx.get(ROOT_NODE_ID,function(e,data){if(e||data===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false,function(e2){if(noErrorTx(e2,tx,cb)){tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false,function(e3){if(e3){tx.abort(function(){cb(e3)})}else{tx.commit(cb)}})}})}else{tx.commit(cb)}})};AsyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename,cb){var this$1=this;var handleDirectoryListings=function(e,inode,dirList){if(e){cb(e)}else if(dirList[filename]){cb(null,dirList[filename])}else{cb(ApiError.ENOENT(path.resolve(parent,filename)))}};if(parent==="/"){if(filename===""){cb(null,ROOT_NODE_ID)}else{this.getINode(tx,parent,ROOT_NODE_ID,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,parent,inode,function(e2,dirList){handleDirectoryListings(e2,inode,dirList)})}})}}else{this.findINodeAndDirListing(tx,parent,handleDirectoryListings)}};AsyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p,cb){var this$1=this;this._findINode(tx,path.dirname(p),path.basename(p),function(e,id){if(noError(e,cb)){this$1.getINode(tx,p,id,cb)}})};AsyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id,cb){tx.get(id,function(e,data){if(noError(e,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,Inode.fromBuffer(data))}}})};AsyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode,cb){if(!inode.isDirectory()){cb(ApiError.ENOTDIR(p))}else{tx.get(inode.id,function(e,data){if(noError(e,cb)){try{cb(null,JSON.parse(data.toString()))}catch(e2){cb(ApiError.ENOENT(p))}}})}};AsyncKeyValueFileSystem2.prototype.findINodeAndDirListing=function findINodeAndDirListing(tx,p,cb){var this$1=this;this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,listing){if(noError(e2,cb)){cb(null,inode,listing)}})}})};AsyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data,cb){var retries=0,currId;var reroll=function(){if(++retries===5){cb(new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store."))}else{currId=GenerateRandomID();tx.put(currId,data,false,function(e,committed){if(e||!committed){reroll()}else{cb(null,currId)}})}};reroll()};AsyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data,cb){var this$1=this;var parentDir=path.dirname(p),fname=path.basename(p),currTime=new Date().getTime();if(p==="/"){return cb(ApiError.EEXIST(p))}this.findINodeAndDirListing(tx,parentDir,function(e,parentNode,dirListing){if(noErrorTx(e,tx,cb)){if(dirListing[fname]){tx.abort(function(){cb(ApiError.EEXIST(p))})}else{this$1.addNewNode(tx,data,function(e2,dataId){if(noErrorTx(e2,tx,cb)){var fileInode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);this$1.addNewNode(tx,fileInode.toBuffer(),function(e3,fileInodeId){if(noErrorTx(e3,tx,cb)){dirListing[fname]=fileInodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(function(e5){if(noErrorTx(e5,tx,cb)){cb(null,fileInode)}})}})}})}})}}})};AsyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),fileName=path.basename(p);this.findINodeAndDirListing(tx,parent,function(e,parentNode,parentListing){if(noErrorTx(e,tx,cb)){if(!parentListing[fileName]){tx.abort(function(){cb(ApiError.ENOENT(p))})}else{var fileNodeId=parentListing[fileName];delete parentListing[fileName];this$1.getINode(tx,p,fileNodeId,function(e2,fileNode){if(noErrorTx(e2,tx,cb)){if(!isDir&&fileNode.isDirectory()){tx.abort(function(){cb(ApiError.EISDIR(p))})}else if(isDir&&!fileNode.isDirectory()){tx.abort(function(){cb(ApiError.ENOTDIR(p))})}else{tx.del(fileNode.id,function(e3){if(noErrorTx(e3,tx,cb)){tx.del(fileNodeId,function(e4){if(noErrorTx(e4,tx,cb)){tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true,function(e5){if(noErrorTx(e5,tx,cb)){tx.commit(cb)}})}})}})}}})}}})};return AsyncKeyValueFileSystem2}(BaseFileSystem);var InMemoryStore=function InMemoryStore2(){this.store={}};InMemoryStore.prototype.name=function name(){return InMemoryFileSystem.Name};InMemoryStore.prototype.clear=function clear(){this.store={}};InMemoryStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};InMemoryStore.prototype.get=function get(key){return this.store[key]};InMemoryStore.prototype.put=function put(key,data,overwrite){if(!overwrite&&this.store.hasOwnProperty(key)){return false}this.store[key]=data;return true};InMemoryStore.prototype.del=function del(key){delete this.store[key]};var InMemoryFileSystem=function(SyncKeyValueFileSystem$$1){function InMemoryFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new InMemoryStore})}if(SyncKeyValueFileSystem$$1)InMemoryFileSystem2.__proto__=SyncKeyValueFileSystem$$1;InMemoryFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);InMemoryFileSystem2.prototype.constructor=InMemoryFileSystem2;InMemoryFileSystem2.Create=function Create(options,cb){cb(null,new InMemoryFileSystem2)};return InMemoryFileSystem2}(SyncKeyValueFileSystem);InMemoryFileSystem.Name="InMemory";InMemoryFileSystem.Options={};var indexedDB=global$1.indexedDB||global$1.mozIndexedDB||global$1.webkitIndexedDB||global$1.msIndexedDB;function convertError$2(e,message){if(message===void 0)message=e.toString();switch(e.name){case"NotFoundError":return new ApiError(ErrorCode.ENOENT,message);case"QuotaExceededError":return new ApiError(ErrorCode.ENOSPC,message);default:return new ApiError(ErrorCode.EIO,message)}}function onErrorHandler(cb,code,message){if(code===void 0)code=ErrorCode.EIO;if(message===void 0)message=null;return function(e){e.preventDefault();cb(new ApiError(code,message!==null?message:void 0))}}var IndexedDBROTransaction=function IndexedDBROTransaction2(tx,store){this.tx=tx;this.store=store};IndexedDBROTransaction.prototype.get=function get(key,cb){try{var r=this.store.get(key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){var result=event.target.result;if(result===void 0){cb(null,result)}else{cb(null,arrayBuffer2Buffer(result))}}}catch(e){cb(convertError$2(e))}};var IndexedDBRWTransaction=function(IndexedDBROTransaction2){function IndexedDBRWTransaction2(tx,store){IndexedDBROTransaction2.call(this,tx,store)}if(IndexedDBROTransaction2)IndexedDBRWTransaction2.__proto__=IndexedDBROTransaction2;IndexedDBRWTransaction2.prototype=Object.create(IndexedDBROTransaction2&&IndexedDBROTransaction2.prototype);IndexedDBRWTransaction2.prototype.constructor=IndexedDBRWTransaction2;IndexedDBRWTransaction2.prototype.put=function put(key,data,overwrite,cb){try{var arraybuffer=buffer2ArrayBuffer(data);var r;if(overwrite){r=this.store.put(arraybuffer,key)}else{r=this.store.add(arraybuffer,key)}r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb(null,true)}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.del=function del(key,cb){try{var r=this.store["delete"](key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb()}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.commit=function commit(cb){setTimeout(cb,0)};IndexedDBRWTransaction2.prototype.abort=function abort(cb){var _e=null;try{this.tx.abort()}catch(e){_e=convertError$2(e)}finally{cb(_e)}};return IndexedDBRWTransaction2}(IndexedDBROTransaction);var IndexedDBStore=function IndexedDBStore2(cb,storeName){var this$1=this;if(storeName===void 0)storeName="browserfs";this.storeName=storeName;var openReq=indexedDB.open(this.storeName,1);openReq.onupgradeneeded=function(event){var db=event.target.result;if(db.objectStoreNames.contains(this$1.storeName)){db.deleteObjectStore(this$1.storeName)}db.createObjectStore(this$1.storeName)};openReq.onsuccess=function(event){this$1.db=event.target.result;cb(null,this$1)};openReq.onerror=onErrorHandler(cb,ErrorCode.EACCES)};IndexedDBStore.prototype.name=function name(){return IndexedDBFileSystem.Name+" - "+this.storeName};IndexedDBStore.prototype.clear=function clear(cb){try{var tx=this.db.transaction(this.storeName,"readwrite"),objectStore=tx.objectStore(this.storeName),r=objectStore.clear();r.onsuccess=function(event){setTimeout(cb,0)};r.onerror=onErrorHandler(cb)}catch(e){cb(convertError$2(e))}};IndexedDBStore.prototype.beginTransaction=function beginTransaction(type){if(type===void 0)type="readonly";var tx=this.db.transaction(this.storeName,type),objectStore=tx.objectStore(this.storeName);if(type==="readwrite"){return new IndexedDBRWTransaction(tx,objectStore)}else if(type==="readonly"){return new IndexedDBROTransaction(tx,objectStore)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid transaction type.")}};var IndexedDBFileSystem=function(AsyncKeyValueFileSystem$$1){function IndexedDBFileSystem2(cb,storeName,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;AsyncKeyValueFileSystem$$1.call(this);this.store=new IndexedDBStore(function(e){if(e){cb(e)}else{this$1.init(this$1.store,function(e2){cb(e2,this$1)})}},storeName);deprecationMessage(deprecateMsg,IndexedDBFileSystem2.Name,{storeName})}if(AsyncKeyValueFileSystem$$1)IndexedDBFileSystem2.__proto__=AsyncKeyValueFileSystem$$1;IndexedDBFileSystem2.prototype=Object.create(AsyncKeyValueFileSystem$$1&&AsyncKeyValueFileSystem$$1.prototype);IndexedDBFileSystem2.prototype.constructor=IndexedDBFileSystem2;IndexedDBFileSystem2.Create=function Create(opts,cb){new IndexedDBFileSystem2(cb,opts.storeName,false)};IndexedDBFileSystem2.isAvailable=function isAvailable(){try{return typeof indexedDB!=="undefined"&&null!==indexedDB.open("__browserfs_test__")}catch(e){return false}};return IndexedDBFileSystem2}(AsyncKeyValueFileSystem);IndexedDBFileSystem.Name="IndexedDB";IndexedDBFileSystem.Options={storeName:{type:"string",optional:true,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var supportsBinaryString=false;var binaryEncoding;try{global$1.localStorage.setItem("__test__",String.fromCharCode(55296));supportsBinaryString=global$1.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(e){supportsBinaryString=false}binaryEncoding=supportsBinaryString?"binary_string":"binary_string_ie";if(!Buffer2.isEncoding(binaryEncoding)){binaryEncoding="base64"}var LocalStorageStore=function LocalStorageStore2(){};LocalStorageStore.prototype.name=function name(){return LocalStorageFileSystem.Name};LocalStorageStore.prototype.clear=function clear(){global$1.localStorage.clear()};LocalStorageStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};LocalStorageStore.prototype.get=function get(key){try{var data=global$1.localStorage.getItem(key);if(data!==null){return Buffer2.from(data,binaryEncoding)}}catch(e){}return void 0};LocalStorageStore.prototype.put=function put(key,data,overwrite){try{if(!overwrite&&global$1.localStorage.getItem(key)!==null){return false}global$1.localStorage.setItem(key,data.toString(binaryEncoding));return true}catch(e){throw new ApiError(ErrorCode.ENOSPC,"LocalStorage is full.")}};LocalStorageStore.prototype.del=function del(key){try{global$1.localStorage.removeItem(key)}catch(e){throw new ApiError(ErrorCode.EIO,"Unable to delete key "+key+": "+e)}};var LocalStorageFileSystem=function(SyncKeyValueFileSystem$$1){function LocalStorageFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new LocalStorageStore})}if(SyncKeyValueFileSystem$$1)LocalStorageFileSystem2.__proto__=SyncKeyValueFileSystem$$1;LocalStorageFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);LocalStorageFileSystem2.prototype.constructor=LocalStorageFileSystem2;LocalStorageFileSystem2.Create=function Create(options,cb){cb(null,new LocalStorageFileSystem2)};LocalStorageFileSystem2.isAvailable=function isAvailable(){return typeof global$1.localStorage!=="undefined"};return LocalStorageFileSystem2}(SyncKeyValueFileSystem);LocalStorageFileSystem.Name="LocalStorage";LocalStorageFileSystem.Options={};var MountableFileSystem=function(BaseFileSystem$$1){function MountableFileSystem2(){BaseFileSystem$$1.call(this);this.mountList=[];this.mntMap={};this.rootFs=new InMemoryFileSystem}if(BaseFileSystem$$1)MountableFileSystem2.__proto__=BaseFileSystem$$1;MountableFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);MountableFileSystem2.prototype.constructor=MountableFileSystem2;MountableFileSystem2.Create=function Create(opts,cb){var fs4=new MountableFileSystem2;Object.keys(opts).forEach(function(mountPoint){fs4.mount(mountPoint,opts[mountPoint])});cb(null,fs4)};MountableFileSystem2.isAvailable=function isAvailable(){return true};MountableFileSystem2.prototype.mount=function mount(mountPoint,fs4){if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already taken.")}mkdirpSync(mountPoint,511,this.rootFs);this.mntMap[mountPoint]=fs4;this.mountList.push(mountPoint);this.mountList=this.mountList.sort(function(a,b){return b.length-a.length})};MountableFileSystem2.prototype.umount=function umount(mountPoint){var this$1=this;if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(!this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already unmounted.")}delete this.mntMap[mountPoint];this.mountList.splice(this.mountList.indexOf(mountPoint),1);while(mountPoint!=="/"){if(this$1.rootFs.readdirSync(mountPoint).length===0){this$1.rootFs.rmdirSync(mountPoint);mountPoint=path.dirname(mountPoint)}else{break}}};MountableFileSystem2.prototype._getFs=function _getFs(path$$1){var this$1=this;var mountList=this.mountList,len=mountList.length;for(var i2=0;i21?mountPoint.length:0);if(path$$1===""){path$$1="/"}return{fs:this$1.mntMap[mountPoint],path:path$$1}}}return{fs:this.rootFs,path:path$$1}};MountableFileSystem2.prototype.getName=function getName(){return MountableFileSystem2.Name};MountableFileSystem2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};MountableFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};MountableFileSystem2.prototype.supportsLinks=function supportsLinks(){return false};MountableFileSystem2.prototype.supportsProps=function supportsProps(){return false};MountableFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};MountableFileSystem2.prototype.standardizeError=function standardizeError(err,path$$1,realPath){var index=err.message.indexOf(path$$1);if(index!==-1){err.message=err.message.substr(0,index)+realPath+err.message.substr(index+path$$1.length);err.path=realPath}return err};MountableFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){return fs1rv.fs.rename(fs1rv.path,fs2rv.path,function(e){if(e){this$1.standardizeError(this$1.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath)}cb(e)})}return _fsMock.readFile(oldPath,function(err,data){if(err){return cb(err)}_fsMock.writeFile(newPath,data,function(err2){if(err2){return cb(err2)}_fsMock.unlink(oldPath,cb)})})};MountableFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){try{return fs1rv.fs.renameSync(fs1rv.path,fs2rv.path)}catch(e){this.standardizeError(this.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath);throw e}}var data=_fsMock.readFileSync(oldPath);_fsMock.writeFileSync(newPath,data);return _fsMock.unlinkSync(oldPath)};MountableFileSystem2.prototype.readdirSync=function readdirSync(p){var fsInfo=this._getFs(p);var rv=null;if(fsInfo.fs!==this.rootFs){try{rv=this.rootFs.readdirSync(p)}catch(e){}}try{var rv2=fsInfo.fs.readdirSync(fsInfo.path);if(rv===null){return rv2}else{return rv2.concat(rv.filter(function(val){return rv2.indexOf(val)===-1}))}}catch(e){if(rv===null){throw this.standardizeError(e,fsInfo.path,p)}else{return rv}}};MountableFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);fsInfo.fs.readdir(fsInfo.path,function(err,files){if(fsInfo.fs!==this$1.rootFs){try{var rv=this$1.rootFs.readdirSync(p);if(files){files=files.concat(rv.filter(function(val){return files.indexOf(val)===-1}))}else{files=rv}}catch(e){if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}}}else if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}cb(null,files)})};MountableFileSystem2.prototype.rmdirSync=function rmdirSync(p){var fsInfo=this._getFs(p);if(this._containsMountPt(p)){throw ApiError.ENOTEMPTY(p)}else{try{fsInfo.fs.rmdirSync(fsInfo.path)}catch(e){throw this.standardizeError(e,fsInfo.path,p)}}};MountableFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);if(this._containsMountPt(p)){cb(ApiError.ENOTEMPTY(p))}else{fsInfo.fs.rmdir(fsInfo.path,function(err){cb(err?this$1.standardizeError(err,fsInfo.path,p):null)})}};MountableFileSystem2.prototype._containsMountPt=function _containsMountPt(p){var mountPoints=this.mountList,len=mountPoints.length;for(var i2=0;i2=p.length&&pt.slice(0,p.length)===p){return true}}return false};return MountableFileSystem2}(BaseFileSystem);MountableFileSystem.Name="MountableFileSystem";MountableFileSystem.Options={};function defineFcn(name,isSync,numArgs){if(isSync){return function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;try{return rv.fs[name].apply(rv.fs,args)}catch(e){this.standardizeError(e,rv.path,path$$1);throw e}}}else{return function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;if(typeof args[args.length-1]==="function"){var cb=args[args.length-1];args[args.length-1]=function(){var args2=[],len2=arguments.length;while(len2--)args2[len2]=arguments[len2];if(args2.length>0&&args2[0]instanceof ApiError){this$1.standardizeError(args2[0],rv.path,path$$1)}cb.apply(null,args2)}}return rv.fs[name].apply(rv.fs,args)}}}var fsCmdMap=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]];for(var i=0;i0){var fn=timeouts.shift();return fn()}}};if(gScope.addEventListener){gScope.addEventListener("message",handleMessage,true)}else{gScope.attachEvent("onmessage",handleMessage)}}else if(gScope.MessageChannel){var channel=new gScope.MessageChannel;channel.port1.onmessage=function(event){if(timeouts.length>0){return timeouts.shift()()}};bfsSetImmediate=function(fn){timeouts.push(fn);channel.port2.postMessage("")}}else{bfsSetImmediate=function(fn){return setTimeout(fn,0)}}}var setImmediate$3=bfsSetImmediate;var Mutex=function Mutex2(){this._locked=false;this._waiters=[]};Mutex.prototype.lock=function lock(cb){if(this._locked){this._waiters.push(cb);return}this._locked=true;cb()};Mutex.prototype.unlock=function unlock(){if(!this._locked){throw new Error("unlock of a non-locked mutex")}var next=this._waiters.shift();if(next){setImmediate$3(next);return}this._locked=false};Mutex.prototype.tryLock=function tryLock(){if(this._locked){return false}this._locked=true;return true};Mutex.prototype.isLocked=function isLocked(){return this._locked};var LockedFS=function LockedFS2(fs4){this._fs=fs4;this._mu=new Mutex};LockedFS.prototype.getName=function getName(){return"LockedFS<"+this._fs.getName()+">"};LockedFS.prototype.getFSUnlocked=function getFSUnlocked(){return this._fs};LockedFS.prototype.initialize=function initialize3(cb){this._fs.initialize(cb)};LockedFS.prototype.diskSpace=function diskSpace(p,cb){this._fs.diskSpace(p,cb)};LockedFS.prototype.isReadOnly=function isReadOnly(){return this._fs.isReadOnly()};LockedFS.prototype.supportsLinks=function supportsLinks(){return this._fs.supportsLinks()};LockedFS.prototype.supportsProps=function supportsProps(){return this._fs.supportsProps()};LockedFS.prototype.supportsSynch=function supportsSynch(){return this._fs.supportsSynch()};LockedFS.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rename(oldPath,newPath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.renameSync=function renameSync(oldPath,newPath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.renameSync(oldPath,newPath)};LockedFS.prototype.stat=function stat(p,isLstat,cb){var this$1=this;this._mu.lock(function(){this$1._fs.stat(p,isLstat,function(err,stat2){this$1._mu.unlock();cb(err,stat2)})})};LockedFS.prototype.statSync=function statSync(p,isLstat){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.statSync(p,isLstat)};LockedFS.prototype.open=function open(p,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.open(p,flag,mode,function(err,fd){this$1._mu.unlock();cb(err,fd)})})};LockedFS.prototype.openSync=function openSync(p,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.openSync(p,flag,mode)};LockedFS.prototype.unlink=function unlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.unlink(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.unlinkSync=function unlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.unlinkSync(p)};LockedFS.prototype.rmdir=function rmdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rmdir(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.rmdirSync=function rmdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.rmdirSync(p)};LockedFS.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.mkdir(p,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.mkdirSync=function mkdirSync(p,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.mkdirSync(p,mode)};LockedFS.prototype.readdir=function readdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readdir(p,function(err,files){this$1._mu.unlock();cb(err,files)})})};LockedFS.prototype.readdirSync=function readdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readdirSync(p)};LockedFS.prototype.exists=function exists2(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.exists(p,function(exists3){this$1._mu.unlock();cb(exists3)})})};LockedFS.prototype.existsSync=function existsSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.existsSync(p)};LockedFS.prototype.realpath=function realpath(p,cache,cb){var this$1=this;this._mu.lock(function(){this$1._fs.realpath(p,cache,function(err,resolvedPath){this$1._mu.unlock();cb(err,resolvedPath)})})};LockedFS.prototype.realpathSync=function realpathSync(p,cache){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.realpathSync(p,cache)};LockedFS.prototype.truncate=function truncate(p,len,cb){var this$1=this;this._mu.lock(function(){this$1._fs.truncate(p,len,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.truncateSync=function truncateSync(p,len){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.truncateSync(p,len)};LockedFS.prototype.readFile=function readFile2(fname,encoding,flag,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readFile(fname,encoding,flag,function(err,data){this$1._mu.unlock();cb(err,data)})})};LockedFS.prototype.readFileSync=function readFileSync(fname,encoding,flag){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readFileSync(fname,encoding,flag)};LockedFS.prototype.writeFile=function writeFile2(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.writeFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.writeFileSync=function writeFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.writeFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.appendFile=function appendFile3(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.appendFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.appendFileSync=function appendFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.appendFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chmod(p,isLchmod,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chmodSync=function chmodSync(p,isLchmod,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chmodSync(p,isLchmod,mode)};LockedFS.prototype.chown=function chown(p,isLchown,uid,gid,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chown(p,isLchown,uid,gid,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chownSync=function chownSync(p,isLchown,uid,gid){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chownSync(p,isLchown,uid,gid)};LockedFS.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;this._mu.lock(function(){this$1._fs.utimes(p,atime,mtime,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.utimesSync=function utimesSync(p,atime,mtime){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.utimesSync(p,atime,mtime)};LockedFS.prototype.link=function link(srcpath,dstpath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.link(srcpath,dstpath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.linkSync=function linkSync(srcpath,dstpath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.linkSync(srcpath,dstpath)};LockedFS.prototype.symlink=function symlink(srcpath,dstpath,type,cb){var this$1=this;this._mu.lock(function(){this$1._fs.symlink(srcpath,dstpath,type,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.symlinkSync(srcpath,dstpath,type)};LockedFS.prototype.readlink=function readlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readlink(p,function(err,linkString){this$1._mu.unlock();cb(err,linkString)})})};LockedFS.prototype.readlinkSync=function readlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readlinkSync(p)};var deletionLogPath="/.deletedFiles.log";function makeModeWritable(mode){return 146|mode}function getFlag(f){return FileFlag.getFileFlag(f)}var OverlayFile=function(PreloadFile$$1){function OverlayFile2(fs4,path$$1,flag,stats,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stats,data)}if(PreloadFile$$1)OverlayFile2.__proto__=PreloadFile$$1;OverlayFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);OverlayFile2.prototype.constructor=OverlayFile2;OverlayFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){cb(null);return}this._fs._syncAsync(this,function(err){this$1.resetDirty();cb(err)})};OverlayFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};OverlayFile2.prototype.close=function close(cb){this.sync(cb)};OverlayFile2.prototype.closeSync=function closeSync(){this.syncSync()};return OverlayFile2}(PreloadFile);var UnlockedOverlayFS=function(BaseFileSystem$$1){function UnlockedOverlayFS2(writable,readable){BaseFileSystem$$1.call(this);this._isInitialized=false;this._initializeCallbacks=[];this._deletedFiles={};this._deleteLog="";this._deleteLogUpdatePending=false;this._deleteLogUpdateNeeded=false;this._deleteLogError=null;this._writable=writable;this._readable=readable;if(this._writable.isReadOnly()){throw new ApiError(ErrorCode.EINVAL,"Writable file system must be writable.")}}if(BaseFileSystem$$1)UnlockedOverlayFS2.__proto__=BaseFileSystem$$1;UnlockedOverlayFS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);UnlockedOverlayFS2.prototype.constructor=UnlockedOverlayFS2;UnlockedOverlayFS2.isAvailable=function isAvailable(){return true};UnlockedOverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return{readable:this._readable,writable:this._writable}};UnlockedOverlayFS2.prototype._syncAsync=function _syncAsync(file,cb){var this$1=this;this.createParentDirectoriesAsync(file.getPath(),function(err){if(err){return cb(err)}this$1._writable.writeFile(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode,cb)})};UnlockedOverlayFS2.prototype._syncSync=function _syncSync(file){this.createParentDirectories(file.getPath());this._writable.writeFileSync(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode)};UnlockedOverlayFS2.prototype.getName=function getName(){return OverlayFS.Name};UnlockedOverlayFS2.prototype.initialize=function initialize3(cb){var this$1=this;var callbackArray=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbackArray.forEach(function(cb2){return cb2(e)})};if(this._isInitialized){return cb()}callbackArray.push(cb);if(callbackArray.length!==1){return}this._writable.readFile(deletionLogPath,"utf8",getFlag("r"),function(err,data){if(err){if(err.errno!==ErrorCode.ENOENT){return end(err)}}else{this$1._deleteLog=data}this$1._reparseDeletionLog();end()})};UnlockedOverlayFS2.prototype.isReadOnly=function isReadOnly(){return false};UnlockedOverlayFS2.prototype.supportsSynch=function supportsSynch(){return this._readable.supportsSynch()&&this._writable.supportsSynch()};UnlockedOverlayFS2.prototype.supportsLinks=function supportsLinks(){return false};UnlockedOverlayFS2.prototype.supportsProps=function supportsProps(){return this._readable.supportsProps()&&this._writable.supportsProps()};UnlockedOverlayFS2.prototype.getDeletionLog=function getDeletionLog(){return this._deleteLog};UnlockedOverlayFS2.prototype.restoreDeletionLog=function restoreDeletionLog(log){this._deleteLog=log;this._reparseDeletionLog();this.updateLog("")};UnlockedOverlayFS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(oldPath,cb)||this.checkPathAsync(newPath,cb)){return}if(oldPath===deletionLogPath||newPath===deletionLogPath){return cb(ApiError.EPERM("Cannot rename deletion log."))}if(oldPath===newPath){return cb()}this.stat(oldPath,false,function(oldErr,oldStats){if(oldErr){return cb(oldErr)}return this$1.stat(newPath,false,function(newErr,newStats){var self2=this$1;function copyDirContents(files){var file=files.shift();if(!file){return cb()}var oldFile=path.resolve(oldPath,file);var newFile=path.resolve(newPath,file);self2.rename(oldFile,newFile,function(err){if(err){return cb(err)}copyDirContents(files)})}var mode=511;if(oldStats.isDirectory()){if(newErr){if(newErr.errno!==ErrorCode.ENOENT){return cb(newErr)}return this$1._writable.exists(oldPath,function(exists2){if(exists2){return this$1._writable.rename(oldPath,newPath,cb)}this$1._writable.mkdir(newPath,mode,function(mkdirErr){if(mkdirErr){return cb(mkdirErr)}this$1._readable.readdir(oldPath,function(err,files){if(err){return cb()}copyDirContents(files)})})})}mode=newStats.mode;if(!newStats.isDirectory()){return cb(ApiError.ENOTDIR(newPath))}this$1.readdir(newPath,function(readdirErr,files){if(files&&files.length){return cb(ApiError.ENOTEMPTY(newPath))}this$1._readable.readdir(oldPath,function(err,files2){if(err){return cb()}copyDirContents(files2)})})}if(newStats&&newStats.isDirectory()){return cb(ApiError.EISDIR(newPath))}this$1.readFile(oldPath,null,getFlag("r"),function(err,data){if(err){return cb(err)}return this$1.writeFile(newPath,data,null,getFlag("w"),oldStats.mode,function(err2){if(err2){return cb(err2)}return this$1.unlink(oldPath,cb)})})})})};UnlockedOverlayFS2.prototype.renameSync=function renameSync(oldPath,newPath){var this$1=this;this.checkInitialized();this.checkPath(oldPath);this.checkPath(newPath);if(oldPath===deletionLogPath||newPath===deletionLogPath){throw ApiError.EPERM("Cannot rename deletion log.")}var oldStats=this.statSync(oldPath,false);if(oldStats.isDirectory()){if(oldPath===newPath){return}var mode=511;if(this.existsSync(newPath)){var stats=this.statSync(newPath,false);mode=stats.mode;if(stats.isDirectory()){if(this.readdirSync(newPath).length>0){throw ApiError.ENOTEMPTY(newPath)}}else{throw ApiError.ENOTDIR(newPath)}}if(this._writable.existsSync(oldPath)){this._writable.renameSync(oldPath,newPath)}else if(!this._writable.existsSync(newPath)){this._writable.mkdirSync(newPath,mode)}if(this._readable.existsSync(oldPath)){this._readable.readdirSync(oldPath).forEach(function(name){this$1.renameSync(path.resolve(oldPath,name),path.resolve(newPath,name))})}}else{if(this.existsSync(newPath)&&this.statSync(newPath,false).isDirectory()){throw ApiError.EISDIR(newPath)}this.writeFileSync(newPath,this.readFileSync(oldPath,null,getFlag("r")),null,getFlag("w"),oldStats.mode)}if(oldPath!==newPath&&this.existsSync(oldPath)){this.unlinkSync(oldPath)}};UnlockedOverlayFS2.prototype.stat=function stat(p,isLstat,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this._writable.stat(p,isLstat,function(err,stat2){if(err&&err.errno===ErrorCode.ENOENT){if(this$1._deletedFiles[p]){cb(ApiError.ENOENT(p))}this$1._readable.stat(p,isLstat,function(err2,stat3){if(stat3){stat3=stat3.clone();stat3.mode=makeModeWritable(stat3.mode)}cb(err2,stat3)})}else{cb(err,stat2)}})};UnlockedOverlayFS2.prototype.statSync=function statSync(p,isLstat){this.checkInitialized();try{return this._writable.statSync(p,isLstat)}catch(e){if(this._deletedFiles[p]){throw ApiError.ENOENT(p)}var oldStat=this._readable.statSync(p,isLstat).clone();oldStat.mode=makeModeWritable(oldStat.mode);return oldStat}};UnlockedOverlayFS2.prototype.open=function open(p,flag,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.stat(p,false,function(err,stats){if(stats){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}this$1._writable.open(p,flag,mode,cb)});case ActionType.NOP:return this$1._writable.exists(p,function(exists2){if(exists2){this$1._writable.open(p,flag,mode,cb)}else{stats=stats.clone();stats.mode=mode;this$1._readable.readFile(p,null,getFlag("r"),function(readFileErr,data){if(readFileErr){return cb(readFileErr)}if(stats.size===-1){stats.size=data.length}var f=new OverlayFile(this$1,p,flag,stats,data);cb(null,f)})}});default:return cb(ApiError.EEXIST(p))}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}return this$1._writable.open(p,flag,mode,cb)});default:return cb(ApiError.ENOENT(p))}}})};UnlockedOverlayFS2.prototype.openSync=function openSync(p,flag,mode){this.checkInitialized();this.checkPath(p);if(p===deletionLogPath){throw ApiError.EPERM("Cannot open deletion log.")}if(this.existsSync(p)){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);case ActionType.NOP:if(this._writable.existsSync(p)){return this._writable.openSync(p,flag,mode)}else{var buf=this._readable.readFileSync(p,null,getFlag("r"));var stats=this._readable.statSync(p,false).clone();stats.mode=mode;return new OverlayFile(this,p,flag,stats,buf)}default:throw ApiError.EEXIST(p)}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);default:throw ApiError.ENOENT(p)}}};UnlockedOverlayFS2.prototype.unlink=function unlink(p,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){return this$1._writable.unlink(p,function(err){if(err){return cb(err)}this$1.exists(p,function(readableExists){if(readableExists){this$1.deletePath(p)}cb(null)})})}else{this$1.deletePath(p);cb(null)}})})};UnlockedOverlayFS2.prototype.unlinkSync=function unlinkSync(p){this.checkInitialized();this.checkPath(p);if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.unlinkSync(p)}if(this.existsSync(p)){this.deletePath(p)}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.rmdir=function rmdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}var rmdirLower=function(){this$1.readdir(p,function(err,files){if(err){return cb(err)}if(files.length){return cb(ApiError.ENOTEMPTY(p))}this$1.deletePath(p);cb(null)})};this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){this$1._writable.rmdir(p,function(err){if(err){return cb(err)}this$1._readable.exists(p,function(readableExists){if(readableExists){rmdirLower()}else{cb()}})})}else{rmdirLower()}})})};UnlockedOverlayFS2.prototype.rmdirSync=function rmdirSync(p){this.checkInitialized();if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.rmdirSync(p)}if(this.existsSync(p)){if(this.readdirSync(p).length>0){throw ApiError.ENOTEMPTY(p)}else{this.deletePath(p)}}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.exists(p,function(exists2){if(exists2){return cb(ApiError.EEXIST(p))}this$1.createParentDirectoriesAsync(p,function(err){if(err){return cb(err)}this$1._writable.mkdir(p,mode,cb)})})};UnlockedOverlayFS2.prototype.mkdirSync=function mkdirSync(p,mode){this.checkInitialized();if(this.existsSync(p)){throw ApiError.EEXIST(p)}else{this.createParentDirectories(p);this._writable.mkdirSync(p,mode)}};UnlockedOverlayFS2.prototype.readdir=function readdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.stat(p,false,function(err,dirStats){if(err){return cb(err)}if(!dirStats.isDirectory()){return cb(ApiError.ENOTDIR(p))}this$1._writable.readdir(p,function(err2,wFiles){if(err2&&err2.code!=="ENOENT"){return cb(err2)}else if(err2||!wFiles){wFiles=[]}this$1._readable.readdir(p,function(err3,rFiles){if(err3||!rFiles){rFiles=[]}var seenMap={};var filtered=wFiles.concat(rFiles.filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]})).filter(function(fPath){var result=!seenMap[fPath];seenMap[fPath]=true;return result});cb(null,filtered)})})})};UnlockedOverlayFS2.prototype.readdirSync=function readdirSync(p){var this$1=this;this.checkInitialized();var dirStats=this.statSync(p,false);if(!dirStats.isDirectory()){throw ApiError.ENOTDIR(p)}var contents=[];try{contents=contents.concat(this._writable.readdirSync(p))}catch(e){}try{contents=contents.concat(this._readable.readdirSync(p).filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]}))}catch(e){}var seenMap={};return contents.filter(function(fileP){var result=!seenMap[fileP];seenMap[fileP]=true;return result})};UnlockedOverlayFS2.prototype.exists=function exists2(p,cb){var this$1=this;this.checkInitialized();this._writable.exists(p,function(existsWritable){if(existsWritable){return cb(true)}this$1._readable.exists(p,function(existsReadable){cb(existsReadable&&this$1._deletedFiles[p]!==true)})})};UnlockedOverlayFS2.prototype.existsSync=function existsSync(p){this.checkInitialized();return this._writable.existsSync(p)||this._readable.existsSync(p)&&this._deletedFiles[p]!==true};UnlockedOverlayFS2.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chmod(p,isLchmod,mode,cb)}})};UnlockedOverlayFS2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chmodSync(p,isLchmod,mode)})};UnlockedOverlayFS2.prototype.chown=function chown(p,isLchmod,uid,gid,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chown(p,isLchmod,uid,gid,cb)}})};UnlockedOverlayFS2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chownSync(p,isLchown,uid,gid)})};UnlockedOverlayFS2.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.utimes(p,atime,mtime,cb)}})};UnlockedOverlayFS2.prototype.utimesSync=function utimesSync(p,atime,mtime){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.utimesSync(p,atime,mtime)})};UnlockedOverlayFS2.prototype.deletePath=function deletePath(p){this._deletedFiles[p]=true;this.updateLog("d"+p+"\n")};UnlockedOverlayFS2.prototype.updateLog=function updateLog(addition){var this$1=this;this._deleteLog+=addition;if(this._deleteLogUpdatePending){this._deleteLogUpdateNeeded=true}else{this._deleteLogUpdatePending=true;this._writable.writeFile(deletionLogPath,this._deleteLog,"utf8",FileFlag.getFileFlag("w"),420,function(e){this$1._deleteLogUpdatePending=false;if(e){this$1._deleteLogError=e}else if(this$1._deleteLogUpdateNeeded){this$1._deleteLogUpdateNeeded=false;this$1.updateLog("")}})}};UnlockedOverlayFS2.prototype._reparseDeletionLog=function _reparseDeletionLog(){var this$1=this;this._deletedFiles={};this._deleteLog.split("\n").forEach(function(path$$1){this$1._deletedFiles[path$$1.slice(1)]=path$$1.slice(0,1)==="d"})};UnlockedOverlayFS2.prototype.checkInitialized=function checkInitialized(){if(!this._isInitialized){throw new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;throw e}};UnlockedOverlayFS2.prototype.checkInitAsync=function checkInitAsync(cb){if(!this._isInitialized){cb(new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it."));return false}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;cb(e);return false}return true};UnlockedOverlayFS2.prototype.checkPath=function checkPath(p){if(p===deletionLogPath){throw ApiError.EPERM(p)}};UnlockedOverlayFS2.prototype.checkPathAsync=function checkPathAsync(p,cb){if(p===deletionLogPath){cb(ApiError.EPERM(p));return true}return false};UnlockedOverlayFS2.prototype.createParentDirectoriesAsync=function createParentDirectoriesAsync(p,cb){var parent=path.dirname(p);var toCreate=[];var self2=this;this._writable.stat(parent,false,statDone);function statDone(err,stat){if(err){toCreate.push(parent);parent=path.dirname(parent);self2._writable.stat(parent,false,statDone)}else{createParents()}}function createParents(){if(!toCreate.length){return cb()}var dir=toCreate.pop();self2._readable.stat(dir,false,function(err,stats){if(!stats){return cb()}self2._writable.mkdir(dir,stats.mode,function(err2){if(err2){return cb(err2)}createParents()})})}};UnlockedOverlayFS2.prototype.createParentDirectories=function createParentDirectories(p){var this$1=this;var parent=path.dirname(p),toCreate=[];while(!this._writable.existsSync(parent)){toCreate.push(parent);parent=path.dirname(parent)}toCreate=toCreate.reverse();toCreate.forEach(function(p2){this$1._writable.mkdirSync(p2,this$1.statSync(p2,false).mode)})};UnlockedOverlayFS2.prototype.operateOnWritable=function operateOnWritable(p,f){if(this.existsSync(p)){if(!this._writable.existsSync(p)){this.copyToWritable(p)}f()}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.operateOnWritableAsync=function operateOnWritableAsync(p,cb){var this$1=this;this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(existsWritable){if(existsWritable){cb()}else{return this$1.copyToWritableAsync(p,cb)}})})};UnlockedOverlayFS2.prototype.copyToWritable=function copyToWritable(p){var pStats=this.statSync(p,false);if(pStats.isDirectory()){this._writable.mkdirSync(p,pStats.mode)}else{this.writeFileSync(p,this._readable.readFileSync(p,null,getFlag("r")),null,getFlag("w"),this.statSync(p,false).mode)}};UnlockedOverlayFS2.prototype.copyToWritableAsync=function copyToWritableAsync(p,cb){var this$1=this;this.stat(p,false,function(err,pStats){if(err){return cb(err)}if(pStats.isDirectory()){return this$1._writable.mkdir(p,pStats.mode,cb)}this$1._readable.readFile(p,null,getFlag("r"),function(err2,data){if(err2){return cb(err2)}this$1.writeFile(p,data,null,getFlag("w"),pStats.mode,cb)})})};return UnlockedOverlayFS2}(BaseFileSystem);var OverlayFS=function(LockedFS$$1){function OverlayFS2(writable,readable,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;LockedFS$$1.call(this,new UnlockedOverlayFS(writable,readable));deprecationMessage(deprecateMsg,OverlayFS2.Name,{readable:"readable file system",writable:"writable file system"})}if(LockedFS$$1)OverlayFS2.__proto__=LockedFS$$1;OverlayFS2.prototype=Object.create(LockedFS$$1&&LockedFS$$1.prototype);OverlayFS2.prototype.constructor=OverlayFS2;OverlayFS2.Create=function Create(opts,cb){try{var fs4=new OverlayFS2(opts.writable,opts.readable,false);fs4.initialize(function(e){cb(e,fs4)},false)}catch(e){cb(e)}};OverlayFS2.isAvailable=function isAvailable(){return UnlockedOverlayFS.isAvailable()};OverlayFS2.prototype.initialize=function initialize3(cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.")}LockedFS$$1.prototype.initialize.call(this,cb)};OverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()};OverlayFS2.prototype.unwrap=function unwrap(){return LockedFS$$1.prototype.getFSUnlocked.call(this)};return OverlayFS2}(LockedFS);OverlayFS.Name="OverlayFS";OverlayFS.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var SpecialArgType;(function(SpecialArgType2){SpecialArgType2[SpecialArgType2["CB"]=0]="CB";SpecialArgType2[SpecialArgType2["FD"]=1]="FD";SpecialArgType2[SpecialArgType2["API_ERROR"]=2]="API_ERROR";SpecialArgType2[SpecialArgType2["STATS"]=3]="STATS";SpecialArgType2[SpecialArgType2["PROBE"]=4]="PROBE";SpecialArgType2[SpecialArgType2["FILEFLAG"]=5]="FILEFLAG";SpecialArgType2[SpecialArgType2["BUFFER"]=6]="BUFFER";SpecialArgType2[SpecialArgType2["ERROR"]=7]="ERROR"})(SpecialArgType||(SpecialArgType={}));var CallbackArgumentConverter=function CallbackArgumentConverter2(){this._callbacks={};this._nextId=0};CallbackArgumentConverter.prototype.toRemoteArg=function toRemoteArg(cb){var id=this._nextId++;this._callbacks[id]=cb;return{type:SpecialArgType.CB,id}};CallbackArgumentConverter.prototype.toLocalArg=function toLocalArg(id){var cb=this._callbacks[id];delete this._callbacks[id];return cb};var FileDescriptorArgumentConverter=function FileDescriptorArgumentConverter2(){this._fileDescriptors={};this._nextId=0};FileDescriptorArgumentConverter.prototype.toRemoteArg=function toRemoteArg(fd,p,flag,cb){var id=this._nextId++;var data;var stat;this._fileDescriptors[id]=fd;fd.stat(function(err,stats){if(err){cb(err)}else{stat=bufferToTransferrableObject(stats.toBuffer());if(flag.isReadable()){fd.read(Buffer2.alloc(stats.size),0,stats.size,0,function(err2,bytesRead,buff){if(err2){cb(err2)}else{data=bufferToTransferrableObject(buff);cb(null,{type:SpecialArgType.FD,id,data,stat,path:p,flag:flag.getFlagString()})}})}else{cb(null,{type:SpecialArgType.FD,id,data:new ArrayBuffer(0),stat,path:p,flag:flag.getFlagString()})}}})};FileDescriptorArgumentConverter.prototype.applyFdAPIRequest=function applyFdAPIRequest(request,cb){var this$1=this;var fdArg=request.args[0];this._applyFdChanges(fdArg,function(err,fd){if(err){cb(err)}else{fd[request.method](function(e){if(request.method==="close"){delete this$1._fileDescriptors[fdArg.id]}cb(e)})}})};FileDescriptorArgumentConverter.prototype._applyFdChanges=function _applyFdChanges(remoteFd,cb){var fd=this._fileDescriptors[remoteFd.id],data=transferrableObjectToBuffer(remoteFd.data),remoteStats=Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));var flag=FileFlag.getFileFlag(remoteFd.flag);if(flag.isWriteable()){fd.write(data,0,data.length,flag.isAppendable()?fd.getPos():0,function(e){function applyStatChanges(){fd.stat(function(e2,stats){if(e2){cb(e2)}else{if(stats.mode!==remoteStats.mode){fd.chmod(remoteStats.mode,function(e3){cb(e3,fd)})}else{cb(e2,fd)}}})}if(e){cb(e)}else{if(!flag.isAppendable()){fd.truncate(data.length,function(){applyStatChanges()})}else{applyStatChanges()}}})}else{cb(null,fd)}};function apiErrorLocal2Remote(e){return{type:SpecialArgType.API_ERROR,errorData:bufferToTransferrableObject(e.writeToBuffer())}}function apiErrorRemote2Local(e){return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData))}function errorLocal2Remote(e){return{type:SpecialArgType.ERROR,name:e.name,message:e.message,stack:e.stack}}function errorRemote2Local(e){var cnstr=global$1[e.name];if(typeof cnstr!=="function"){cnstr=Error}var err=new cnstr(e.message);err.stack=e.stack;return err}function statsLocal2Remote(stats){return{type:SpecialArgType.STATS,statsData:bufferToTransferrableObject(stats.toBuffer())}}function statsRemote2Local(stats){return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData))}function fileFlagLocal2Remote(flag){return{type:SpecialArgType.FILEFLAG,flagStr:flag.getFlagString()}}function fileFlagRemote2Local(remoteFlag){return FileFlag.getFileFlag(remoteFlag.flagStr)}function bufferToTransferrableObject(buff){return buffer2ArrayBuffer(buff)}function transferrableObjectToBuffer(buff){return arrayBuffer2Buffer(buff)}function bufferLocal2Remote(buff){return{type:SpecialArgType.BUFFER,data:bufferToTransferrableObject(buff)}}function bufferRemote2Local(buffArg){return transferrableObjectToBuffer(buffArg.data)}function isAPIRequest(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}function isAPIResponse(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}var WorkerFile=function(PreloadFile$$1){function WorkerFile2(_fs,_path,_flag,_stat,remoteFdId,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents);this._remoteFdId=remoteFdId}if(PreloadFile$$1)WorkerFile2.__proto__=PreloadFile$$1;WorkerFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);WorkerFile2.prototype.constructor=WorkerFile2;WorkerFile2.prototype.getRemoteFdId=function getRemoteFdId(){return this._remoteFdId};WorkerFile2.prototype.toRemoteArg=function toRemoteArg(){return{type:SpecialArgType.FD,id:this._remoteFdId,data:bufferToTransferrableObject(this.getBuffer()),stat:bufferToTransferrableObject(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}};WorkerFile2.prototype.sync=function sync(cb){this._syncClose("sync",cb)};WorkerFile2.prototype.close=function close(cb){this._syncClose("close",cb)};WorkerFile2.prototype._syncClose=function _syncClose(type,cb){var this$1=this;if(this.isDirty()){this._fs.syncClose(type,this,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};return WorkerFile2}(PreloadFile);var WorkerFS=function(BaseFileSystem$$1){function WorkerFS2(worker,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._callbackConverter=new CallbackArgumentConverter;this._isInitialized=false;this._isReadOnly=false;this._supportLinks=false;this._supportProps=false;this._worker=worker;deprecationMessage(deprecateMsg,WorkerFS2.Name,{worker:"Web Worker instance"});this._worker.addEventListener("message",function(e){var resp=e.data;if(isAPIResponse(resp)){var i2;var args=resp.args;var fixedArgs=new Array(args.length);for(i2=0;i20){countdown=-1;message={browserfsMessage:true,cbId,args:[apiErrorLocal2Remote(err)]};worker.postMessage(message)}}for(i2=0;i20){var inode=void 0;var next=queue.pop();var pwd=next[0];var tree=next[1];var parent=next[2];for(var node in tree){if(tree.hasOwnProperty(node)){var children=tree[node];var name=pwd+"/"+node;if(children){idx._index[name]=inode=new DirInode;queue.push([name,children,inode])}else{inode=new FileInode(new Stats(FileType.FILE,-1,365))}if(parent){parent._ls[node]=inode}}}}return idx};FileIndex.prototype.fileIterator=function fileIterator(cb){var this$1=this;for(var path$$1 in this$1._index){if(this$1._index.hasOwnProperty(path$$1)){var dir=this$1._index[path$$1];var files=dir.getListing();for(var i2=0,list2=files;i20&&prefixUrl.charAt(prefixUrl.length-1)!=="/"){prefixUrl=prefixUrl+"/"}this.prefixUrl=prefixUrl;var listing=null;if(typeof listingUrlOrObj==="string"){listing=this._requestFileSync(listingUrlOrObj,"json");if(!listing){throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}}else{listing=listingUrlOrObj}deprecationMessage(deprecateMsg,XmlHttpRequest2.Name,{index:typeof listingUrlOrObj==="string"?listingUrlOrObj:"file index as an object",baseUrl:prefixUrl});this._index=FileIndex.fromListing(listing)}if(BaseFileSystem$$1)XmlHttpRequest2.__proto__=BaseFileSystem$$1;XmlHttpRequest2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);XmlHttpRequest2.prototype.constructor=XmlHttpRequest2;XmlHttpRequest2.Create=function Create(opts,cb){if(opts.index===void 0){opts.index="index.json"}if(typeof opts.index==="string"){XmlHttpRequest2.FromURL(opts.index,cb,opts.baseUrl,false)}else{cb(null,new XmlHttpRequest2(opts.index,opts.baseUrl,false))}};XmlHttpRequest2.isAvailable=function isAvailable(){return typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest!==null};XmlHttpRequest2.FromURL=function FromURL(url,cb,baseUrl,deprecateMsg){if(baseUrl===void 0)baseUrl=url.slice(0,url.lastIndexOf("/")+1);if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: "`+url+'", baseUrl: "'+baseUrl+`" }, cb)' instead.`)}asyncDownloadFile(url,"json",function(e,data){if(e){cb(e)}else{cb(null,new XmlHttpRequest2(data,baseUrl,false))}})};XmlHttpRequest2.prototype.empty=function empty(){this._index.fileIterator(function(file){file.fileData=null})};XmlHttpRequest2.prototype.getName=function getName(){return XmlHttpRequest2.Name};XmlHttpRequest2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};XmlHttpRequest2.prototype.isReadOnly=function isReadOnly(){return true};XmlHttpRequest2.prototype.supportsLinks=function supportsLinks(){return false};XmlHttpRequest2.prototype.supportsProps=function supportsProps(){return false};XmlHttpRequest2.prototype.supportsSynch=function supportsSynch(){return true};XmlHttpRequest2.prototype.preloadFile=function preloadFile(path$$1,buffer$$1){var inode=this._index.getInode(path$$1);if(isFileInode(inode)){if(inode===null){throw ApiError.ENOENT(path$$1)}var stats=inode.getData();stats.size=buffer$$1.length;stats.fileData=buffer$$1}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.stat=function stat(path$$1,isLstat,cb){var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){this._requestFileSizeAsync(path$$1,function(e,size){if(e){return cb(e)}stats.size=size;cb(null,stats.clone())})}else{cb(null,stats.clone())}}else if(isDirInode(inode)){stats=inode.getStats();cb(null,stats)}else{cb(ApiError.FileError(ErrorCode.EINVAL,path$$1))}};XmlHttpRequest2.prototype.statSync=function statSync(path$$1,isLstat){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){stats.size=this._requestFileSizeSync(path$$1)}}else if(isDirInode(inode)){stats=inode.getStats()}else{throw ApiError.FileError(ErrorCode.EINVAL,path$$1)}return stats};XmlHttpRequest2.prototype.open=function open(path$$1,flags,mode,cb){if(flags.isWriteable()){return cb(new ApiError(ErrorCode.EPERM,path$$1))}var self2=this;var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:return cb(ApiError.EEXIST(path$$1));case ActionType.NOP:if(stats.fileData){return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),stats.fileData))}this._requestFileAsync(path$$1,"buffer",function(err,buffer$$1){if(err){return cb(err)}stats.size=buffer$$1.length;stats.fileData=buffer$$1;return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),buffer$$1))});break;default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileMode object."))}}else{return cb(ApiError.EISDIR(path$$1))}};XmlHttpRequest2.prototype.openSync=function openSync(path$$1,flags,mode){if(flags.isWriteable()){throw new ApiError(ErrorCode.EPERM,path$$1)}var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:throw ApiError.EEXIST(path$$1);case ActionType.NOP:if(stats.fileData){return new NoSyncFile(this,path$$1,flags,stats.clone(),stats.fileData)}var buffer$$1=this._requestFileSync(path$$1,"buffer");stats.size=buffer$$1.length;stats.fileData=buffer$$1;return new NoSyncFile(this,path$$1,flags,stats.clone(),buffer$$1);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileMode object.")}}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.readdir=function readdir(path$$1,cb){try{cb(null,this.readdirSync(path$$1))}catch(e){cb(e)}};XmlHttpRequest2.prototype.readdirSync=function readdirSync(path$$1){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}else if(isDirInode(inode)){return inode.getListing()}else{throw ApiError.ENOTDIR(path$$1)}};XmlHttpRequest2.prototype.readFile=function readFile2(fname,encoding,flag,cb){var oldCb=cb;this.open(fname,flag,420,function(err,fd){if(err){return cb(err)}cb=function(err2,arg){fd.close(function(err22){if(!err2){err2=err22}return oldCb(err2,arg)})};var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){cb(err,copyingSlice(fdBuff))}else{tryToString(fdBuff,encoding,cb)}})};XmlHttpRequest2.prototype.readFileSync=function readFileSync(fname,encoding,flag){var fd=this.openSync(fname,flag,420);try{var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){return copyingSlice(fdBuff)}return fdBuff.toString(encoding)}finally{fd.closeSync()}};XmlHttpRequest2.prototype.getXhrPath=function getXhrPath(filePath){if(filePath.charAt(0)==="/"){filePath=filePath.slice(1)}return this.prefixUrl+filePath};XmlHttpRequest2.prototype._requestFileAsync=function _requestFileAsync(p,type,cb){asyncDownloadFile(this.getXhrPath(p),type,cb)};XmlHttpRequest2.prototype._requestFileSync=function _requestFileSync(p,type){return syncDownloadFile(this.getXhrPath(p),type)};XmlHttpRequest2.prototype._requestFileSizeAsync=function _requestFileSizeAsync(path$$1,cb){getFileSizeAsync(this.getXhrPath(path$$1),cb)};XmlHttpRequest2.prototype._requestFileSizeSync=function _requestFileSizeSync(path$$1){return getFileSizeSync(this.getXhrPath(path$$1))};return XmlHttpRequest2}(BaseFileSystem);XmlHttpRequest.Name="XmlHttpRequest";XmlHttpRequest.Options={index:{type:["string","object"],optional:true,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:true,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var ExtendedASCII=function ExtendedASCII2(){};ExtendedASCII.str2byte=function str2byte(str,buf){var length=str.length>buf.length?buf.length:str.length;for(var i2=0;i2127){var charIdx=ExtendedASCII.extendedChars.indexOf(str.charAt(i2));if(charIdx>-1){charCode=charIdx+128}}buf[charCode]=i2}return length};ExtendedASCII.byte2str=function byte2str(buff){var chars=new Array(buff.length);for(var i2=0;i2127){chars[i2]=ExtendedASCII.extendedChars[charCode-128]}else{chars[i2]=String.fromCharCode(charCode)}}return chars.join("")};ExtendedASCII.byteLength=function byteLength(str){return str.length};ExtendedASCII.extendedChars=["\xC7","\xFC","\xE9","\xE2","\xE4","\xE0","\xE5","\xE7","\xEA","\xEB","\xE8","\xEF","\xEE","\xEC","\xC4","\xC5","\xC9","\xE6","\xC6","\xF4","\xF6","\xF2","\xFB","\xF9","\xFF","\xD6","\xDC","\xF8","\xA3","\xD8","\xD7","\u0192","\xE1","\xED","\xF3","\xFA","\xF1","\xD1","\xAA","\xBA","\xBF","\xAE","\xAC","\xBD","\xBC","\xA1","\xAB","\xBB","_","_","_","\xA6","\xA6","\xC1","\xC2","\xC0","\xA9","\xA6","\xA6","+","+","\xA2","\xA5","+","+","-","-","+","-","+","\xE3","\xC3","+","+","-","-","\xA6","-","+","\xA4","\xF0","\xD0","\xCA","\xCB","\xC8","i","\xCD","\xCE","\xCF","+","+","_","_","\xA6","\xCC","_","\xD3","\xDF","\xD4","\xD2","\xF5","\xD5","\xB5","\xFE","\xDE","\xDA","\xDB","\xD9","\xFD","\xDD","\xAF","\xB4","\xAD","\xB1","_","\xBE","\xB6","\xA7","\xF7","\xB8","\xB0","\xA8","\xB7","\xB9","\xB3","\xB2","_"," "];var inflateRaw=__webpack_require__(31).inflateRaw;var decompressionMethods={};var ExternalFileAttributeType;(function(ExternalFileAttributeType2){ExternalFileAttributeType2[ExternalFileAttributeType2["MSDOS"]=0]="MSDOS";ExternalFileAttributeType2[ExternalFileAttributeType2["AMIGA"]=1]="AMIGA";ExternalFileAttributeType2[ExternalFileAttributeType2["OPENVMS"]=2]="OPENVMS";ExternalFileAttributeType2[ExternalFileAttributeType2["UNIX"]=3]="UNIX";ExternalFileAttributeType2[ExternalFileAttributeType2["VM_CMS"]=4]="VM_CMS";ExternalFileAttributeType2[ExternalFileAttributeType2["ATARI_ST"]=5]="ATARI_ST";ExternalFileAttributeType2[ExternalFileAttributeType2["OS2_HPFS"]=6]="OS2_HPFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MAC"]=7]="MAC";ExternalFileAttributeType2[ExternalFileAttributeType2["Z_SYSTEM"]=8]="Z_SYSTEM";ExternalFileAttributeType2[ExternalFileAttributeType2["CP_M"]=9]="CP_M";ExternalFileAttributeType2[ExternalFileAttributeType2["NTFS"]=10]="NTFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MVS"]=11]="MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["VSE"]=12]="VSE";ExternalFileAttributeType2[ExternalFileAttributeType2["ACORN_RISC"]=13]="ACORN_RISC";ExternalFileAttributeType2[ExternalFileAttributeType2["VFAT"]=14]="VFAT";ExternalFileAttributeType2[ExternalFileAttributeType2["ALT_MVS"]=15]="ALT_MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["BEOS"]=16]="BEOS";ExternalFileAttributeType2[ExternalFileAttributeType2["TANDEM"]=17]="TANDEM";ExternalFileAttributeType2[ExternalFileAttributeType2["OS_400"]=18]="OS_400";ExternalFileAttributeType2[ExternalFileAttributeType2["OSX"]=19]="OSX"})(ExternalFileAttributeType||(ExternalFileAttributeType={}));var CompressionMethod;(function(CompressionMethod2){CompressionMethod2[CompressionMethod2["STORED"]=0]="STORED";CompressionMethod2[CompressionMethod2["SHRUNK"]=1]="SHRUNK";CompressionMethod2[CompressionMethod2["REDUCED_1"]=2]="REDUCED_1";CompressionMethod2[CompressionMethod2["REDUCED_2"]=3]="REDUCED_2";CompressionMethod2[CompressionMethod2["REDUCED_3"]=4]="REDUCED_3";CompressionMethod2[CompressionMethod2["REDUCED_4"]=5]="REDUCED_4";CompressionMethod2[CompressionMethod2["IMPLODE"]=6]="IMPLODE";CompressionMethod2[CompressionMethod2["DEFLATE"]=8]="DEFLATE";CompressionMethod2[CompressionMethod2["DEFLATE64"]=9]="DEFLATE64";CompressionMethod2[CompressionMethod2["TERSE_OLD"]=10]="TERSE_OLD";CompressionMethod2[CompressionMethod2["BZIP2"]=12]="BZIP2";CompressionMethod2[CompressionMethod2["LZMA"]=14]="LZMA";CompressionMethod2[CompressionMethod2["TERSE_NEW"]=18]="TERSE_NEW";CompressionMethod2[CompressionMethod2["LZ77"]=19]="LZ77";CompressionMethod2[CompressionMethod2["WAVPACK"]=97]="WAVPACK";CompressionMethod2[CompressionMethod2["PPMD"]=98]="PPMD"})(CompressionMethod||(CompressionMethod={}));function msdos2date(time,date){var day=date&31;var month=(date>>5&15)-1;var year=(date>>9)+1980;var second=time&31;var minute=time>>5&63;var hour=time>>11;return new Date(year,month,day,hour,minute,second)}function safeToString(buff,useUTF8,start,length){if(length===0){return""}else if(useUTF8){return buff.toString("utf8",start,start+length)}else{return ExtendedASCII.byte2str(buff.slice(start,start+length))}}var FileHeader=function FileHeader2(data){this.data=data;if(data.readUInt32LE(0)!==67324752){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))}};FileHeader.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(4)};FileHeader.prototype.flags=function flags(){return this.data.readUInt16LE(6)};FileHeader.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(8)};FileHeader.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(10),this.data.readUInt16LE(12))};FileHeader.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(10)};FileHeader.prototype.crc32=function crc32(){return this.data.readUInt32LE(14)};FileHeader.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(26)};FileHeader.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(28)};FileHeader.prototype.fileName=function fileName(){return safeToString(this.data,this.useUTF8(),30,this.fileNameLength())};FileHeader.prototype.extraField=function extraField(){var start=30+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};FileHeader.prototype.totalSize=function totalSize(){return 30+this.fileNameLength()+this.extraFieldLength()};FileHeader.prototype.useUTF8=function useUTF8(){return(this.flags()&2048)===2048};var FileData=function FileData2(header,record,data){this.header=header;this.record=record;this.data=data};FileData.prototype.decompress=function decompress(){var compressionMethod=this.header.compressionMethod();var fcn=decompressionMethods[compressionMethod];if(fcn){return fcn(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag())}else{var name=CompressionMethod[compressionMethod];if(!name){name="Unknown: "+compressionMethod}throw new ApiError(ErrorCode.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+name)}};FileData.prototype.getHeader=function getHeader(){return this.header};FileData.prototype.getRecord=function getRecord(){return this.record};FileData.prototype.getRawData=function getRawData(){return this.data};var DataDescriptor=function DataDescriptor2(data){this.data=data};DataDescriptor.prototype.crc32=function crc32(){return this.data.readUInt32LE(0)};DataDescriptor.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(4)};DataDescriptor.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(8)};var ArchiveExtraDataRecord=function ArchiveExtraDataRecord2(data){this.data=data;if(this.data.readUInt32LE(0)!==134630224){throw new ApiError(ErrorCode.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))}};ArchiveExtraDataRecord.prototype.length=function length(){return this.data.readUInt32LE(4)};ArchiveExtraDataRecord.prototype.extraFieldData=function extraFieldData(){return this.data.slice(8,8+this.length())};var DigitalSignature=function DigitalSignature2(data){this.data=data;if(this.data.readUInt32LE(0)!==84233040){throw new ApiError(ErrorCode.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))}};DigitalSignature.prototype.size=function size(){return this.data.readUInt16LE(4)};DigitalSignature.prototype.signatureData=function signatureData(){return this.data.slice(6,6+this.size())};var CentralDirectory=function CentralDirectory2(zipData,data){this.zipData=zipData;this.data=data;if(this.data.readUInt32LE(0)!==33639248){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0))}this._filename=this.produceFilename()};CentralDirectory.prototype.versionMadeBy=function versionMadeBy(){return this.data.readUInt16LE(4)};CentralDirectory.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(6)};CentralDirectory.prototype.flag=function flag(){return this.data.readUInt16LE(8)};CentralDirectory.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(10)};CentralDirectory.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(12),this.data.readUInt16LE(14))};CentralDirectory.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(12)};CentralDirectory.prototype.crc32=function crc32(){return this.data.readUInt32LE(16)};CentralDirectory.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(20)};CentralDirectory.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(24)};CentralDirectory.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(28)};CentralDirectory.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(30)};CentralDirectory.prototype.fileCommentLength=function fileCommentLength(){return this.data.readUInt16LE(32)};CentralDirectory.prototype.diskNumberStart=function diskNumberStart(){return this.data.readUInt16LE(34)};CentralDirectory.prototype.internalAttributes=function internalAttributes(){return this.data.readUInt16LE(36)};CentralDirectory.prototype.externalAttributes=function externalAttributes(){return this.data.readUInt32LE(38)};CentralDirectory.prototype.headerRelativeOffset=function headerRelativeOffset(){return this.data.readUInt32LE(42)};CentralDirectory.prototype.produceFilename=function produceFilename(){var fileName=safeToString(this.data,this.useUTF8(),46,this.fileNameLength());return fileName.replace(/\\/g,"/")};CentralDirectory.prototype.fileName=function fileName(){return this._filename};CentralDirectory.prototype.rawFileName=function rawFileName(){return this.data.slice(46,46+this.fileNameLength())};CentralDirectory.prototype.extraField=function extraField(){var start=44+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};CentralDirectory.prototype.fileComment=function fileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return safeToString(this.data,this.useUTF8(),start,this.fileCommentLength())};CentralDirectory.prototype.rawFileComment=function rawFileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(start,start+this.fileCommentLength())};CentralDirectory.prototype.totalSize=function totalSize(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()};CentralDirectory.prototype.isDirectory=function isDirectory(){var fileName=this.fileName();return(this.externalAttributes()&16?true:false)||fileName.charAt(fileName.length-1)==="/"};CentralDirectory.prototype.isFile=function isFile(){return!this.isDirectory()};CentralDirectory.prototype.useUTF8=function useUTF8(){return(this.flag()&2048)===2048};CentralDirectory.prototype.isEncrypted=function isEncrypted(){return(this.flag()&1)===1};CentralDirectory.prototype.getFileData=function getFileData(){var start=this.headerRelativeOffset();var header=new FileHeader(this.zipData.slice(start));return new FileData(header,this,this.zipData.slice(start+header.totalSize()))};CentralDirectory.prototype.getData=function getData(){return this.getFileData().decompress()};CentralDirectory.prototype.getRawData=function getRawData(){return this.getFileData().getRawData()};CentralDirectory.prototype.getStats=function getStats(){return new Stats(FileType.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var EndOfCentralDirectory=function EndOfCentralDirectory2(data){this.data=data;if(this.data.readUInt32LE(0)!==101010256){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))}};EndOfCentralDirectory.prototype.diskNumber=function diskNumber(){return this.data.readUInt16LE(4)};EndOfCentralDirectory.prototype.cdDiskNumber=function cdDiskNumber(){return this.data.readUInt16LE(6)};EndOfCentralDirectory.prototype.cdDiskEntryCount=function cdDiskEntryCount(){return this.data.readUInt16LE(8)};EndOfCentralDirectory.prototype.cdTotalEntryCount=function cdTotalEntryCount(){return this.data.readUInt16LE(10)};EndOfCentralDirectory.prototype.cdSize=function cdSize(){return this.data.readUInt32LE(12)};EndOfCentralDirectory.prototype.cdOffset=function cdOffset(){return this.data.readUInt32LE(16)};EndOfCentralDirectory.prototype.cdZipCommentLength=function cdZipCommentLength(){return this.data.readUInt16LE(20)};EndOfCentralDirectory.prototype.cdZipComment=function cdZipComment(){return safeToString(this.data,true,22,this.cdZipCommentLength())};EndOfCentralDirectory.prototype.rawCdZipComment=function rawCdZipComment(){return this.data.slice(22,22+this.cdZipCommentLength())};var ZipTOC=function ZipTOC2(index,directoryEntries,eocd,data){this.index=index;this.directoryEntries=directoryEntries;this.eocd=eocd;this.data=data};var ZipFS=function(SynchronousFileSystem$$1){function ZipFS2(input,name,deprecateMsg){if(name===void 0)name="";if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this.name=name;this._index=new FileIndex;this._directoryEntries=[];this._eocd=null;deprecationMessage(deprecateMsg,ZipFS2.Name,{zipData:"zip data as a Buffer",name});if(input instanceof ZipTOC){this._index=input.index;this._directoryEntries=input.directoryEntries;this._eocd=input.eocd;this.data=input.data}else{this.data=input;this.populateIndex()}}if(SynchronousFileSystem$$1)ZipFS2.__proto__=SynchronousFileSystem$$1;ZipFS2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);ZipFS2.prototype.constructor=ZipFS2;ZipFS2.Create=function Create(opts,cb){try{ZipFS2.computeIndex(opts.zipData,function(zipTOC){var fs4=new ZipFS2(zipTOC,opts.name,false);cb(null,fs4)},false)}catch(e){cb(e)}};ZipFS2.isAvailable=function isAvailable(){return true};ZipFS2.RegisterDecompressionMethod=function RegisterDecompressionMethod(m,fcn){decompressionMethods[m]=fcn};ZipFS2.computeIndex=function computeIndex(data,cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.")}var index=new FileIndex;var eocd=ZipFS2.getEOCD(data);if(eocd.diskNumber()!==eocd.cdDiskNumber()){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support spanned zip files.")}var cdPtr=eocd.cdOffset();if(cdPtr===4294967295){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support Zip64.")}var cdEnd=cdPtr+eocd.cdSize();ZipFS2.computeIndexResponsive(data,index,cdPtr,cdEnd,cb,[],eocd)};ZipFS2.getEOCD=function getEOCD(data){var startOffset=22;var endOffset=Math.min(startOffset+65535,data.length-1);for(var i2=startOffset;i2-1};DirectoryRecord.prototype.getRockRidgeOffset=function getRockRidgeOffset(){return this._rockRidgeOffset};DirectoryRecord.prototype.rootCheckForRockRidge=function rootCheckForRockRidge(isoData){var dir=this.getDirectory(isoData);this._rockRidgeOffset=dir.getDotEntry(isoData)._getRockRidgeOffset(isoData);if(this._rockRidgeOffset>-1){this._fileOrDir=null}};DirectoryRecord.prototype.length=function length(){return this._data[0]};DirectoryRecord.prototype.extendedAttributeRecordLength=function extendedAttributeRecordLength(){return this._data[1]};DirectoryRecord.prototype.lba=function lba(){return this._data.readUInt32LE(2)*2048};DirectoryRecord.prototype.dataLength=function dataLength(){return this._data.readUInt32LE(10)};DirectoryRecord.prototype.recordingDate=function recordingDate(){return getShortFormDate(this._data,18)};DirectoryRecord.prototype.fileFlags=function fileFlags(){return this._data[25]};DirectoryRecord.prototype.fileUnitSize=function fileUnitSize(){return this._data[26]};DirectoryRecord.prototype.interleaveGapSize=function interleaveGapSize(){return this._data[27]};DirectoryRecord.prototype.volumeSequenceNumber=function volumeSequenceNumber(){return this._data.readUInt16LE(28)};DirectoryRecord.prototype.identifier=function identifier(){return this._getString(33,this._data[32])};DirectoryRecord.prototype.fileName=function fileName(isoData){if(this.hasRockRidge()){var fn=this._rockRidgeFilename(isoData);if(fn!==null){return fn}}var ident=this.identifier();if(this.isDirectory(isoData)){return ident}var versionSeparator=ident.indexOf(";");if(versionSeparator===-1){return ident}else if(ident[versionSeparator-1]==="."){return ident.slice(0,versionSeparator-1)}else{return ident.slice(0,versionSeparator)}};DirectoryRecord.prototype.isDirectory=function isDirectory(isoData){var rv=!!(this.fileFlags()&2);if(!rv&&this.hasRockRidge()){rv=this.getSUEntries(isoData).filter(function(e){return e instanceof CLEntry}).length>0}return rv};DirectoryRecord.prototype.isSymlink=function isSymlink(isoData){return this.hasRockRidge()&&this.getSUEntries(isoData).filter(function(e){return e instanceof SLEntry}).length>0};DirectoryRecord.prototype.getSymlinkPath=function getSymlinkPath(isoData){var p="";var entries=this.getSUEntries(isoData);var getStr=this._getGetString();for(var i2=0,list2=entries;i21&&p[p.length-1]==="/"){return p.slice(0,p.length-1)}else{return p}};DirectoryRecord.prototype.getFile=function getFile(isoData){if(this.isDirectory(isoData)){throw new Error("Tried to get a File from a directory.")}if(this._fileOrDir===null){this._fileOrDir=isoData.slice(this.lba(),this.lba()+this.dataLength())}return this._fileOrDir};DirectoryRecord.prototype.getDirectory=function getDirectory(isoData){if(!this.isDirectory(isoData)){throw new Error("Tried to get a Directory from a file.")}if(this._fileOrDir===null){this._fileOrDir=this._constructDirectory(isoData)}return this._fileOrDir};DirectoryRecord.prototype.getSUEntries=function getSUEntries(isoData){if(!this._suEntries){this._constructSUEntries(isoData)}return this._suEntries};DirectoryRecord.prototype._rockRidgeFilename=function _rockRidgeFilename(isoData){var nmEntries=this.getSUEntries(isoData).filter(function(e2){return e2 instanceof NMEntry});if(nmEntries.length===0||nmEntries[0].flags()&(2|4)){return null}var str="";var getString=this._getGetString();for(var i2=0,list2=nmEntries;i20){var spEntry=suEntries[0];if(spEntry instanceof SPEntry&&spEntry.checkBytesPass()){for(var i2=1;i2K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer2.prototype;return buf}function Buffer2(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer2[Symbol.species]===Buffer2){Object.defineProperty(Buffer2,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer2.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer2.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer2.prototype.__proto__=Uint8Array.prototype;Buffer2.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==void 0){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer2.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer2.allocUnsafe=function(size){return allocUnsafe(size)};Buffer2.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer2.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer2.alloc(+length)}Buffer2.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer2.compare=function compare(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer2.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===void 0||start<0){start=0}if(start>this.length){return""}if(end===void 0||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer2.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer2.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer2.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer2.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===void 0){start=0}if(end===void 0){end=target?target.length:0}if(thisStart===void 0){thisStart=0}if(thisEnd===void 0){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer2.from(val,encoding)}if(Buffer2.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==void 0){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i2){if(indexSize===1){return buf[i2]}else{return buf.readUInt16BE(i2*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===void 0)encoding="utf8"}else{encoding=length;length=void 0}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===void 0||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer2.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer2.prototype.readUIntLE=function readUIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){checkOffset(offset,byteLength2,this.length)}var val=this[offset+--byteLength2];var mul=1;while(byteLength2>0&&(mul*=256)){val+=this[offset+--byteLength2]*mul}return val};Buffer2.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer2.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer2.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer2.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer2.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer2.prototype.readIntLE=function readIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readIntBE=function readIntBE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var i=byteLength2;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer2.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer2.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer2.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer2.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer2.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer2.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer2.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer2.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var i=byteLength2-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength2};Buffer2.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer2.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer2.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer2.prototype.writeIntLE=function writeIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeIntBE=function writeIntBE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=byteLength2-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer2.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer2.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer2.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer2.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer2.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer2.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer2.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i>>0;end=end===void 0?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}}).call(exports2,__webpack_require__(1))},function(module2,exports2){"use strict";exports2.byteLength=byteLength;exports2.toByteArray=toByteArray;exports2.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len2-2]==="="?2:b64[len2-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i2,j,l,tmp,placeHolders,arr;var len2=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len2*3/4-placeHolders);l=placeHolders>0?len2-4:len2;var L=0;for(i2=0,j=0;i2>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i2=start;i2len22?len22:i2+maxChunkLength))}if(extraBytes===1){tmp=uint8[len2-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len2-2]<<8)+uint8[len2-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},function(module2,exports2){exports2.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports2.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},function(module2,exports2){module2.exports=function(module3){if(!module3.webpackPolyfill){module3.deprecate=function(){};module3.paths=[];module3.children=[];module3.webpackPolyfill=1}return module3}},function(module2,exports2,__webpack_require__){"use strict";var Process=__webpack_require__(7);var process=new Process,processProxy={};function defineKey(key2){if(processProxy[key2]){return}if(typeof process[key2]==="function"){processProxy[key2]=function(){return process[key2].apply(process,arguments)}}else{processProxy[key2]=process[key2]}}for(var key in process){defineKey(key)}processProxy.initializeTTYs=function(){if(process.stdin===null){process.initializeTTYs();processProxy.stdin=process.stdin;processProxy.stdout=process.stdout;processProxy.stderr=process.stderr}};process.nextTick(function(){processProxy.initializeTTYs()});module2.exports=processProxy},function(module2,exports2,__webpack_require__){(function(__dirname){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var events=__webpack_require__(8);var path=null;var Item=function(){function Item2(fun,array){this.fun=fun;this.array=array}Item2.prototype.run=function(){this.fun.apply(null,this.array)};return Item2}();var NextTickQueue=function(){function NextTickQueue2(){this._queue=[];this._draining=false;this._currentQueue=null;this._queueIndex=-1}NextTickQueue2.prototype.push=function(item){var _this=this;if(this._queue.push(item)===1&&!this._draining){setTimeout(function(){return _this._drainQueue()},0)}};NextTickQueue2.prototype._cleanUpNextTick=function(){this._draining=false;if(this._currentQueue&&this._currentQueue.length){this._queue=this._currentQueue.concat(this._queue)}else{this._queueIndex=-1}if(this._queue.length){this._drainQueue()}};NextTickQueue2.prototype._drainQueue=function(){var _this=this;if(this._draining){return}var timeout=setTimeout(function(){return _this._cleanUpNextTick()});this._draining=true;var len=this._queue.length;while(len){this._currentQueue=this._queue;this._queue=[];while(++this._queueIndex0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module2,exports2,__webpack_require__){(function(process){"use strict";var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;function posixSplitPath(filename){var out=splitPathRe.exec(filename);out.shift();return out}var path=function(){function path2(){}path2.normalize=function(p){if(p===""){p="."}var absolute=p.charAt(0)===path2.sep;p=path2._removeDuplicateSeps(p);var components=p.split(path2.sep);var goodComponents=[];for(var idx=0;idx0&&goodComponents[0]!=="..")){goodComponents.pop()}else{goodComponents.push(c)}}if(!absolute&&goodComponents.length<2){switch(goodComponents.length){case 1:if(goodComponents[0]===""){goodComponents.unshift(".")}break;default:goodComponents.push(".")}}p=goodComponents.join(path2.sep);if(absolute&&p.charAt(0)!==path2.sep){p=path2.sep+p}return p};path2.join=function(){var paths=[];for(var _i=0;_i1&&resolved.charAt(resolved.length-1)===path2.sep){return resolved.substr(0,resolved.length-1)}if(resolved.charAt(0)!==path2.sep){if(resolved.charAt(0)==="."&&(resolved.length===1||resolved.charAt(1)===path2.sep)){resolved=resolved.length===1?"":resolved.substr(2)}var cwd=process.cwd();if(resolved!==""){resolved=this.normalize(cwd+(cwd!=="/"?path2.sep:"")+resolved)}else{resolved=cwd}}return resolved};path2.relative=function(from,to){var i;from=path2.resolve(from);to=path2.resolve(to);var fromSegs=from.split(path2.sep);var toSegs=to.split(path2.sep);toSegs.shift();fromSegs.shift();var upCount=0;var downSegs=[];for(i=0;ifromSegs.length){upCount=fromSegs.length}var rv="";for(i=0;i1&&rv.charAt(rv.length-1)===path2.sep){rv=rv.substr(0,rv.length-1)}return rv};path2.dirname=function(p){p=path2._removeDuplicateSeps(p);var absolute=p.charAt(0)===path2.sep;var sections=p.split(path2.sep);if(sections.pop()===""&§ions.length>0){sections.pop()}if(sections.length>1||sections.length===1&&!absolute){return sections.join(path2.sep)}else if(absolute){return path2.sep}else{return"."}};path2.basename=function(p,ext){if(ext===void 0){ext=""}if(p===""){return p}p=path2.normalize(p);var sections=p.split(path2.sep);var lastPart=sections[sections.length-1];if(lastPart===""&§ions.length>1){return sections[sections.length-2]}if(ext.length>0){var lastPartExt=lastPart.substr(lastPart.length-ext.length);if(lastPartExt===ext){return lastPart.substr(0,lastPart.length-ext.length)}}return lastPart};path2.extname=function(p){p=path2.normalize(p);var sections=p.split(path2.sep);p=sections.pop();if(p===""&§ions.length>0){p=sections.pop()}if(p===".."){return""}var i=p.lastIndexOf(".");if(i===-1||i===0){return""}return p.substr(i)};path2.isAbsolute=function(p){return p.length>0&&p.charAt(0)===path2.sep};path2._makeLong=function(p){return p};path2.parse=function(p){var allParts=posixSplitPath(p);return{root:allParts[0],dir:allParts[0]+allParts[1].slice(0,-1),base:allParts[2],ext:allParts[3],name:allParts[2].slice(0,allParts[2].length-allParts[3].length)}};path2.format=function(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof pathObject)}var root=pathObject.root||"";if(typeof root!=="string"){throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof pathObject.root)}var dir=pathObject.dir?pathObject.dir+path2.sep:"";var base=pathObject.base||"";return dir+base};path2._removeDuplicateSeps=function(p){p=p.replace(this._replaceRegex,this.sep);return p};path2.sep="/";path2._replaceRegex=new RegExp("//+","g");path2.delimiter=":";path2.posix=path2;path2.win32=path2;return path2}();var _=path;module2.exports=path}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(Buffer2){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var stream=__webpack_require__(11);var TTY=function(_super){__extends(TTY2,_super);function TTY2(){_super.call(this);this.isRaw=false;this.columns=80;this.rows=120;this.isTTY=true;this._bufferedWrites=[];this._waitingForWrites=false}TTY2.prototype.setRawMode=function(mode){if(this.isRaw!==mode){this.isRaw=mode;this.emit("modeChange")}};TTY2.prototype.changeColumns=function(columns){if(columns!==this.columns){this.columns=columns;this.emit("resize")}};TTY2.prototype.changeRows=function(rows){if(rows!==this.rows){this.rows=rows;this.emit("resize")}};TTY2.isatty=function(fd){return fd&&fd instanceof TTY2};TTY2.prototype._write=function(chunk,encoding,cb){var error;try{var data;if(typeof chunk==="string"){data=new Buffer2(chunk,encoding)}else{data=chunk}this._bufferedWrites.push(data);if(this._waitingForWrites){this._read(1024)}}catch(e){error=e}finally{cb(error)}};TTY2.prototype._read=function(size){if(this._bufferedWrites.length===0){this._waitingForWrites=true}else{while(this._bufferedWrites.length>0){this._waitingForWrites=this.push(this._bufferedWrites.shift());if(!this._waitingForWrites){break}}}};return TTY2}(stream.Duplex);module2.exports=TTY}).call(exports2,__webpack_require__(1))},function(module2,exports2,__webpack_require__){module2.exports=Stream;var EE=__webpack_require__(8).EventEmitter;var inherits=__webpack_require__(12);inherits(Stream,EE);Stream.Readable=__webpack_require__(13);Stream.Writable=__webpack_require__(27);Stream.Duplex=__webpack_require__(28);Stream.Transform=__webpack_require__(29);Stream.PassThrough=__webpack_require__(30);Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},function(module2,exports2){if(typeof Object.create==="function"){module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},function(module2,exports2,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(11)}catch(_){}}();exports2=module2.exports=__webpack_require__(14);exports2.Stream=Stream||exports2;exports2.Readable=exports2;exports2.Writable=__webpack_require__(22);exports2.Duplex=__webpack_require__(21);exports2.Transform=__webpack_require__(25);exports2.PassThrough=__webpack_require__(26);if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module2.exports=Stream}}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(process){"use strict";module2.exports=Readable;var processNextTick=__webpack_require__(15);var isArray=__webpack_require__(16);var Duplex;Readable.ReadableState=ReadableState;var EE=__webpack_require__(8).EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var debugUtil=__webpack_require__(19);var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=__webpack_require__(20);var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=__webpack_require__(24).StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||__webpack_require__(21);if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer2.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;iMAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===void 0){enc=void 0;_fill=0}var buf=new Buffer2(size);if(typeof _fill==="string"){var fillBuf=new Buffer2(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer2(size)};exports2.from=function from(value,encodingOrOffset,length){if(typeof Buffer2.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer2.from)){return Buffer2.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer2(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer2(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer2(value.slice(offset,offset+len))}if(Buffer2.isBuffer(value)){var out=new Buffer2(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer2(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer2(value.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")};exports2.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer2.allocUnsafeSlow==="function"){return Buffer2.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(exports2,function(){return this}())},function(module2,exports2,__webpack_require__){(function(Buffer2){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports2.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports2.isBoolean=isBoolean;function isNull(arg){return arg===null}exports2.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports2.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports2.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports2.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports2.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports2.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports2.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports2.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports2.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports2.isError=isError;function isFunction(arg){return typeof arg==="function"}exports2.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports2.isPrimitive=isPrimitive;exports2.isBuffer=Buffer2.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(exports2,__webpack_require__(1))},function(module2,exports2){},function(module2,exports2,__webpack_require__){"use strict";var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);module2.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},function(module2,exports2,__webpack_require__){"use strict";var objectKeys=Object.keys||function(obj){var keys2=[];for(var key in obj){keys2.push(key)}return keys2};module2.exports=Duplex;var processNextTick=__webpack_require__(15);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var Readable=__webpack_require__(14);var Writable=__webpack_require__(22);util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var internalUtil={deprecate:__webpack_require__(23)};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||__webpack_require__(21);if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer2.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer2.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},function(module2,exports2,__webpack_require__){"use strict";module2.exports=Transform;var Duplex=__webpack_require__(21);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==void 0)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg||msg[inflator.err]}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports2.Inflate=Inflate;exports2.inflate=inflate;exports2.inflateRaw=inflateRaw;exports2.ungzip=inflate},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var adler32=__webpack_require__(34);var crc32=__webpack_require__(35);var inflate_fast=__webpack_require__(36);var inflate_table=__webpack_require__(37);var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&©>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module2.exports=adler32},function(module2,exports2){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255]}return crc^-1}module2.exports=crc32},function(module2,exports2){"use strict";var BAD=30;var TYPE=12;module2.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits>>=op;bits-=op}if(bits<15){hold+=input[_in++]<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bitsdmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3;_in-=len;bits-=len<<3;hold&=(1<=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}for(;;){here_bits=len-drop;if(work[sym]end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports2.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports2.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},function(module2,exports2){"use strict";module2.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(module2,exports2){"use strict";module2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(module2,exports2){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module2.exports=ZStream},function(module2,exports2){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module2.exports=GZheader}])})}});var CSV=class{constructor(onOpen=this.onOpen,saveButtonId=null,openButtonId=null){this.onOpen=onOpen;this.notes=[];if(saveButtonId!==null){document.getElementById(saveButtonId).addEventListener("click",this.saveCSV)}if(openButtonId!==null){document.getElementById(openButtonId).addEventListener("click",this.openCSV)}}processArraysForCSV(data=["1|2|3","3|2|1"],delimiter="|",header="a,b,c",saveNotes=false){let csvDat=header+"\n";let noteIdx=0;data.forEach((line,i)=>{if(data[i]==="string"&&delimiter!==","){csvDat+=line.split(delimiter).join(",")}else{csvData+=line.join(",")}if(saveNotes===true){if(this.notes[noteIdx].idx===i){line+=this.notes[noteIdx].text;noteIdx++}}if(line.indexOf("\n")<0){csvDat+="\n"}});return csvDat}static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){var hiddenElement=document.createElement("a");hiddenElement.href="data:text/csv;charset=utf-8,"+encodeURI(csvDat);hiddenElement.target="_blank";if(name!==""){hiddenElement.download=name}else{hiddenElement.download=new Date().toISOString()+".csv"}hiddenElement.click()}static openCSV(delimiter=",",onOpen=(csvDat,header,path)=>{return csvDat,header,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;var tempcsvArr=tempcsvData.split("\n");let header=[];var csvDat=[];tempcsvArr.pop();tempcsvArr.forEach((row,i)=>{if(i==0){header=row.split(delimiter)}else{var temp=row.split(delimiter);csvDat.push(temp)}});onOpen(csvDat,header,input.value);input.value="";res({data:csvDat,header,filename:input.value})};reader.readAsText(file)};input.click()})}static openCSVRaw(onOpen=(csvDat,path)=>{return csvDat,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;onOpen(tempcsvData,input.value);input.value="";res({data:tempcsvData,filename:input.value})};reader.readAsText(file)};input.click()})}onOpen(csvDat=[],header=[]){console.log("CSV Opened!",header,csvDat)}};var parseCSVData=(data,filename,head,hasend=true,parser=(lines,filename2,head2)=>{let result={filename:filename2};let header=head2;if(typeof head2==="string")header=head2.split(",");result.header=header;for(let i=0;i{let lines;if(data.includes("\r"))lines=data.split("\r\n");else lines=data.split("\n");if(!head)head=lines[0];lines.shift();if(hasend===false)lines.pop();let result=parser(lines,filename,head);return result};function toISOLocal(d){d=new Date(d);var z=n=>("0"+n).slice(-2);var zz=n=>("00"+n).slice(-3);var off=d.getTimezoneOffset();var sign=off<0?"+":"-";off=Math.abs(off);return d.getFullYear()+"-"+z(d.getMonth()+1)+"-"+z(d.getDate())+"T"+z(d.getHours())+":"+z(d.getMinutes())+":"+z(d.getSeconds())+"."+zz(d.getMilliseconds())+"(UTC"+sign+z(off/60|0)+":00)"}var processDataForCSV=(options={})=>{if(!options.data)return void 0;if(!Array.isArray(options.data))options.data=[options.data];if(options.data&&!options.header)options.header=Object.keys(options.data[0]);let head=[...options.header];if(head.indexOf("timestamp")>-1){head.splice(head.indexOf("timestamp")+1,0,"localized")}let header=head.join(",");let headeridx=0;let lines=[];let foreach=(obj,i)=>{if(Array.isArray(obj)){for(let j=0;j{if(exists2)appendFile(options.filename,joined,options.dir);else appendFile(options.filename,header+joined,options.dir)})}return result};var BrowserFS=__toESM(require_browserfs());var fsInited=false;var fs2=BrowserFS.BFSRequire("fs");var BFSBuffer=BrowserFS.BFSRequire("buffer").Buffer;var initPromise;var initFS=async(dirs=["data"],oninit=(exists2=[])=>{},onerror=e=>{},filesystem="IndexedDB")=>{if(fsInited){if(initPromise){await initPromise}return true}else{fsInited=true;initPromise=new Promise((resolve,reject)=>{BrowserFS.FileSystem[filesystem].Create({},(e,mountableFileSystem)=>{if(e){reject(e);return}if(!mountableFileSystem){onerror(e);reject(new Error(`Error creating BrowserFS`));return}BrowserFS.initialize(mountableFileSystem);let promises=[];dirs.forEach(async dir=>{promises.push(dirExists(fs2,dir))});Promise.all(promises).then(values=>{oninit(values);resolve(true)})})});return await initPromise}};var exists=async(path="")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.exists("/"+path,function(exists2){resolve(exists2)})})};var readFile=async(path="data")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.readFile("/"+path,function(e,output){resolve(output)})})};async function readFileChunk(path="data",begin=0,end=5120,onread=data=>{}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);if(path!=""){return await new Promise(async(resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})}else{console.error("Path name is not defined");return void 0}}var getFilenames=async(directory="data",onload=directory2=>{})=>{if(!fsInited)await initFS([directory]);else await dirExists(fs2,directory);return await new Promise((resolve,reject)=>{fs2.readdir("/"+directory,(e,dir)=>{if(e){reject(e);return}if(dir){onload(dir);resolve(dir)}else resolve(void 0)})})};var writeFile=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.writeFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var appendFile2=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.appendFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var deleteFile=async(path="data",ondelete=()=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{if(path!=""){fs2.unlink("/"+path,e=>{if(e)console.error(e);ondelete();resolve(true)})}else{console.error("Path name is not defined");resolve(false)}})};var readFileAsText=async(path="data",end="end",begin=0,onread=(data,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(async(resolve,reject)=>{let size=await getFileSize(path);if(end==="end"){end=size}else if(typeof end==="number"){if(end>size)end=size}fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})};var listFiles=async(dir="data",onload=directory=>{})=>{if(!fsInited)await initFS([dir]);else await dirExists(fs2,dir);return await new Promise((resolve,reject)=>{fs2.readdir("/"+dir,(e,directory)=>{if(e){reject(e);return}if(directory){onload(directory)}resolve(directory)})})};var getFileSize=async(path="data",onread=size=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;onread(filesize);resolve(filesize)})})};var getCSVHeader=async(path="data",onopen=(header,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,65535,0,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();let lines=data.split("\n");let header=lines[0];fs2.close(fd,()=>{onopen(header,path);resolve(header)})}else resolve(void 0)})})})};var writeToCSVFromDB=async(path="data",fileSizeLimitMb=10)=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{if(path!=""){fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;fs2.open(path,"r",(e2,fd)=>{if(e2){reject(e2);return}let i=0;let maxFileSize=fileSizeLimitMb*1024*1024;let end=maxFileSize;if(filesize{if(e3){reject(e3);return}if(bytesRead!==0)CSV.saveCSV(output.toString(),path.split("/")[1]);fs2.close(fd);resolve(true)})}else{const writeChunkToFile=async()=>{if(ifilesize){end=filesize-i}let chunk=0;fs2.read(fd,end,i,"utf-8",(e3,output,bytesRead)=>{if(e3){reject(e3);return}if(bytesRead!==0){CSV.saveCSV(output.toString(),path.split("/")[1]+"_"+chunk);i+=maxFileSize;chunk++;writeChunkToFile();fs2.close(fd);resolve(true)}})}}}})})}else{console.error("File name is not defined.");resolve(false)}})};async function processCSVChunksFromDB(path="data",onData=(csvdata,start2,end2,size)=>{},maxChunkSize=1e4,start=0,end="end",options={}){let size=await getFileSize(path);let partition=start;return await new Promise((res,rej)=>{let processPartition=()=>{let endChunk=partition+maxChunkSize;if(endChunk>size){endChunk=size}readCSVChunkFromDB(path,partition,endChunk,options).then(async result=>{await onData(result,partition,endChunk,size);partition=endChunk;if(partition!==size){processPartition()}else{res(true)}}).catch(rej)};processPartition()})}async function readCSVChunkFromDB(path="data",start=0,end="end",options={}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);const transpose=options.transpose||false;let head=await getCSVHeader(path);if(head)head=head.split(",");else return void 0;let resultLengths=[];let resultNames=[];let results=transpose?[]:{};head.forEach(v=>{if(v){resultNames.push(v);resultLengths.push(1)}else resultLengths[resultLengths.length-1]++});let size=await getFileSize(path);if(end==="end")end=size;else if(end>size){start=size-(end-start);end=size}let data=(await readFileChunk(path,start,end))?.split("\n").slice(1,-1);let preprocess=value=>{try{value=JSON.parse(value)}catch{}return value};if(data)data.forEach((r,i)=>{let row=r.split(",");if(transpose){const entry={};if(options.json)row.forEach((v,idx)=>{if(options.json)entry[resultNames[idx]]=preprocess(v);else entry[resultNames[idx]]=v});results.push(entry)}else{row.forEach((v,i2)=>{const header=resultNames[i2];if(!results[header])results[header]=[];if(options.json)results[header].push(preprocess(v));else results[header].push(v)})}});return results}var directories={};var dirExists=async(fs3,directory)=>{if(!fsInited)await initFS([directory]);return await new Promise((resolve,reject)=>{if(!directory)reject(false);if(directories[directory]==="exists"||directories[directory]==="created"){resolve()}else{if(directory[0]==="/")directory=directory.substring(1);if(!directory)reject(false);fs3.exists(`/${directory}`,exists2=>{if(exists2){directories[directory]="exists";resolve()}else if(directories[directory]==="creating"){resolve()}else{directories[directory]="creating";fs3.mkdir(`/${directory}`,1,err=>{if(err){reject(err);return}directories[directory]="created";setTimeout(resolve,500)})}})}})};var BFSRoutes={initFS,dirExists,exists,readFile,readFileChunk,getFilenames,writeFile,appendFile:appendFile2,deleteFile,readFileAsText,getFileSize,getCSVHeader,listFiles};var CSV_REFERENCE={};function lerp(v0,v1,t){return(1-t)*v0+t*v1}function interpolerp(v0,v1,fit,floor=true){if(fit<=2)return[v0,v1];let a=1/fit;let result=new Array(fit);result[0]=v0;for(let i=1;i<=fit;i++){result[i]=lerp(v0,v1,a*i);if(floor)result[i]=Math.floor(result[i])}return result}var appendCSV=async(newData,filename,header,options)=>{if(!filename){let keys=Object.keys(CSV_REFERENCE);if(keys.length>0)filename=keys[keys.length-1];else filename=`csv${new Date().toISOString()}`}let csv=CSV_REFERENCE[filename];if(!csv){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);CSV_REFERENCE[filename]={header:header?header:["timestamp","localized",...keys],lastX:void 0,buffer:"",buffered:0,bufferSize:options?.bufferSize?options.bufferSize:0,toFixed:options?.toFixed?options.toFixed:0,xIncrement:options?.xIncrement?options.xIncrement:0};csv=CSV_REFERENCE[filename];const existingHeader=await getCSVHeader(filename).catch(()=>null);const isDifferent=!existingHeader||existingHeader!==csv.header.join(",");if(isDifferent)header=csv.header}if(!csv.header||csv.header?.length===0){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);csv.header=header?header:["timestamp","localized",...keys]}else if(header)csv.header=header;let maxLen=1;for(const key in newData){const value=newData[key];if(csv.header.indexOf(key)>-1&&value&&Array.isArray(value)&&value?.length>maxLen)maxLen=value?.length}let x;if(csv.xIncrement){if(!csv.lastX){if(typeof newData[csv.header[0]]!=="undefined"){x=newData[csv.header[0]]}else if(csv.header[0].toLowerCase().includes("time")||csv.header[0].toLowerCase().includes("unix"))x=Date.now()}else{if(newData[csv.header[2]]){if(Array.isArray(newData[csv.header[2]]))x=csv.lastX+csv.xIncrement*newData[csv.header[2]].length;else x=csv.lastX+csv.xIncrement}else if(newData[csv.header[0]]){if(Array.isArray(newData[csv.header[0]]))x=csv.lastX+csv.xIncrement*newData[csv.header[0]].length;else x=csv.lastX+csv.xIncrement}else x=csv.lastX+csv.xIncrement}}else if(newData[csv.header[0]])x=newData[csv.header[0]];else x=Date.now();if(typeof csv.lastX==="undefined")csv.lastX=Array.isArray(x)?x[0]:x;if(typeof x==="undefined"){if(csv.header[0].includes("time")){let now=Date.now();if(maxLen===1)x=Date.now();else{x=interpolerp(csv.lastX,now,maxLen);x.shift()}}else{let newX=csv.lastX+1;if(maxLen>1){x=new Array(maxLen).fill("");x[maxLen-1]=newX}else x=newX}}else if(maxLen>1&&x?.length!==maxLen){if(!Array.isArray(x)||x.length===1){x=interpolerp(csv.lastX,x,maxLen,true);x.shift()}else{x=interpolerp(x[0],x[x.length-1],maxLen,true);x.shift()}}let toAppend=[];if(Array.isArray(x)){let curIdcs={};for(let i=0;icurIdcs[csv.header[j]]){curIdcs[csv.header[j]]++;toAppend[i][j]=d[curIdcs[csv.header[j]]]}else{toAppend[i][j]=""}}}}else{if(i===x.length-1){toAppend[i][j]=d}else{toAppend[i][j]=""}}if(typeof toAppend[i][j]==="number"&&Math.floor(toAppend[i][j])!==toAppend[i][j])toAppend[i][j]=toAppend[i][j].toFixed(CSV_REFERENCE[filename].toFixed)}}}else{toAppend.push([]);for(let j=0;j{csvProcessed+=(options?.json?arr.map(v=>JSON.stringify(v)):arr).join(",")+"\n";if(csv.bufferSize)csv.buffered++});csv.lastX=toAppend[toAppend.length-1][0];if(csv.bufferSize){csv.buffer+=csvProcessed;if(csv.buffered>csv.bufferSize){let r=new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csv.buffer,written=>{res(written)})}else{appendFile2(filename,csv.buffer,written=>{res(written)})}})});await r;csv.buffer="";csv.buffered=0;return r}else return await Promise.resolve(true)}else{return await new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csvProcessed,written=>{res(written)})}else{appendFile2(filename,csvProcessed,written=>{res(written)})}})})}};var updateCSVHeader=(header,filename)=>{if(CSV_REFERENCE[filename]){CSV_REFERENCE[filename].header=header}};var createCSV=(filename,header,toFixed=5,bufferSize=0,xIncrement)=>{if(!CSV_REFERENCE[filename]){if(header?.indexOf("timestamp")>1){header.splice(header.indexOf("timestamp"),1);header.unshift("timestamp")}if((header?.[0].toLowerCase().includes("time")||header?.[0].toLowerCase().includes("unix"))&&header[1]!=="localized"){header.splice(1,0,"localized")}CSV_REFERENCE[filename]={header,lastX:header[1]==="localized"?Date.now():0,bufferSize,buffer:"",buffered:0,toFixed,xIncrement};return new Promise((res,rej)=>{exists(filename).then(doesExist=>{if(!doesExist){writeFile(filename,CSV_REFERENCE[filename].header?CSV_REFERENCE[filename].header.join(",")+"\n":"",written=>{res(written)}).catch(rej)}})})}};var visualizeDirectory=(dir,parentNode=document.body)=>{return new Promise(async(res,rej)=>{if(parentNode.querySelector("#bfs"+dir))parentNode.querySelector("#bfs"+dir)?.remove();parentNode.insertAdjacentHTML("beforeend",`
`);let div=parentNode.querySelector("#bfs"+dir);await listFiles(dir).then(directory=>{if(directory.length===0)div.innerHTML="No Files!";else directory.forEach(listing=>{div?.insertAdjacentHTML("beforeend",`
- Data: - ${listing} - - ${listing.indexOf(".")>-1?``:""} -
`);if(document.getElementById(`delete${listing}`)){document.getElementById(`delete${listing}`).onclick=()=>{deleteFile(dir+"/"+listing,()=>{visualizeDirectory(dir,parentNode)})}}if(document.getElementById(`download${listing}`)){document.getElementById(`download${listing}`).onclick=()=>{writeToCSVFromDB(dir+"/"+listing,10)}}});res(directory)}).catch(rej)})};var csvRoutes={appendCSV,updateCSVHeader,createCSV,visualizeDirectory,openCSV:CSV.openCSV,saveCSV:CSV.saveCSV,openCSVRaw:CSV.openCSVRaw,parseCSVData,getCSVHeader,writeToCSVFromDB,readCSVChunkFromDB,processCSVChunksFromDB,toISOLocal};export{BFSRoutes,CSV,appendCSV,appendFile2 as appendFile,createCSV,csvRoutes,deleteFile,dirExists,exists,fs2 as fs,fsInited,getCSVHeader,getFileSize,getFilenames,initFS,listFiles,parseCSVData,processCSVChunksFromDB,processDataForCSV,readCSVChunkFromDB,readFile,readFileAsText,readFileChunk,toISOLocal,updateCSVHeader,visualizeDirectory,writeFile,writeToCSVFromDB}; -/*! Bundled license information: - -browserfs/dist/browserfs.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) -*/ diff --git a/src/extras/dist/index.storage.services.js b/src/extras/dist/index.storage.services.js deleted file mode 100644 index 40ef601c..00000000 --- a/src/extras/dist/index.storage.services.js +++ /dev/null @@ -1,16 +0,0 @@ -(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browserfs=__commonJS({"node_modules/browserfs/dist/browserfs.js"(exports,module){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["BrowserFS"]=factory();else root["BrowserFS"]=factory()})(exports,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module2=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module2.exports,module2,module2.exports,__webpack_require__);module2.loaded=true;return module2.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module2,exports2,__webpack_require__){(function(Buffer2,global,module3,process){"use strict";Object.defineProperty(exports2,"__esModule",{value:true});var buffer=__webpack_require__(2);var path=__webpack_require__(9);var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2["EPERM"]=1]="EPERM";ErrorCode2[ErrorCode2["ENOENT"]=2]="ENOENT";ErrorCode2[ErrorCode2["EIO"]=5]="EIO";ErrorCode2[ErrorCode2["EBADF"]=9]="EBADF";ErrorCode2[ErrorCode2["EACCES"]=13]="EACCES";ErrorCode2[ErrorCode2["EBUSY"]=16]="EBUSY";ErrorCode2[ErrorCode2["EEXIST"]=17]="EEXIST";ErrorCode2[ErrorCode2["ENOTDIR"]=20]="ENOTDIR";ErrorCode2[ErrorCode2["EISDIR"]=21]="EISDIR";ErrorCode2[ErrorCode2["EINVAL"]=22]="EINVAL";ErrorCode2[ErrorCode2["EFBIG"]=27]="EFBIG";ErrorCode2[ErrorCode2["ENOSPC"]=28]="ENOSPC";ErrorCode2[ErrorCode2["EROFS"]=30]="EROFS";ErrorCode2[ErrorCode2["ENOTEMPTY"]=39]="ENOTEMPTY";ErrorCode2[ErrorCode2["ENOTSUP"]=95]="ENOTSUP"})(ErrorCode||(ErrorCode={}));var ErrorStrings={};ErrorStrings[ErrorCode.EPERM]="Operation not permitted.";ErrorStrings[ErrorCode.ENOENT]="No such file or directory.";ErrorStrings[ErrorCode.EIO]="Input/output error.";ErrorStrings[ErrorCode.EBADF]="Bad file descriptor.";ErrorStrings[ErrorCode.EACCES]="Permission denied.";ErrorStrings[ErrorCode.EBUSY]="Resource busy or locked.";ErrorStrings[ErrorCode.EEXIST]="File exists.";ErrorStrings[ErrorCode.ENOTDIR]="File is not a directory.";ErrorStrings[ErrorCode.EISDIR]="File is a directory.";ErrorStrings[ErrorCode.EINVAL]="Invalid argument.";ErrorStrings[ErrorCode.EFBIG]="File is too big.";ErrorStrings[ErrorCode.ENOSPC]="No space left on disk.";ErrorStrings[ErrorCode.EROFS]="Cannot modify a read-only file system.";ErrorStrings[ErrorCode.ENOTEMPTY]="Directory is not empty.";ErrorStrings[ErrorCode.ENOTSUP]="Operation is not supported.";var ApiError=function(Error2){function ApiError2(type,message,path$$1){if(message===void 0)message=ErrorStrings[type];Error2.call(this,message);this.syscall="";this.errno=type;this.code=ErrorCode[type];this.path=path$$1;this.stack=new Error2().stack;this.message="Error: "+this.code+": "+message+(this.path?", '"+this.path+"'":"")}if(Error2)ApiError2.__proto__=Error2;ApiError2.prototype=Object.create(Error2&&Error2.prototype);ApiError2.prototype.constructor=ApiError2;ApiError2.fromJSON=function fromJSON(json){var err=new ApiError2(0);err.errno=json.errno;err.code=json.code;err.path=json.path;err.stack=json.stack;err.message=json.message;return err};ApiError2.fromBuffer=function fromBuffer(buffer$$1,i2){if(i2===void 0)i2=0;return ApiError2.fromJSON(JSON.parse(buffer$$1.toString("utf8",i2+4,i2+4+buffer$$1.readUInt32LE(i2))))};ApiError2.FileError=function FileError(code,p){return new ApiError2(code,ErrorStrings[code],p)};ApiError2.ENOENT=function ENOENT(path$$1){return this.FileError(ErrorCode.ENOENT,path$$1)};ApiError2.EEXIST=function EEXIST(path$$1){return this.FileError(ErrorCode.EEXIST,path$$1)};ApiError2.EISDIR=function EISDIR(path$$1){return this.FileError(ErrorCode.EISDIR,path$$1)};ApiError2.ENOTDIR=function ENOTDIR(path$$1){return this.FileError(ErrorCode.ENOTDIR,path$$1)};ApiError2.EPERM=function EPERM(path$$1){return this.FileError(ErrorCode.EPERM,path$$1)};ApiError2.ENOTEMPTY=function ENOTEMPTY(path$$1){return this.FileError(ErrorCode.ENOTEMPTY,path$$1)};ApiError2.prototype.toString=function toString(){return this.message};ApiError2.prototype.toJSON=function toJSON(){return{errno:this.errno,code:this.code,path:this.path,stack:this.stack,message:this.message}};ApiError2.prototype.writeToBuffer=function writeToBuffer(buffer$$1,i2){if(buffer$$1===void 0)buffer$$1=Buffer2.alloc(this.bufferSize());if(i2===void 0)i2=0;var bytesWritten=buffer$$1.write(JSON.stringify(this.toJSON()),i2+4);buffer$$1.writeUInt32LE(bytesWritten,i2);return buffer$$1};ApiError2.prototype.bufferSize=function bufferSize(){return 4+Buffer2.byteLength(JSON.stringify(this.toJSON()))};return ApiError2}(Error);var api_error=Object.freeze({get ErrorCode(){return ErrorCode},ErrorStrings,ApiError});var ActionType;(function(ActionType2){ActionType2[ActionType2["NOP"]=0]="NOP";ActionType2[ActionType2["THROW_EXCEPTION"]=1]="THROW_EXCEPTION";ActionType2[ActionType2["TRUNCATE_FILE"]=2]="TRUNCATE_FILE";ActionType2[ActionType2["CREATE_FILE"]=3]="CREATE_FILE"})(ActionType||(ActionType={}));var FileFlag=function FileFlag2(flagStr){this.flagStr=flagStr;if(FileFlag2.validFlagStrs.indexOf(flagStr)<0){throw new ApiError(ErrorCode.EINVAL,"Invalid flag: "+flagStr)}};FileFlag.getFileFlag=function getFileFlag(flagStr){if(FileFlag.flagCache.hasOwnProperty(flagStr)){return FileFlag.flagCache[flagStr]}return FileFlag.flagCache[flagStr]=new FileFlag(flagStr)};FileFlag.prototype.getFlagString=function getFlagString(){return this.flagStr};FileFlag.prototype.isReadable=function isReadable(){return this.flagStr.indexOf("r")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isWriteable=function isWriteable(){return this.flagStr.indexOf("w")!==-1||this.flagStr.indexOf("a")!==-1||this.flagStr.indexOf("+")!==-1};FileFlag.prototype.isTruncating=function isTruncating(){return this.flagStr.indexOf("w")!==-1};FileFlag.prototype.isAppendable=function isAppendable(){return this.flagStr.indexOf("a")!==-1};FileFlag.prototype.isSynchronous=function isSynchronous(){return this.flagStr.indexOf("s")!==-1};FileFlag.prototype.isExclusive=function isExclusive(){return this.flagStr.indexOf("x")!==-1};FileFlag.prototype.pathExistsAction=function pathExistsAction(){if(this.isExclusive()){return ActionType.THROW_EXCEPTION}else if(this.isTruncating()){return ActionType.TRUNCATE_FILE}else{return ActionType.NOP}};FileFlag.prototype.pathNotExistsAction=function pathNotExistsAction(){if((this.isWriteable()||this.isAppendable())&&this.flagStr!=="r+"){return ActionType.CREATE_FILE}else{return ActionType.THROW_EXCEPTION}};FileFlag.flagCache={};FileFlag.validFlagStrs=["r","r+","rs","rs+","w","wx","w+","wx+","a","ax","a+","ax+"];var FileType;(function(FileType2){FileType2[FileType2["FILE"]=32768]="FILE";FileType2[FileType2["DIRECTORY"]=16384]="DIRECTORY";FileType2[FileType2["SYMLINK"]=40960]="SYMLINK"})(FileType||(FileType={}));var Stats=function Stats2(itemType,size,mode,atime,mtime,ctime){if(atime===void 0)atime=new Date;if(mtime===void 0)mtime=new Date;if(ctime===void 0)ctime=new Date;this.size=size;this.atime=atime;this.mtime=mtime;this.ctime=ctime;this.dev=0;this.ino=0;this.rdev=0;this.nlink=1;this.blksize=4096;this.uid=0;this.gid=0;this.birthtime=new Date(0);this.fileData=null;if(!mode){switch(itemType){case FileType.FILE:this.mode=420;break;case FileType.DIRECTORY:default:this.mode=511}}else{this.mode=mode}this.blocks=Math.ceil(size/512);if(this.mode<4096){this.mode|=itemType}};Stats.fromBuffer=function fromBuffer(buffer$$1){var size=buffer$$1.readUInt32LE(0),mode=buffer$$1.readUInt32LE(4),atime=buffer$$1.readDoubleLE(8),mtime=buffer$$1.readDoubleLE(16),ctime=buffer$$1.readDoubleLE(24);return new Stats(mode&61440,size,mode&4095,new Date(atime),new Date(mtime),new Date(ctime))};Stats.prototype.toBuffer=function toBuffer(){var buffer$$1=Buffer2.alloc(32);buffer$$1.writeUInt32LE(this.size,0);buffer$$1.writeUInt32LE(this.mode,4);buffer$$1.writeDoubleLE(this.atime.getTime(),8);buffer$$1.writeDoubleLE(this.mtime.getTime(),16);buffer$$1.writeDoubleLE(this.ctime.getTime(),24);return buffer$$1};Stats.prototype.clone=function clone(){return new Stats(this.mode&61440,this.size,this.mode&4095,this.atime,this.mtime,this.ctime)};Stats.prototype.isFile=function isFile(){return(this.mode&61440)===FileType.FILE};Stats.prototype.isDirectory=function isDirectory(){return(this.mode&61440)===FileType.DIRECTORY};Stats.prototype.isSymbolicLink=function isSymbolicLink(){return(this.mode&61440)===FileType.SYMLINK};Stats.prototype.chmod=function chmod(mode){this.mode=this.mode&61440|mode};Stats.prototype.isSocket=function isSocket(){return false};Stats.prototype.isBlockDevice=function isBlockDevice(){return false};Stats.prototype.isCharacterDevice=function isCharacterDevice(){return false};Stats.prototype.isFIFO=function isFIFO(){return false};var wrapCb=function(cb,numArgs){return cb};function assertRoot(fs4){if(fs4){return fs4}throw new ApiError(ErrorCode.EIO,"Initialize BrowserFS with a file system using BrowserFS.initialize(filesystem)")}function normalizeMode(mode,def){switch(typeof mode){case"number":return mode;case"string":var trueMode=parseInt(mode,8);if(!isNaN(trueMode)){return trueMode}return def;default:return def}}function normalizeTime(time){if(time instanceof Date){return time}else if(typeof time==="number"){return new Date(time*1e3)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid time.")}}function normalizePath(p){if(p.indexOf("\0")>=0){throw new ApiError(ErrorCode.EINVAL,"Path must be a string without null bytes.")}else if(p===""){throw new ApiError(ErrorCode.EINVAL,"Path must not be empty.")}return path.resolve(p)}function normalizeOptions(options,defEnc,defFlag,defMode){switch(typeof options){case"object":return{encoding:typeof options["encoding"]!=="undefined"?options["encoding"]:defEnc,flag:typeof options["flag"]!=="undefined"?options["flag"]:defFlag,mode:normalizeMode(options["mode"],defMode)};case"string":return{encoding:options,flag:defFlag,mode:defMode};default:return{encoding:defEnc,flag:defFlag,mode:defMode}}}function nopCb(){}var FS=function FS2(){this.F_OK=0;this.R_OK=4;this.W_OK=2;this.X_OK=1;this.root=null;this.fdMap={};this.nextFd=100};FS.prototype.initialize=function initialize3(rootFS){if(!rootFS.constructor.isAvailable()){throw new ApiError(ErrorCode.EINVAL,"Tried to instantiate BrowserFS with an unavailable file system.")}return this.root=rootFS};FS.prototype._toUnixTimestamp=function _toUnixTimestamp(time){if(typeof time==="number"){return time}else if(time instanceof Date){return time.getTime()/1e3}throw new Error("Cannot parse time: "+time)};FS.prototype.getRootFS=function getRootFS(){if(this.root){return this.root}else{return null}};FS.prototype.rename=function rename(oldPath,newPath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).rename(normalizePath(oldPath),normalizePath(newPath),newCb)}catch(e){newCb(e)}};FS.prototype.renameSync=function renameSync(oldPath,newPath){assertRoot(this.root).renameSync(normalizePath(oldPath),normalizePath(newPath))};FS.prototype.exists=function exists2(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).exists(normalizePath(path$$1),newCb)}catch(e){return newCb(false)}};FS.prototype.existsSync=function existsSync(path$$1){try{return assertRoot(this.root).existsSync(normalizePath(path$$1))}catch(e){return false}};FS.prototype.stat=function stat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),false,newCb)}catch(e){return newCb(e)}};FS.prototype.statSync=function statSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),false)};FS.prototype.lstat=function lstat(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{return assertRoot(this.root).stat(normalizePath(path$$1),true,newCb)}catch(e){return newCb(e)}};FS.prototype.lstatSync=function lstatSync(path$$1){return assertRoot(this.root).statSync(normalizePath(path$$1),true)};FS.prototype.truncate=function truncate(path$$1,arg2,cb){if(arg2===void 0)arg2=0;if(cb===void 0)cb=nopCb;var len=0;if(typeof arg2==="function"){cb=arg2}else if(typeof arg2==="number"){len=arg2}var newCb=wrapCb(cb,1);try{if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncate(normalizePath(path$$1),len,newCb)}catch(e){return newCb(e)}};FS.prototype.truncateSync=function truncateSync(path$$1,len){if(len===void 0)len=0;if(len<0){throw new ApiError(ErrorCode.EINVAL)}return assertRoot(this.root).truncateSync(normalizePath(path$$1),len)};FS.prototype.unlink=function unlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{return assertRoot(this.root).unlink(normalizePath(path$$1),newCb)}catch(e){return newCb(e)}};FS.prototype.unlinkSync=function unlinkSync(path$$1){return assertRoot(this.root).unlinkSync(normalizePath(path$$1))};FS.prototype.open=function open(path$$1,flag,arg2,cb){var this$1=this;if(cb===void 0)cb=nopCb;var mode=normalizeMode(arg2,420);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{assertRoot(this.root).open(normalizePath(path$$1),FileFlag.getFileFlag(flag),mode,function(e,file){if(file){newCb(e,this$1.getFdForFile(file))}else{newCb(e)}})}catch(e){newCb(e)}};FS.prototype.openSync=function openSync(path$$1,flag,mode){if(mode===void 0)mode=420;return this.getFdForFile(assertRoot(this.root).openSync(normalizePath(path$$1),FileFlag.getFileFlag(flag),normalizeMode(mode,420)))};FS.prototype.readFile=function readFile2(filename,arg2,cb){if(arg2===void 0)arg2={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg2,null,"r",null);cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,2);try{var flag=FileFlag.getFileFlag(options["flag"]);if(!flag.isReadable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading."))}return assertRoot(this.root).readFile(normalizePath(filename),options.encoding,flag,newCb)}catch(e){return newCb(e)}};FS.prototype.readFileSync=function readFileSync(filename,arg2){if(arg2===void 0)arg2={};var options=normalizeOptions(arg2,null,"r",null);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isReadable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to readFile must allow for reading.")}return assertRoot(this.root).readFileSync(normalizePath(filename),options.encoding,flag)};FS.prototype.writeFile=function writeFile2(filename,data,arg3,cb){if(arg3===void 0)arg3={};if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","w",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing."))}return assertRoot(this.root).writeFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){return newCb(e)}};FS.prototype.writeFileSync=function writeFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","w",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isWriteable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to writeFile must allow for writing.")}return assertRoot(this.root).writeFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.appendFile=function appendFile3(filename,data,arg3,cb){if(cb===void 0)cb=nopCb;var options=normalizeOptions(arg3,"utf8","a",420);cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){return newCb(new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending."))}assertRoot(this.root).appendFile(normalizePath(filename),data,options.encoding,flag,options.mode,newCb)}catch(e){newCb(e)}};FS.prototype.appendFileSync=function appendFileSync(filename,data,arg3){var options=normalizeOptions(arg3,"utf8","a",420);var flag=FileFlag.getFileFlag(options.flag);if(!flag.isAppendable()){throw new ApiError(ErrorCode.EINVAL,"Flag passed to appendFile must allow for appending.")}return assertRoot(this.root).appendFileSync(normalizePath(filename),data,options.encoding,flag,options.mode)};FS.prototype.fstat=function fstat(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{var file=this.fd2file(fd);file.stat(newCb)}catch(e){newCb(e)}};FS.prototype.fstatSync=function fstatSync(fd){return this.fd2file(fd).statSync()};FS.prototype.close=function close(fd,cb){var this$1=this;if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).close(function(e){if(!e){this$1.closeFd(fd)}newCb(e)})}catch(e){newCb(e)}};FS.prototype.closeSync=function closeSync(fd){this.fd2file(fd).closeSync();this.closeFd(fd)};FS.prototype.ftruncate=function ftruncate(fd,arg2,cb){if(cb===void 0)cb=nopCb;var length=typeof arg2==="number"?arg2:0;cb=typeof arg2==="function"?arg2:cb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(length<0){throw new ApiError(ErrorCode.EINVAL)}file.truncate(length,newCb)}catch(e){newCb(e)}};FS.prototype.ftruncateSync=function ftruncateSync(fd,len){if(len===void 0)len=0;var file=this.fd2file(fd);if(len<0){throw new ApiError(ErrorCode.EINVAL)}file.truncateSync(len)};FS.prototype.fsync=function fsync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).sync(newCb)}catch(e){newCb(e)}};FS.prototype.fsyncSync=function fsyncSync(fd){this.fd2file(fd).syncSync()};FS.prototype.fdatasync=function fdatasync(fd,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{this.fd2file(fd).datasync(newCb)}catch(e){newCb(e)}};FS.prototype.fdatasyncSync=function fdatasyncSync(fd){this.fd2file(fd).datasyncSync()};FS.prototype.write=function write(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var buffer$$1,offset,length,position=null;if(typeof arg2==="string"){var encoding="utf8";switch(typeof arg3){case"function":cb=arg3;break;case"number":position=arg3;encoding=typeof arg4==="string"?arg4:"utf8";cb=typeof arg5==="function"?arg5:cb;break;default:cb=typeof arg4==="function"?arg4:typeof arg5==="function"?arg5:cb;return cb(new ApiError(ErrorCode.EINVAL,"Invalid arguments."))}buffer$$1=Buffer2.from(arg2,encoding);offset=0;length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null;cb=typeof arg5==="function"?arg5:cb}var newCb=wrapCb(cb,3);try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.write(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.writeSync=function writeSync(fd,arg2,arg3,arg4,arg5){var buffer$$1,offset=0,length,position;if(typeof arg2==="string"){position=typeof arg3==="number"?arg3:null;var encoding=typeof arg4==="string"?arg4:"utf8";offset=0;buffer$$1=Buffer2.from(arg2,encoding);length=buffer$$1.length}else{buffer$$1=arg2;offset=arg3;length=arg4;position=typeof arg5==="number"?arg5:null}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}return file.writeSync(buffer$$1,offset,length,position)};FS.prototype.read=function read(fd,arg2,arg3,arg4,arg5,cb){if(cb===void 0)cb=nopCb;var position,offset,length,buffer$$1,newCb;if(typeof arg2==="number"){length=arg2;position=arg3;var encoding=arg4;cb=typeof arg5==="function"?arg5:cb;offset=0;buffer$$1=Buffer2.alloc(length);newCb=wrapCb(function(err,bytesRead,buf){if(err){return cb(err)}cb(err,buf.toString(encoding),bytesRead)},3)}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5;newCb=wrapCb(cb,3)}try{var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}file.read(buffer$$1,offset,length,position,newCb)}catch(e){newCb(e)}};FS.prototype.readSync=function readSync(fd,arg2,arg3,arg4,arg5){var shenanigans=false;var buffer$$1,offset,length,position,encoding="utf8";if(typeof arg2==="number"){length=arg2;position=arg3;encoding=arg4;offset=0;buffer$$1=Buffer2.alloc(length);shenanigans=true}else{buffer$$1=arg2;offset=arg3;length=arg4;position=arg5}var file=this.fd2file(fd);if(position===void 0||position===null){position=file.getPos()}var rv=file.readSync(buffer$$1,offset,length,position);if(!shenanigans){return rv}else{return[buffer$$1.toString(encoding),rv]}};FS.prototype.fchown=function fchown(fd,uid,gid,callback){if(callback===void 0)callback=nopCb;var newCb=wrapCb(callback,1);try{this.fd2file(fd).chown(uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.fchownSync=function fchownSync(fd,uid,gid){this.fd2file(fd).chownSync(uid,gid)};FS.prototype.fchmod=function fchmod(fd,mode,cb){var newCb=wrapCb(cb,1);try{var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmod(numMode,newCb)}catch(e){newCb(e)}};FS.prototype.fchmodSync=function fchmodSync(fd,mode){var numMode=typeof mode==="string"?parseInt(mode,8):mode;this.fd2file(fd).chmodSync(numMode)};FS.prototype.futimes=function futimes(fd,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var file=this.fd2file(fd);if(typeof atime==="number"){atime=new Date(atime*1e3)}if(typeof mtime==="number"){mtime=new Date(mtime*1e3)}file.utimes(atime,mtime,newCb)}catch(e){newCb(e)}};FS.prototype.futimesSync=function futimesSync(fd,atime,mtime){this.fd2file(fd).utimesSync(normalizeTime(atime),normalizeTime(mtime))};FS.prototype.rmdir=function rmdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).rmdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.rmdirSync=function rmdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).rmdirSync(path$$1)};FS.prototype.mkdir=function mkdir(path$$1,mode,cb){if(cb===void 0)cb=nopCb;if(typeof mode==="function"){cb=mode;mode=511}var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).mkdir(path$$1,mode,newCb)}catch(e){newCb(e)}};FS.prototype.mkdirSync=function mkdirSync(path$$1,mode){assertRoot(this.root).mkdirSync(normalizePath(path$$1),normalizeMode(mode,511))};FS.prototype.readdir=function readdir(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readdir(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readdirSync=function readdirSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readdirSync(path$$1)};FS.prototype.link=function link(srcpath,dstpath,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).link(srcpath,dstpath,newCb)}catch(e){newCb(e)}};FS.prototype.linkSync=function linkSync(srcpath,dstpath){srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).linkSync(srcpath,dstpath)};FS.prototype.symlink=function symlink(srcpath,dstpath,arg3,cb){if(cb===void 0)cb=nopCb;var type=typeof arg3==="string"?arg3:"file";cb=typeof arg3==="function"?arg3:cb;var newCb=wrapCb(cb,1);try{if(type!=="file"&&type!=="dir"){return newCb(new ApiError(ErrorCode.EINVAL,"Invalid type: "+type))}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);assertRoot(this.root).symlink(srcpath,dstpath,type,newCb)}catch(e){newCb(e)}};FS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(!type){type="file"}else if(type!=="file"&&type!=="dir"){throw new ApiError(ErrorCode.EINVAL,"Invalid type: "+type)}srcpath=normalizePath(srcpath);dstpath=normalizePath(dstpath);return assertRoot(this.root).symlinkSync(srcpath,dstpath,type)};FS.prototype.readlink=function readlink(path$$1,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).readlink(path$$1,newCb)}catch(e){newCb(e)}};FS.prototype.readlinkSync=function readlinkSync(path$$1){path$$1=normalizePath(path$$1);return assertRoot(this.root).readlinkSync(path$$1)};FS.prototype.chown=function chown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,false,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.chownSync=function chownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,false,uid,gid)};FS.prototype.lchown=function lchown(path$$1,uid,gid,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{path$$1=normalizePath(path$$1);assertRoot(this.root).chown(path$$1,true,uid,gid,newCb)}catch(e){newCb(e)}};FS.prototype.lchownSync=function lchownSync(path$$1,uid,gid){path$$1=normalizePath(path$$1);assertRoot(this.root).chownSync(path$$1,true,uid,gid)};FS.prototype.chmod=function chmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),false,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.chmodSync=function chmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}path$$1=normalizePath(path$$1);assertRoot(this.root).chmodSync(path$$1,false,numMode)};FS.prototype.lchmod=function lchmod(path$$1,mode,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{var numMode=normalizeMode(mode,-1);if(numMode<0){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmod(normalizePath(path$$1),true,numMode,newCb)}catch(e){newCb(e)}};FS.prototype.lchmodSync=function lchmodSync(path$$1,mode){var numMode=normalizeMode(mode,-1);if(numMode<1){throw new ApiError(ErrorCode.EINVAL,"Invalid mode.")}assertRoot(this.root).chmodSync(normalizePath(path$$1),true,numMode)};FS.prototype.utimes=function utimes(path$$1,atime,mtime,cb){if(cb===void 0)cb=nopCb;var newCb=wrapCb(cb,1);try{assertRoot(this.root).utimes(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime),newCb)}catch(e){newCb(e)}};FS.prototype.utimesSync=function utimesSync(path$$1,atime,mtime){assertRoot(this.root).utimesSync(normalizePath(path$$1),normalizeTime(atime),normalizeTime(mtime))};FS.prototype.realpath=function realpath(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;var cache=typeof arg2==="object"?arg2:{};cb=typeof arg2==="function"?arg2:nopCb;var newCb=wrapCb(cb,2);try{path$$1=normalizePath(path$$1);assertRoot(this.root).realpath(path$$1,cache,newCb)}catch(e){newCb(e)}};FS.prototype.realpathSync=function realpathSync(path$$1,cache){if(cache===void 0)cache={};path$$1=normalizePath(path$$1);return assertRoot(this.root).realpathSync(path$$1,cache)};FS.prototype.watchFile=function watchFile(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.unwatchFile=function unwatchFile(filename,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.watch=function watch(filename,arg2,listener){if(listener===void 0)listener=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.access=function access(path$$1,arg2,cb){if(cb===void 0)cb=nopCb;throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.accessSync=function accessSync(path$$1,mode){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createReadStream=function createReadStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.createWriteStream=function createWriteStream(path$$1,options){throw new ApiError(ErrorCode.ENOTSUP)};FS.prototype.wrapCallbacks=function wrapCallbacks(cbWrapper){wrapCb=cbWrapper};FS.prototype.getFdForFile=function getFdForFile(file){var fd=this.nextFd++;this.fdMap[fd]=file;return fd};FS.prototype.fd2file=function fd2file(fd){var rv=this.fdMap[fd];if(rv){return rv}else{throw new ApiError(ErrorCode.EBADF,"Invalid file descriptor.")}};FS.prototype.closeFd=function closeFd(fd){delete this.fdMap[fd]};FS.Stats=Stats;var fs3=new FS;var _fsMock={};var fsProto=FS.prototype;Object.keys(fsProto).forEach(function(key){if(typeof fs3[key]==="function"){_fsMock[key]=function(){return fs3[key].apply(fs3,arguments)}}else{_fsMock[key]=fs3[key]}});_fsMock["changeFSModule"]=function(newFs){fs3=newFs};_fsMock["getFSModule"]=function(){return fs3};_fsMock["FS"]=FS;function _min(d0,d1,d2,bx,ay){return d0d2?d2+1:d0+1:bx===ay?d1:d1+1}function levenshtein(a,b){if(a===b){return 0}if(a.length>b.length){var tmp=a;a=b;b=tmp}var la=a.length;var lb=b.length;while(la>0&&a.charCodeAt(la-1)===b.charCodeAt(lb-1)){la--;lb--}var offset=0;while(offsetdd?dd+1:dy$1+1:bx0$1===vector[la+y$2]?d0:d0+1;d0=dy$1}}return dd}function deprecationMessage(print,fsName,opts){if(print){console.warn("["+fsName+"] Direct file system constructor usage is deprecated for this file system, and will be removed in the next major version. Please use the '"+fsName+".Create("+JSON.stringify(opts)+", callback)' method instead. See https://github.com/jvilk/BrowserFS/issues/176 for more details.")}}var isIE=typeof navigator!=="undefined"&&!!(/(msie) ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||navigator.userAgent.indexOf("Trident")!==-1);var isWebWorker=typeof window==="undefined";function fail(){throw new Error("BFS has reached an impossible code path; please file a bug.")}function mkdirpSync(p,mode,fs4){if(!fs4.existsSync(p)){mkdirpSync(path.dirname(p),mode,fs4);fs4.mkdirSync(p,mode)}}function buffer2ArrayBuffer(buff){var u8=buffer2Uint8array(buff),u8offset=u8.byteOffset,u8Len=u8.byteLength;if(u8offset===0&&u8Len===u8.buffer.byteLength){return u8.buffer}else{return u8.buffer.slice(u8offset,u8offset+u8Len)}}function buffer2Uint8array(buff){if(buff instanceof Uint8Array){return buff}else{return new Uint8Array(buff)}}function arrayish2Buffer(arr){if(arr instanceof Buffer2){return arr}else if(arr instanceof Uint8Array){return uint8Array2Buffer(arr)}else{return Buffer2.from(arr)}}function uint8Array2Buffer(u8){if(u8 instanceof Buffer2){return u8}else if(u8.byteOffset===0&&u8.byteLength===u8.buffer.byteLength){return arrayBuffer2Buffer(u8.buffer)}else{return Buffer2.from(u8.buffer,u8.byteOffset,u8.byteLength)}}function arrayBuffer2Buffer(ab){return Buffer2.from(ab)}function copyingSlice(buff,start,end){if(start===void 0)start=0;if(end===void 0)end=buff.length;if(start<0||end<0||end>buff.length||start>end){throw new TypeError("Invalid slice bounds on buffer of length "+buff.length+": ["+start+", "+end+"]")}if(buff.length===0){return emptyBuffer()}else{var u8=buffer2Uint8array(buff),s0=buff[0],newS0=(s0+1)%255;buff[0]=newS0;if(u8[0]===newS0){u8[0]=s0;return uint8Array2Buffer(u8.slice(start,end))}else{buff[0]=s0;return uint8Array2Buffer(u8.subarray(start,end))}}}var emptyBuff=null;function emptyBuffer(){if(emptyBuff){return emptyBuff}return emptyBuff=Buffer2.alloc(0)}function bufferValidator(v,cb){if(Buffer2.isBuffer(v)){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"option must be a Buffer."))}}function checkOptions(fsType,opts,cb){var optsInfo=fsType.Options;var fsName=fsType.Name;var pendingValidators=0;var callbackCalled=false;var loopEnded=false;function validatorCallback(e){if(!callbackCalled){if(e){callbackCalled=true;cb(e)}pendingValidators--;if(pendingValidators===0&&loopEnded){cb()}}}var loop=function(optName2){if(optsInfo.hasOwnProperty(optName2)){var opt=optsInfo[optName2];var providedValue=opts[optName2];if(providedValue===void 0||providedValue===null){if(!opt.optional){var incorrectOptions=Object.keys(opts).filter(function(o){return!(o in optsInfo)}).map(function(a){return{str:a,distance:levenshtein(optName2,a)}}).filter(function(o){return o.distance<5}).sort(function(a,b){return a.distance-b.distance});if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Required option '"+optName2+"' not provided."+(incorrectOptions.length>0?" You provided unrecognized option '"+incorrectOptions[0].str+"'; perhaps you meant to type '"+optName2+"'.":"")+"\nOption description: "+opt.description))}}}else{var typeMatches=false;if(Array.isArray(opt.type)){typeMatches=opt.type.indexOf(typeof providedValue)!==-1}else{typeMatches=typeof providedValue===opt.type}if(!typeMatches){if(callbackCalled){return{}}callbackCalled=true;return{v:cb(new ApiError(ErrorCode.EINVAL,"["+fsName+"] Value provided for option "+optName2+" is not the proper type. Expected "+(Array.isArray(opt.type)?"one of {"+opt.type.join(", ")+"}":opt.type)+", but received "+typeof providedValue+"\nOption description: "+opt.description))}}else if(opt.validator){pendingValidators++;opt.validator(providedValue,validatorCallback)}}}};for(var optName in optsInfo){var returned=loop(optName);if(returned)return returned.v}loopEnded=true;if(pendingValidators===0&&!callbackCalled){cb()}}var BFSUtils=Object.freeze({deprecationMessage,isIE,isWebWorker,fail,mkdirpSync,buffer2ArrayBuffer,buffer2Uint8array,arrayish2Buffer,uint8Array2Buffer,arrayBuffer2Buffer,copyingSlice,emptyBuffer,bufferValidator,checkOptions});var BFSEmscriptenStreamOps=function BFSEmscriptenStreamOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenStreamOps.prototype.open=function open(stream){var path$$1=this.fs.realPath(stream.node);var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)){stream.nfd=this.nodefs.openSync(path$$1,this.fs.flagsToPermissionString(stream.flags))}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.close=function close(stream){var FS2=this.FS;try{if(FS2.isFile(stream.node.mode)&&stream.nfd){this.nodefs.closeSync(stream.nfd)}}catch(e){if(!e.code){throw e}throw new FS2.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.read=function read(stream,buffer$$1,offset,length,position){try{return this.nodefs.readSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.write=function write(stream,buffer$$1,offset,length,position){try{return this.nodefs.writeSync(stream.nfd,uint8Array2Buffer(buffer$$1),offset,length,position)}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenStreamOps.prototype.llseek=function llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(this.FS.isFile(stream.node.mode)){try{var stat=this.nodefs.fstatSync(stream.nfd);position+=stat.size}catch(e){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}}if(position<0){throw new this.FS.ErrnoError(this.ERRNO_CODES.EINVAL)}stream.position=position;return position};var BFSEmscriptenNodeOps=function BFSEmscriptenNodeOps2(fs4){this.fs=fs4;this.nodefs=fs4.getNodeFS();this.FS=fs4.getFS();this.PATH=fs4.getPATH();this.ERRNO_CODES=fs4.getERRNO_CODES()};BFSEmscriptenNodeOps.prototype.getattr=function getattr(node){var path$$1=this.fs.realPath(node);var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}};BFSEmscriptenNodeOps.prototype.setattr=function setattr(node,attr){var path$$1=this.fs.realPath(node);try{if(attr.mode!==void 0){this.nodefs.chmodSync(path$$1,attr.mode);node.mode=attr.mode}if(attr.timestamp!==void 0){var date=new Date(attr.timestamp);this.nodefs.utimesSync(path$$1,date,date)}}catch(e){if(!e.code){throw e}if(e.code!=="ENOTSUP"){throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}if(attr.size!==void 0){try{this.nodefs.truncateSync(path$$1,attr.size)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}}};BFSEmscriptenNodeOps.prototype.lookup=function lookup(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);var mode=this.fs.getMode(path$$1);return this.fs.createNode(parent,name,mode)};BFSEmscriptenNodeOps.prototype.mknod=function mknod(parent,name,mode,dev){var node=this.fs.createNode(parent,name,mode,dev);var path$$1=this.fs.realPath(node);try{if(this.FS.isDir(node.mode)){this.nodefs.mkdirSync(path$$1,node.mode)}else{this.nodefs.writeFileSync(path$$1,"",{mode:node.mode})}}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return node};BFSEmscriptenNodeOps.prototype.rename=function rename(oldNode,newDir,newName){var oldPath=this.fs.realPath(oldNode);var newPath=this.PATH.join2(this.fs.realPath(newDir),newName);try{this.nodefs.renameSync(oldPath,newPath);oldNode.name=newName;oldNode.parent=newDir}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.unlink=function unlink(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.unlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.rmdir=function rmdir(parent,name){var path$$1=this.PATH.join2(this.fs.realPath(parent),name);try{this.nodefs.rmdirSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readdir=function readdir(node){var path$$1=this.fs.realPath(node);try{var contents=this.nodefs.readdirSync(path$$1);contents.push(".","..");return contents}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.symlink=function symlink(parent,newName,oldPath){var newPath=this.PATH.join2(this.fs.realPath(parent),newName);try{this.nodefs.symlinkSync(oldPath,newPath)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};BFSEmscriptenNodeOps.prototype.readlink=function readlink(node){var path$$1=this.fs.realPath(node);try{return this.nodefs.readlinkSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}};var BFSEmscriptenFS=function BFSEmscriptenFS2(_FS,_PATH,_ERRNO_CODES,nodefs){if(_FS===void 0)_FS=self["FS"];if(_PATH===void 0)_PATH=self["PATH"];if(_ERRNO_CODES===void 0)_ERRNO_CODES=self["ERRNO_CODES"];if(nodefs===void 0)nodefs=_fsMock;this.flagsToPermissionStringMap={0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"};this.nodefs=nodefs;this.FS=_FS;this.PATH=_PATH;this.ERRNO_CODES=_ERRNO_CODES;this.node_ops=new BFSEmscriptenNodeOps(this);this.stream_ops=new BFSEmscriptenStreamOps(this)};BFSEmscriptenFS.prototype.mount=function mount(m){return this.createNode(null,"/",this.getMode(m.opts.root),0)};BFSEmscriptenFS.prototype.createNode=function createNode(parent,name,mode,dev){var FS2=this.FS;if(!FS2.isDir(mode)&&!FS2.isFile(mode)&&!FS2.isLink(mode)){throw new FS2.ErrnoError(this.ERRNO_CODES.EINVAL)}var node=FS2.createNode(parent,name,mode);node.node_ops=this.node_ops;node.stream_ops=this.stream_ops;return node};BFSEmscriptenFS.prototype.getMode=function getMode(path$$1){var stat;try{stat=this.nodefs.lstatSync(path$$1)}catch(e){if(!e.code){throw e}throw new this.FS.ErrnoError(this.ERRNO_CODES[e.code])}return stat.mode};BFSEmscriptenFS.prototype.realPath=function realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return this.PATH.join.apply(null,parts)};BFSEmscriptenFS.prototype.flagsToPermissionString=function flagsToPermissionString(flags){var parsedFlags=typeof flags==="string"?parseInt(flags,10):flags;parsedFlags&=8191;if(parsedFlags in this.flagsToPermissionStringMap){return this.flagsToPermissionStringMap[parsedFlags]}else{return flags}};BFSEmscriptenFS.prototype.getNodeFS=function getNodeFS(){return this.nodefs};BFSEmscriptenFS.prototype.getFS=function getFS(){return this.FS};BFSEmscriptenFS.prototype.getPATH=function getPATH(){return this.PATH};BFSEmscriptenFS.prototype.getERRNO_CODES=function getERRNO_CODES(){return this.ERRNO_CODES};var BaseFileSystem=function BaseFileSystem2(){};BaseFileSystem.prototype.supportsLinks=function supportsLinks(){return false};BaseFileSystem.prototype.diskSpace=function diskSpace(p,cb){cb(0,0)};BaseFileSystem.prototype.openFile=function openFile(p,flag,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFile=function createFile(p,flag,mode,cb){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.open=function open(p,flag,mode,cb){var this$1=this;var mustBeFile=function(e,stats){if(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.stat(path.dirname(p),false,function(e2,parentStats){if(e2){cb(e2)}else if(parentStats&&!parentStats.isDirectory()){cb(ApiError.ENOTDIR(path.dirname(p)))}else{this$1.createFile(p,flag,mode,cb)}});case ActionType.THROW_EXCEPTION:return cb(ApiError.ENOENT(p));default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}else{if(stats&&stats.isDirectory()){return cb(ApiError.EISDIR(p))}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:return cb(ApiError.EEXIST(p));case ActionType.TRUNCATE_FILE:return this$1.openFile(p,flag,function(e2,fd){if(e2){cb(e2)}else if(fd){fd.truncate(0,function(){fd.sync(function(){cb(null,fd)})})}else{fail()}});case ActionType.NOP:return this$1.openFile(p,flag,cb);default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object."))}}};this.stat(p,false,mustBeFile)};BaseFileSystem.prototype.rename=function rename(oldPath,newPath,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.renameSync=function renameSync(oldPath,newPath){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.stat=function stat(p,isLstat,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.statSync=function statSync(p,isLstat){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openFileSync=function openFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.createFileSync=function createFileSync(p,flag,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.openSync=function openSync(p,flag,mode){var stats;try{stats=this.statSync(p,false)}catch(e){switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:var parentStats=this.statSync(path.dirname(p),false);if(!parentStats.isDirectory()){throw ApiError.ENOTDIR(path.dirname(p))}return this.createFileSync(p,flag,mode);case ActionType.THROW_EXCEPTION:throw ApiError.ENOENT(p);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}}if(stats.isDirectory()){throw ApiError.EISDIR(p)}switch(flag.pathExistsAction()){case ActionType.THROW_EXCEPTION:throw ApiError.EEXIST(p);case ActionType.TRUNCATE_FILE:this.unlinkSync(p);return this.createFileSync(p,flag,stats.mode);case ActionType.NOP:return this.openFileSync(p,flag,mode);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileFlag object.")}};BaseFileSystem.prototype.unlink=function unlink(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.unlinkSync=function unlinkSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.rmdir=function rmdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.rmdirSync=function rmdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.mkdir=function mkdir(p,mode,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.mkdirSync=function mkdirSync(p,mode){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.readdir=function readdir(p,cb){cb(new ApiError(ErrorCode.ENOTSUP))};BaseFileSystem.prototype.readdirSync=function readdirSync(p){throw new ApiError(ErrorCode.ENOTSUP)};BaseFileSystem.prototype.exists=function exists2(p,cb){this.stat(p,null,function(err){cb(!err)})};BaseFileSystem.prototype.existsSync=function existsSync(p){try{this.statSync(p,true);return true}catch(e){return false}};BaseFileSystem.prototype.realpath=function realpath(p,cache,cb){if(this.supportsLinks()){var splitPath=p.split(path.sep);for(var i2=0;i2this._buffer.length){var buf=Buffer2.alloc(len-this._buffer.length,0);this.writeSync(buf,0,buf.length,this._buffer.length);if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}return}this._stat.size=len;var newBuff=Buffer2.alloc(len);this._buffer.copy(newBuff,0,0,len);this._buffer=newBuff;if(this._flag.isSynchronous()&&_fsMock.getRootFS().supportsSynch()){this.syncSync()}};PreloadFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){this._dirty=true;if(position===void 0||position===null){position=this.getPos()}if(!this._flag.isWriteable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a writeable mode.")}var endFp=position+length;if(endFp>this._stat.size){this._stat.size=endFp;if(endFp>this._buffer.length){var newBuff=Buffer2.alloc(endFp);this._buffer.copy(newBuff);this._buffer=newBuff}}var len=buffer$$1.copy(this._buffer,position,offset,offset+length);this._stat.mtime=new Date;if(this._flag.isSynchronous()){this.syncSync();return len}this.setPos(position+len);return len};PreloadFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};PreloadFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){if(!this._flag.isReadable()){throw new ApiError(ErrorCode.EPERM,"File not opened with a readable mode.")}if(position===void 0||position===null){position=this.getPos()}var endRead=position+length;if(endRead>this._stat.size){length=this._stat.size-position}var rv=this._buffer.copy(buffer$$1,offset,position,position+length);this._stat.atime=new Date;this._pos=position+length;return rv};PreloadFile2.prototype.chmod=function chmod(mode,cb){try{this.chmodSync(mode);cb()}catch(e){cb(e)}};PreloadFile2.prototype.chmodSync=function chmodSync(mode){if(!this._fs.supportsProps()){throw new ApiError(ErrorCode.ENOTSUP)}this._dirty=true;this._stat.chmod(mode);this.syncSync()};PreloadFile2.prototype.isDirty=function isDirty(){return this._dirty};PreloadFile2.prototype.resetDirty=function resetDirty(){this._dirty=false};return PreloadFile2}(BaseFile);var NoSyncFile=function(PreloadFile2){function NoSyncFile2(_fs,_path,_flag,_stat,contents){PreloadFile2.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile2)NoSyncFile2.__proto__=PreloadFile2;NoSyncFile2.prototype=Object.create(PreloadFile2&&PreloadFile2.prototype);NoSyncFile2.prototype.constructor=NoSyncFile2;NoSyncFile2.prototype.sync=function sync(cb){cb()};NoSyncFile2.prototype.syncSync=function syncSync(){};NoSyncFile2.prototype.close=function close(cb){cb()};NoSyncFile2.prototype.closeSync=function closeSync(){};return NoSyncFile2}(PreloadFile);var MirrorFile=function(PreloadFile$$1){function MirrorFile2(fs4,path$$1,flag,stat,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,data)}if(PreloadFile$$1)MirrorFile2.__proto__=PreloadFile$$1;MirrorFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);MirrorFile2.prototype.constructor=MirrorFile2;MirrorFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};MirrorFile2.prototype.closeSync=function closeSync(){this.syncSync()};return MirrorFile2}(PreloadFile);var AsyncMirror=function(SynchronousFileSystem$$1){function AsyncMirror2(sync,async,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this._queue=[];this._queueRunning=false;this._isInitialized=false;this._initializeCallbacks=[];this._sync=sync;this._async=async;if(!sync.supportsSynch()){throw new Error("The first argument to AsyncMirror needs to be a synchronous file system.")}deprecationMessage(deprecateMsg,AsyncMirror2.Name,{sync:"sync file system instance",async:"async file system instance"})}if(SynchronousFileSystem$$1)AsyncMirror2.__proto__=SynchronousFileSystem$$1;AsyncMirror2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);AsyncMirror2.prototype.constructor=AsyncMirror2;AsyncMirror2.Create=function Create(opts,cb){try{var fs4=new AsyncMirror2(opts.sync,opts.async,false);fs4.initialize(function(e){if(e){cb(e)}else{cb(null,fs4)}},false)}catch(e){cb(e)}};AsyncMirror2.isAvailable=function isAvailable(){return true};AsyncMirror2.prototype.getName=function getName(){return AsyncMirror2.Name};AsyncMirror2.prototype._syncSync=function _syncSync(fd){this._sync.writeFileSync(fd.getPath(),fd.getBuffer(),null,FileFlag.getFileFlag("w"),fd.getStats().mode);this.enqueueOp({apiMethod:"writeFile",arguments:[fd.getPath(),fd.getBuffer(),null,fd.getFlag(),fd.getStats().mode]})};AsyncMirror2.prototype.initialize=function initialize3(userCb,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[AsyncMirror] AsyncMirror.initialize() is deprecated and will be removed in the next major version. Please use 'AsyncMirror.Create({ sync: (sync file system instance), async: (async file system instance)}, cb)' to create and initialize AsyncMirror instances.")}var callbacks=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbacks.forEach(function(cb){return cb(e)})};if(!this._isInitialized){if(callbacks.push(userCb)===1){var copyDirectory=function(p,mode,cb){if(p!=="/"){this$1._sync.mkdirSync(p,mode)}this$1._async.readdir(p,function(err,files){var i2=0;function copyNextFile(err2){if(err2){cb(err2)}else if(i20){var op2=this$1._queue.shift(),args=op2.arguments;args.push(doNextOp);this$1._async[op2.apiMethod].apply(this$1._async,args)}else{this$1._queueRunning=false}};doNextOp()}};return AsyncMirror2}(SynchronousFileSystem);AsyncMirror.Name="AsyncMirror";AsyncMirror.Options={sync:{type:"object",description:"The synchronous file system to mirror the asynchronous file system to."},async:{type:"object",description:"The asynchronous file system to mirror."}};function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}var nativeMax=Math.max;function overRest$1(func,start,transform){start=nativeMax(start===void 0?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}var breakLoop={};function noop(){}function once(fn){return function(){if(fn===null){return}var callFn=fn;fn=null;callFn.apply(this,arguments)}}var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator;var getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()};function baseTimes(n,iteratee){var index=-1,result=Array(n);while(++index-1&&value%1==0&&value++numRun){switch(error.status){case Dropbox.ApiError.SERVER_ERROR:case Dropbox.ApiError.NETWORK_ERROR:case Dropbox.ApiError.RATE_LIMITED:setTimeout(function(){performOp(interceptCb)},timeoutDuration*1e3);break;default:cb.apply(null,arguments);break}}else{cb.apply(null,arguments)}};performOp(interceptCb)};CachedDropboxClient.prototype.getCachedInfo=function getCachedInfo(p){return this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.putCachedInfo=function putCachedInfo(p,cache){this._cache[p.toLowerCase()]=cache};CachedDropboxClient.prototype.deleteCachedInfo=function deleteCachedInfo(p){delete this._cache[p.toLowerCase()]};CachedDropboxClient.prototype.getCachedDirInfo=function getCachedDirInfo(p){var info=this.getCachedInfo(p);if(isDirInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.getCachedFileInfo=function getCachedFileInfo(p){var info=this.getCachedInfo(p);if(isFileInfo(info)){return info}else{return null}};CachedDropboxClient.prototype.updateCachedDirInfo=function updateCachedDirInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.contentHash!==null&&(cachedInfo===void 0||cachedInfo.stat.contentHash!==stat.contentHash)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedFileInfo=function updateCachedFileInfo(p,stat,contents){if(contents===void 0)contents=null;var cachedInfo=this.getCachedInfo(p);if(stat.versionTag!==null&&(cachedInfo===void 0||cachedInfo.stat.versionTag!==stat.versionTag)){this.putCachedInfo(p,{stat,contents})}};CachedDropboxClient.prototype.updateCachedInfo=function updateCachedInfo(p,stat,contents){if(contents===void 0)contents=null;if(stat.isFile&&isArrayBuffer(contents)){this.updateCachedFileInfo(p,stat,contents)}else if(stat.isFolder&&Array.isArray(contents)){this.updateCachedDirInfo(p,stat,contents)}};var DropboxFile=function(PreloadFile$$1){function DropboxFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)DropboxFile2.__proto__=PreloadFile$$1;DropboxFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);DropboxFile2.prototype.constructor=DropboxFile2;DropboxFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){var buffer$$1=this.getBuffer(),arrayBuffer=buffer2ArrayBuffer(buffer$$1);this._fs._writeFileStrict(this.getPath(),arrayBuffer,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};DropboxFile2.prototype.close=function close(cb){this.sync(cb)};return DropboxFile2}(PreloadFile);var DropboxFileSystem=function(BaseFileSystem$$1){function DropboxFileSystem2(client,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._client=new CachedDropboxClient(client);deprecationMessage(deprecateMsg,DropboxFileSystem2.Name,{client:"authenticated dropbox client instance"});constructErrorCodeLookup()}if(BaseFileSystem$$1)DropboxFileSystem2.__proto__=BaseFileSystem$$1;DropboxFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);DropboxFileSystem2.prototype.constructor=DropboxFileSystem2;DropboxFileSystem2.Create=function Create(opts,cb){cb(null,new DropboxFileSystem2(opts.client,false))};DropboxFileSystem2.isAvailable=function isAvailable(){return typeof Dropbox!=="undefined"};DropboxFileSystem2.prototype.getName=function getName(){return DropboxFileSystem2.Name};DropboxFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};DropboxFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};DropboxFileSystem2.prototype.supportsProps=function supportsProps(){return false};DropboxFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};DropboxFileSystem2.prototype.empty=function empty(mainCb){var this$1=this;this._client.readdir("/",function(error,files){if(error){mainCb(this$1.convert(error,"/"))}else{var deleteFile2=function(file,cb){var p=path.join("/",file);this$1._client.remove(p,function(err){cb(err?this$1.convert(err,p):null)})};var finished=function(err){if(err){mainCb(err)}else{mainCb()}};eachLimit(files,deleteFile2,finished)}})};DropboxFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._client.move(oldPath,newPath,function(error){if(error){this$1._client.stat(newPath,function(error2,stat){if(error2||stat.isFolder){var missingPath=error.response.error.indexOf(oldPath)>-1?oldPath:newPath;cb(this$1.convert(error,missingPath))}else{this$1._client.remove(newPath,function(error22){if(error22){cb(this$1.convert(error22,newPath))}else{this$1.rename(oldPath,newPath,cb)}})}})}else{cb()}})};DropboxFileSystem2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;this._client.stat(path$$1,function(error,stat2){if(error){cb(this$1.convert(error,path$$1))}else if(stat2&&stat2.isRemoved){cb(ApiError.FileError(ErrorCode.ENOENT,path$$1))}else{var stats=new Stats(this$1._statType(stat2),stat2.size);return cb(null,stats)}})};DropboxFileSystem2.prototype.open=function open(path$$1,flags,mode,cb){var this$1=this;this._client.readFile(path$$1,function(error,content,dbStat){if(error){if(flags.isReadable()){cb(this$1.convert(error,path$$1))}else{switch(error.status){case Dropbox.ApiError.NOT_FOUND:var ab=new ArrayBuffer(0);return this$1._writeFileStrict(path$$1,ab,function(error2,stat){if(error2){cb(error2)}else{var file2=this$1._makeFile(path$$1,flags,stat,arrayBuffer2Buffer(ab));cb(null,file2)}});default:return cb(this$1.convert(error,path$$1))}}}else{var buffer$$1;if(content===null){buffer$$1=emptyBuffer()}else{buffer$$1=arrayBuffer2Buffer(content)}var file=this$1._makeFile(path$$1,flags,dbStat,buffer$$1);return cb(null,file)}})};DropboxFileSystem2.prototype._writeFileStrict=function _writeFileStrict(p,data,cb){var this$1=this;var parent=path.dirname(p);this.stat(parent,false,function(error,stat){if(error){cb(ApiError.FileError(ErrorCode.ENOENT,parent))}else{this$1._client.writeFile(p,data,function(error2,stat2){if(error2){cb(this$1.convert(error2,p))}else{cb(null,stat2)}})}})};DropboxFileSystem2.prototype._statType=function _statType(stat){return stat.isFile?FileType.FILE:FileType.DIRECTORY};DropboxFileSystem2.prototype._makeFile=function _makeFile(path$$1,flag,stat,buffer$$1){var type=this._statType(stat);var stats=new Stats(type,stat.size);return new DropboxFile(this,path$$1,flag,stats,buffer$$1)};DropboxFileSystem2.prototype._remove=function _remove(path$$1,cb,isFile){var this$1=this;this._client.stat(path$$1,function(error,stat){if(error){cb(this$1.convert(error,path$$1))}else{if(stat.isFile&&!isFile){cb(ApiError.FileError(ErrorCode.ENOTDIR,path$$1))}else if(!stat.isFile&&isFile){cb(ApiError.FileError(ErrorCode.EISDIR,path$$1))}else{this$1._client.remove(path$$1,function(error2){if(error2){cb(this$1.convert(error2,path$$1))}else{cb(null)}})}}})};DropboxFileSystem2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};DropboxFileSystem2.prototype.rmdir=function rmdir(path$$1,cb){this._remove(path$$1,cb,false)};DropboxFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;var parent=path.dirname(p);this._client.stat(parent,function(error,stat){if(error){cb(this$1.convert(error,parent))}else{this$1._client.mkdir(p,function(error2){if(error2){cb(ApiError.FileError(ErrorCode.EEXIST,p))}else{cb(null)}})}})};DropboxFileSystem2.prototype.readdir=function readdir(path$$1,cb){var this$1=this;this._client.readdir(path$$1,function(error,files){if(error){return cb(this$1.convert(error))}else{return cb(null,files)}})};DropboxFileSystem2.prototype.convert=function convert(err,path$$1){if(path$$1===void 0)path$$1=null;var errorCode=errorCodeLookup[err.status];if(errorCode===void 0){errorCode=ErrorCode.EIO}if(!path$$1){return new ApiError(errorCode)}else{return ApiError.FileError(errorCode,path$$1)}};return DropboxFileSystem2}(BaseFileSystem);DropboxFileSystem.Name="Dropbox";DropboxFileSystem.Options={client:{type:"object",description:"An *authenticated* Dropbox client. Must be from the 0.10 JS SDK.",validator:function(opt,cb){if(opt.isAuthenticated&&opt.isAuthenticated()){cb()}else{cb(new ApiError(ErrorCode.EINVAL,"'client' option must be an authenticated Dropbox client from the v0.10 JS SDK."))}}}};function convertError(e,path$$1){if(path$$1===void 0)path$$1="";var errno=e.errno;var parent=e.node;var paths=[];while(parent){paths.unshift(parent.name);if(parent===parent.parent){break}parent=parent.parent}return new ApiError(errno,ErrorStrings[errno],paths.length>0?"/"+paths.join("/"):path$$1)}var EmscriptenFile=function(BaseFile$$1){function EmscriptenFile2(_fs,_FS,_path,_stream){BaseFile$$1.call(this);this._fs=_fs;this._FS=_FS;this._path=_path;this._stream=_stream}if(BaseFile$$1)EmscriptenFile2.__proto__=BaseFile$$1;EmscriptenFile2.prototype=Object.create(BaseFile$$1&&BaseFile$$1.prototype);EmscriptenFile2.prototype.constructor=EmscriptenFile2;EmscriptenFile2.prototype.getPos=function getPos(){return void 0};EmscriptenFile2.prototype.close=function close(cb){var err=null;try{this.closeSync()}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.closeSync=function closeSync(){try{this._FS.close(this._stream)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.stat=function stat(cb){try{cb(null,this.statSync())}catch(e){cb(e)}};EmscriptenFile2.prototype.statSync=function statSync(){try{return this._fs.statSync(this._path,false)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.truncate=function truncate(len,cb){var err=null;try{this.truncateSync(len)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.truncateSync=function truncateSync(len){try{this._FS.ftruncate(this._stream.fd,len)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.write=function write(buffer$$1,offset,length,position,cb){try{cb(null,this.writeSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.writeSync=function writeSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.write(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.read=function read(buffer$$1,offset,length,position,cb){try{cb(null,this.readSync(buffer$$1,offset,length,position),buffer$$1)}catch(e){cb(e)}};EmscriptenFile2.prototype.readSync=function readSync(buffer$$1,offset,length,position){try{var u8=buffer2Uint8array(buffer$$1);var emPosition=position===null?void 0:position;return this._FS.read(this._stream,u8,offset,length,emPosition)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.sync=function sync(cb){cb()};EmscriptenFile2.prototype.syncSync=function syncSync(){};EmscriptenFile2.prototype.chown=function chown(uid,gid,cb){var err=null;try{this.chownSync(uid,gid)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chownSync=function chownSync(uid,gid){try{this._FS.fchown(this._stream.fd,uid,gid)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.chmod=function chmod(mode,cb){var err=null;try{this.chmodSync(mode)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.chmodSync=function chmodSync(mode){try{this._FS.fchmod(this._stream.fd,mode)}catch(e){throw convertError(e,this._path)}};EmscriptenFile2.prototype.utimes=function utimes(atime,mtime,cb){var err=null;try{this.utimesSync(atime,mtime)}catch(e){err=e}finally{cb(err)}};EmscriptenFile2.prototype.utimesSync=function utimesSync(atime,mtime){this._fs.utimesSync(this._path,atime,mtime)};return EmscriptenFile2}(BaseFile);var EmscriptenFileSystem=function(SynchronousFileSystem$$1){function EmscriptenFileSystem2(_FS){SynchronousFileSystem$$1.call(this);this._FS=_FS}if(SynchronousFileSystem$$1)EmscriptenFileSystem2.__proto__=SynchronousFileSystem$$1;EmscriptenFileSystem2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);EmscriptenFileSystem2.prototype.constructor=EmscriptenFileSystem2;EmscriptenFileSystem2.Create=function Create(opts,cb){cb(null,new EmscriptenFileSystem2(opts.FS))};EmscriptenFileSystem2.isAvailable=function isAvailable(){return true};EmscriptenFileSystem2.prototype.getName=function getName(){return this._FS.DB_NAME()};EmscriptenFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};EmscriptenFileSystem2.prototype.supportsLinks=function supportsLinks(){return true};EmscriptenFileSystem2.prototype.supportsProps=function supportsProps(){return true};EmscriptenFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};EmscriptenFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){try{this._FS.rename(oldPath,newPath)}catch(e){if(e.errno===ErrorCode.ENOENT){throw convertError(e,this.existsSync(oldPath)?newPath:oldPath)}else{throw convertError(e)}}};EmscriptenFileSystem2.prototype.statSync=function statSync(p,isLstat){try{var stats=isLstat?this._FS.lstat(p):this._FS.stat(p);var itemType=this.modeToFileType(stats.mode);return new Stats(itemType,stats.size,stats.mode,stats.atime,stats.mtime,stats.ctime)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.openSync=function openSync(p,flag,mode){try{var stream=this._FS.open(p,flag.getFlagString(),mode);if(this._FS.isDir(stream.node.mode)){this._FS.close(stream);throw ApiError.EISDIR(p)}return new EmscriptenFile(this,this._FS,p,stream)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.unlinkSync=function unlinkSync(p){try{this._FS.unlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.rmdirSync=function rmdirSync(p){try{this._FS.rmdir(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){try{this._FS.mkdir(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readdirSync=function readdirSync(p){try{return this._FS.readdir(p).filter(function(p2){return p2!=="."&&p2!==".."})}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.truncateSync=function truncateSync(p,len){try{this._FS.truncate(p,len)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.readFileSync=function readFileSync(p,encoding,flag){try{var data=this._FS.readFile(p,{flags:flag.getFlagString()});var buff=uint8Array2Buffer(data);if(encoding){return buff.toString(encoding)}else{return buff}}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.writeFileSync=function writeFileSync(p,data,encoding,flag,mode){try{if(encoding){data=Buffer2.from(data,encoding)}var u8=buffer2Uint8array(data);this._FS.writeFile(p,u8,{flags:flag.getFlagString(),encoding:"binary"});this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){try{isLchmod?this._FS.lchmod(p,mode):this._FS.chmod(p,mode)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){try{isLchown?this._FS.lchown(p,uid,gid):this._FS.chown(p,uid,gid)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){try{this._FS.symlink(srcpath,dstpath)}catch(e){throw convertError(e)}};EmscriptenFileSystem2.prototype.readlinkSync=function readlinkSync(p){try{return this._FS.readlink(p)}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.utimesSync=function utimesSync(p,atime,mtime){try{this._FS.utime(p,atime.getTime(),mtime.getTime())}catch(e){throw convertError(e,p)}};EmscriptenFileSystem2.prototype.modeToFileType=function modeToFileType(mode){if(this._FS.isDir(mode)){return FileType.DIRECTORY}else if(this._FS.isFile(mode)){return FileType.FILE}else if(this._FS.isLink(mode)){return FileType.SYMLINK}else{throw ApiError.EPERM("Invalid mode: "+mode)}};return EmscriptenFileSystem2}(SynchronousFileSystem);EmscriptenFileSystem.Name="EmscriptenFileSystem";EmscriptenFileSystem.Options={FS:{type:"object",description:"The Emscripten file system to use (the `FS` variable)"}};var FolderAdapter=function(BaseFileSystem$$1){function FolderAdapter2(folder,wrapped){BaseFileSystem$$1.call(this);this._folder=folder;this._wrapped=wrapped}if(BaseFileSystem$$1)FolderAdapter2.__proto__=BaseFileSystem$$1;FolderAdapter2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);FolderAdapter2.prototype.constructor=FolderAdapter2;FolderAdapter2.Create=function Create(opts,cb){cb(null,new FolderAdapter2(opts.folder,opts.wrapped))};FolderAdapter2.isAvailable=function isAvailable(){return true};FolderAdapter2.prototype.initialize=function initialize3(cb){var this$1=this;this._wrapped.exists(this._folder,function(exists2){if(exists2){cb()}else if(this$1._wrapped.isReadOnly()){cb(ApiError.ENOENT(this$1._folder))}else{this$1._wrapped.mkdir(this$1._folder,511,cb)}})};FolderAdapter2.prototype.getName=function getName(){return this._wrapped.getName()};FolderAdapter2.prototype.isReadOnly=function isReadOnly(){return this._wrapped.isReadOnly()};FolderAdapter2.prototype.supportsProps=function supportsProps(){return this._wrapped.supportsProps()};FolderAdapter2.prototype.supportsSynch=function supportsSynch(){return this._wrapped.supportsSynch()};FolderAdapter2.prototype.supportsLinks=function supportsLinks(){return false};return FolderAdapter2}(BaseFileSystem);FolderAdapter.Name="FolderAdapter";FolderAdapter.Options={folder:{type:"string",description:"The folder to use as the root directory"},wrapped:{type:"object",description:"The file system to wrap"}};function translateError(folder,e){if(e!==null&&typeof e==="object"){var err=e;var p=err.path;if(p){p="/"+path.relative(folder,p);err.message=err.message.replace(err.path,p);err.path=p}}return e}function wrapCallback(folder,cb){if(typeof cb==="function"){return function(err){if(arguments.length>0){arguments[0]=translateError(folder,err)}cb.apply(null,arguments)}}else{return cb}}function wrapFunction(name,wrapFirst,wrapSecond){if(name.slice(name.length-4)!=="Sync"){return function(){if(arguments.length>0){if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}arguments[arguments.length-1]=wrapCallback(this._folder,arguments[arguments.length-1])}return this._wrapped[name].apply(this._wrapped,arguments)}}else{return function(){try{if(wrapFirst){arguments[0]=path.join(this._folder,arguments[0])}if(wrapSecond){arguments[1]=path.join(this._folder,arguments[1])}return this._wrapped[name].apply(this._wrapped,arguments)}catch(e){throw translateError(this._folder,e)}}}}["diskSpace","stat","statSync","open","openSync","unlink","unlinkSync","rmdir","rmdirSync","mkdir","mkdirSync","readdir","readdirSync","exists","existsSync","realpath","realpathSync","truncate","truncateSync","readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","chmod","chmodSync","chown","chownSync","utimes","utimesSync","readlink","readlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,false)});["rename","renameSync","link","linkSync","symlink","symlinkSync"].forEach(function(name){FolderAdapter.prototype[name]=wrapFunction(name,true,true)});var toExport;if(typeof window!=="undefined"){toExport=window}else if(typeof self!=="undefined"){toExport=self}else{toExport=global}var global$1=toExport;function isDirectoryEntry(entry){return entry.isDirectory}var _getFS=global$1.webkitRequestFileSystem||global$1.requestFileSystem||null;function _requestQuota(type,size,success,errorCallback){if(typeof navigator["webkitPersistentStorage"]!=="undefined"){switch(type){case global$1.PERSISTENT:navigator.webkitPersistentStorage.requestQuota(size,success,errorCallback);break;case global$1.TEMPORARY:navigator.webkitTemporaryStorage.requestQuota(size,success,errorCallback);break;default:errorCallback(new TypeError("Invalid storage type: "+type));break}}else{global$1.webkitStorageInfo.requestQuota(type,size,success,errorCallback)}}function _toArray(list2){return Array.prototype.slice.call(list2||[],0)}function convertError$1(err,p,expectedDir){switch(err.name){case"PathExistsError":return ApiError.EEXIST(p);case"QuotaExceededError":return ApiError.FileError(ErrorCode.ENOSPC,p);case"NotFoundError":return ApiError.ENOENT(p);case"SecurityError":return ApiError.FileError(ErrorCode.EACCES,p);case"InvalidModificationError":return ApiError.FileError(ErrorCode.EPERM,p);case"TypeMismatchError":return ApiError.FileError(expectedDir?ErrorCode.ENOTDIR:ErrorCode.EISDIR,p);case"EncodingError":case"InvalidStateError":case"NoModificationAllowedError":default:return ApiError.FileError(ErrorCode.EINVAL,p)}}var HTML5FSFile=function(PreloadFile$$1){function HTML5FSFile2(fs4,entry,path$$1,flag,stat,contents){PreloadFile$$1.call(this,fs4,path$$1,flag,stat,contents);this._entry=entry}if(PreloadFile$$1)HTML5FSFile2.__proto__=PreloadFile$$1;HTML5FSFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);HTML5FSFile2.prototype.constructor=HTML5FSFile2;HTML5FSFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){return cb()}this._entry.createWriter(function(writer){var buffer$$1=this$1.getBuffer();var blob=new Blob([buffer2ArrayBuffer(buffer$$1)]);var length=blob.size;writer.onwriteend=function(err){writer.onwriteend=null;writer.onerror=null;writer.truncate(length);this$1.resetDirty();cb()};writer.onerror=function(err){cb(convertError$1(err,this$1.getPath(),false))};writer.write(blob)})};HTML5FSFile2.prototype.close=function close(cb){this.sync(cb)};return HTML5FSFile2}(PreloadFile);var HTML5FS=function(BaseFileSystem$$1){function HTML5FS2(size,type,deprecateMsg){if(size===void 0)size=5;if(type===void 0)type=global$1.PERSISTENT;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this.size=1024*1024*size;this.type=type;deprecationMessage(deprecateMsg,HTML5FS2.Name,{size,type})}if(BaseFileSystem$$1)HTML5FS2.__proto__=BaseFileSystem$$1;HTML5FS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);HTML5FS2.prototype.constructor=HTML5FS2;HTML5FS2.Create=function Create(opts,cb){var fs4=new HTML5FS2(opts.size,opts.type,false);fs4.allocate(function(e){return e?cb(e):cb(null,fs4)},false)};HTML5FS2.isAvailable=function isAvailable(){return!!_getFS};HTML5FS2.prototype.getName=function getName(){return HTML5FS2.Name};HTML5FS2.prototype.isReadOnly=function isReadOnly(){return false};HTML5FS2.prototype.supportsSymlinks=function supportsSymlinks(){return false};HTML5FS2.prototype.supportsProps=function supportsProps(){return false};HTML5FS2.prototype.supportsSynch=function supportsSynch(){return false};HTML5FS2.prototype.allocate=function allocate(cb,deprecateMsg){var this$1=this;if(cb===void 0)cb=function(){};if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[HTML5FS] HTML5FS.allocate() is deprecated and will be removed in the next major release. Please use 'HTML5FS.Create({type: "+this.type+", size: "+this.size+"}, cb)' to create and allocate HTML5FS instances.")}var success=function(fs4){this$1.fs=fs4;cb()};var error=function(err){cb(convertError$1(err,"/",true))};if(this.type===global$1.PERSISTENT){_requestQuota(this.type,this.size,function(granted){_getFS(this$1.type,granted,success,error)},error)}else{_getFS(this.type,this.size,success,error)}};HTML5FS2.prototype.empty=function empty(mainCb){this._readdir("/",function(err,entries){if(err){console.error("Failed to empty FS");mainCb(err)}else{var finished=function(er){if(err){console.error("Failed to empty FS");mainCb(err)}else{mainCb()}};var deleteEntry=function(entry,cb){var succ=function(){cb()};var error=function(err2){cb(convertError$1(err2,entry.fullPath,!entry.isDirectory))};if(isDirectoryEntry(entry)){entry.removeRecursively(succ,error)}else{entry.remove(succ,error)}};eachLimit(entries,deleteEntry,finished)}})};HTML5FS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var semaphore=2;var successCount=0;var root2=this.fs.root;var currentPath=oldPath;var error=function(err){if(--semaphore<=0){cb(convertError$1(err,currentPath,false))}};var success=function(file){if(++successCount===2){return cb(new ApiError(ErrorCode.EINVAL,"Something was identified as both a file and a directory. This should never happen."))}if(oldPath===newPath){return cb()}currentPath=path.dirname(newPath);root2.getDirectory(currentPath,{},function(parentDir){currentPath=path.basename(newPath);file.moveTo(parentDir,currentPath,function(entry){cb()},function(err){if(file.isDirectory){currentPath=newPath;this$1.unlink(newPath,function(e){if(e){error(err)}else{this$1.rename(oldPath,newPath,cb)}})}else{error(err)}})},error)};root2.getFile(oldPath,{},success,error);root2.getDirectory(oldPath,{},success,error)};HTML5FS2.prototype.stat=function stat(path$$1,isLstat,cb){var this$1=this;var opts={create:false};var loadAsFile=function(entry){var fileFromEntry=function(file){var stat2=new Stats(FileType.FILE,file.size);cb(null,stat2)};entry.file(fileFromEntry,failedToLoad)};var loadAsDir=function(dir$$1){var size=4096;var stat2=new Stats(FileType.DIRECTORY,size);cb(null,stat2)};var failedToLoad=function(err){cb(convertError$1(err,path$$1,false))};var failedToLoadAsFile=function(){this$1.fs.root.getDirectory(path$$1,opts,loadAsDir,failedToLoad)};this.fs.root.getFile(path$$1,opts,loadAsFile,failedToLoadAsFile)};HTML5FS2.prototype.open=function open(p,flags,mode,cb){var this$1=this;var error=function(err){if(err.name==="InvalidModificationError"&&flags.isExclusive()){cb(ApiError.EEXIST(p))}else{cb(convertError$1(err,p,false))}};this.fs.root.getFile(p,{create:flags.pathNotExistsAction()===ActionType.CREATE_FILE,exclusive:flags.isExclusive()},function(entry){entry.file(function(file){var reader=new FileReader;reader.onloadend=function(event){var bfsFile=this$1._makeFile(p,entry,flags,file,reader.result);cb(null,bfsFile)};reader.onerror=function(ev){error(reader.error)};reader.readAsArrayBuffer(file)},error)},error)};HTML5FS2.prototype.unlink=function unlink(path$$1,cb){this._remove(path$$1,cb,true)};HTML5FS2.prototype.rmdir=function rmdir(path$$1,cb){var this$1=this;this.readdir(path$$1,function(e,files){if(e){cb(e)}else if(files.length>0){cb(ApiError.ENOTEMPTY(path$$1))}else{this$1._remove(path$$1,cb,false)}})};HTML5FS2.prototype.mkdir=function mkdir(path$$1,mode,cb){var opts={create:true,exclusive:true};var success=function(dir$$1){cb()};var error=function(err){cb(convertError$1(err,path$$1,true))};this.fs.root.getDirectory(path$$1,opts,success,error)};HTML5FS2.prototype.readdir=function readdir(path$$1,cb){this._readdir(path$$1,function(e,entries){if(entries){var rv=[];for(var i2=0,list2=entries;i20){throw ApiError.ENOTEMPTY(p)}else{this.removeEntry(p,true)}};SyncKeyValueFileSystem2.prototype.mkdirSync=function mkdirSync(p,mode){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data)};SyncKeyValueFileSystem2.prototype.readdirSync=function readdirSync(p){var tx=this.store.beginTransaction("readonly");return Object.keys(this.getDirListing(tx,p,this.findINode(tx,p)))};SyncKeyValueFileSystem2.prototype._syncSync=function _syncSync(p,data,stats){var tx=this.store.beginTransaction("readwrite"),fileInodeId=this._findINode(tx,path.dirname(p),path.basename(p)),fileInode=this.getINode(tx,p,fileInodeId),inodeChanged=fileInode.update(stats);try{tx.put(fileInode.id,data,true);if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true)}}catch(e){tx.abort();throw e}tx.commit()};SyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(){var tx=this.store.beginTransaction("readwrite");if(tx.get(ROOT_NODE_ID)===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false);tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false);tx.commit()}};SyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename){var this$1=this;var readDirectory=function(inode){var dirList=this$1.getDirListing(tx,parent,inode);if(dirList[filename]){return dirList[filename]}else{throw ApiError.ENOENT(path.resolve(parent,filename))}};if(parent==="/"){if(filename===""){return ROOT_NODE_ID}else{return readDirectory(this.getINode(tx,parent,ROOT_NODE_ID))}}else{return readDirectory(this.getINode(tx,parent+path.sep+filename,this._findINode(tx,path.dirname(parent),path.basename(parent))))}};SyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p){return this.getINode(tx,p,this._findINode(tx,path.dirname(p),path.basename(p)))};SyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id){var inode=tx.get(id);if(inode===void 0){throw ApiError.ENOENT(p)}return Inode.fromBuffer(inode)};SyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode){if(!inode.isDirectory()){throw ApiError.ENOTDIR(p)}var data=tx.get(inode.id);if(data===void 0){throw ApiError.ENOENT(p)}return JSON.parse(data.toString())};SyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data){var retries=0;var currId;while(retries<5){try{currId=GenerateRandomID();tx.put(currId,data,false);return currId}catch(e){}}throw new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store.")};SyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data){var parentDir=path.dirname(p),fname=path.basename(p),parentNode=this.findINode(tx,parentDir),dirListing=this.getDirListing(tx,parentDir,parentNode),currTime=new Date().getTime();if(p==="/"){throw ApiError.EEXIST(p)}if(dirListing[fname]){throw ApiError.EEXIST(p)}var fileNode;try{var dataId=this.addNewNode(tx,data);fileNode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);var fileNodeId=this.addNewNode(tx,fileNode.toBuffer());dirListing[fname]=fileNodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true)}catch(e){tx.abort();throw e}tx.commit();return fileNode};SyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir){var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),parentNode=this.findINode(tx,parent),parentListing=this.getDirListing(tx,parent,parentNode),fileName=path.basename(p);if(!parentListing[fileName]){throw ApiError.ENOENT(p)}var fileNodeId=parentListing[fileName];delete parentListing[fileName];var fileNode=this.getINode(tx,p,fileNodeId);if(!isDir&&fileNode.isDirectory()){throw ApiError.EISDIR(p)}else if(isDir&&!fileNode.isDirectory()){throw ApiError.ENOTDIR(p)}try{tx.del(fileNode.id);tx.del(fileNodeId);tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true)}catch(e){tx.abort();throw e}tx.commit()};return SyncKeyValueFileSystem2}(SynchronousFileSystem);var AsyncKeyValueFile=function(PreloadFile$$1){function AsyncKeyValueFile2(_fs,_path,_flag,_stat,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents)}if(PreloadFile$$1)AsyncKeyValueFile2.__proto__=PreloadFile$$1;AsyncKeyValueFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);AsyncKeyValueFile2.prototype.constructor=AsyncKeyValueFile2;AsyncKeyValueFile2.prototype.sync=function sync(cb){var this$1=this;if(this.isDirty()){this._fs._sync(this.getPath(),this.getBuffer(),this.getStats(),function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};AsyncKeyValueFile2.prototype.close=function close(cb){this.sync(cb)};return AsyncKeyValueFile2}(PreloadFile);var AsyncKeyValueFileSystem=function(BaseFileSystem$$1){function AsyncKeyValueFileSystem2(){BaseFileSystem$$1.apply(this,arguments)}if(BaseFileSystem$$1)AsyncKeyValueFileSystem2.__proto__=BaseFileSystem$$1;AsyncKeyValueFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);AsyncKeyValueFileSystem2.prototype.constructor=AsyncKeyValueFileSystem2;AsyncKeyValueFileSystem2.isAvailable=function isAvailable(){return true};AsyncKeyValueFileSystem2.prototype.init=function init(store,cb){this.store=store;this.makeRootDirectory(cb)};AsyncKeyValueFileSystem2.prototype.getName=function getName(){return this.store.name()};AsyncKeyValueFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};AsyncKeyValueFileSystem2.prototype.supportsSymlinks=function supportsSymlinks(){return false};AsyncKeyValueFileSystem2.prototype.supportsProps=function supportsProps(){return false};AsyncKeyValueFileSystem2.prototype.supportsSynch=function supportsSynch(){return false};AsyncKeyValueFileSystem2.prototype.empty=function empty(cb){var this$1=this;this.store.clear(function(e){if(noError(e,cb)){this$1.makeRootDirectory(cb)}})};AsyncKeyValueFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");var oldParent=path.dirname(oldPath),oldName=path.basename(oldPath);var newParent=path.dirname(newPath),newName=path.basename(newPath);var inodes={};var lists={};var errorOccurred=false;if((newParent+"/").indexOf(oldPath+"/")===0){return cb(new ApiError(ErrorCode.EBUSY,oldParent))}var theOleSwitcharoo=function(){if(errorOccurred||!lists.hasOwnProperty(oldParent)||!lists.hasOwnProperty(newParent)){return}var oldParentList=lists[oldParent],oldParentINode=inodes[oldParent],newParentList=lists[newParent],newParentINode=inodes[newParent];if(!oldParentList[oldName]){cb(ApiError.ENOENT(oldPath))}else{var fileId=oldParentList[oldName];delete oldParentList[oldName];var completeRename=function(){newParentList[newName]=fileId;tx.put(oldParentINode.id,Buffer2.from(JSON.stringify(oldParentList)),true,function(e){if(noErrorTx(e,tx,cb)){if(oldParent===newParent){tx.commit(cb)}else{tx.put(newParentINode.id,Buffer2.from(JSON.stringify(newParentList)),true,function(e2){if(noErrorTx(e2,tx,cb)){tx.commit(cb)}})}}})};if(newParentList[newName]){this$1.getINode(tx,newPath,newParentList[newName],function(e,inode){if(noErrorTx(e,tx,cb)){if(inode.isFile()){tx.del(inode.id,function(e2){if(noErrorTx(e2,tx,cb)){tx.del(newParentList[newName],function(e3){if(noErrorTx(e3,tx,cb)){completeRename()}})}})}else{tx.abort(function(e2){cb(ApiError.EPERM(newPath))})}}})}else{completeRename()}}};var processInodeAndListings=function(p){this$1.findINodeAndDirListing(tx,p,function(e,node,dirList){if(e){if(!errorOccurred){errorOccurred=true;tx.abort(function(){cb(e)})}}else{inodes[p]=node;lists[p]=dirList;theOleSwitcharoo()}})};processInodeAndListings(oldParent);if(oldParent!==newParent){processInodeAndListings(newParent)}};AsyncKeyValueFileSystem2.prototype.stat=function stat(p,isLstat,cb){var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){cb(null,inode.toStats())}})};AsyncKeyValueFileSystem2.prototype.createFile=function createFile(p,flag,mode,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),data=emptyBuffer();this.commitNewFile(tx,p,FileType.FILE,mode,data,function(e,newFile){if(noError(e,cb)){cb(null,new AsyncKeyValueFile(this$1,p,flag,newFile.toStats(),data))}})};AsyncKeyValueFileSystem2.prototype.openFile=function openFile(p,flag,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){tx.get(inode.id,function(e2,data){if(noError(e2,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,new AsyncKeyValueFile(this$1,p,flag,inode.toStats(),data))}}})}})};AsyncKeyValueFileSystem2.prototype.unlink=function unlink(p,cb){this.removeEntry(p,false,cb)};AsyncKeyValueFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;this.readdir(p,function(err,files){if(err){cb(err)}else if(files.length>0){cb(ApiError.ENOTEMPTY(p))}else{this$1.removeEntry(p,true,cb)}})};AsyncKeyValueFileSystem2.prototype.mkdir=function mkdir(p,mode,cb){var tx=this.store.beginTransaction("readwrite"),data=Buffer2.from("{}");this.commitNewFile(tx,p,FileType.DIRECTORY,mode,data,cb)};AsyncKeyValueFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var tx=this.store.beginTransaction("readonly");this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,dirListing){if(noError(e2,cb)){cb(null,Object.keys(dirListing))}})}})};AsyncKeyValueFileSystem2.prototype._sync=function _sync(p,data,stats,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite");this._findINode(tx,path.dirname(p),path.basename(p),function(e,fileInodeId){if(noErrorTx(e,tx,cb)){this$1.getINode(tx,p,fileInodeId,function(e2,fileInode){if(noErrorTx(e2,tx,cb)){var inodeChanged=fileInode.update(stats);tx.put(fileInode.id,data,true,function(e3){if(noErrorTx(e3,tx,cb)){if(inodeChanged){tx.put(fileInodeId,fileInode.toBuffer(),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(cb)}})}else{tx.commit(cb)}}})}})}})};AsyncKeyValueFileSystem2.prototype.makeRootDirectory=function makeRootDirectory(cb){var tx=this.store.beginTransaction("readwrite");tx.get(ROOT_NODE_ID,function(e,data){if(e||data===void 0){var currTime=new Date().getTime(),dirInode=new Inode(GenerateRandomID(),4096,511|FileType.DIRECTORY,currTime,currTime,currTime);tx.put(dirInode.id,getEmptyDirNode(),false,function(e2){if(noErrorTx(e2,tx,cb)){tx.put(ROOT_NODE_ID,dirInode.toBuffer(),false,function(e3){if(e3){tx.abort(function(){cb(e3)})}else{tx.commit(cb)}})}})}else{tx.commit(cb)}})};AsyncKeyValueFileSystem2.prototype._findINode=function _findINode(tx,parent,filename,cb){var this$1=this;var handleDirectoryListings=function(e,inode,dirList){if(e){cb(e)}else if(dirList[filename]){cb(null,dirList[filename])}else{cb(ApiError.ENOENT(path.resolve(parent,filename)))}};if(parent==="/"){if(filename===""){cb(null,ROOT_NODE_ID)}else{this.getINode(tx,parent,ROOT_NODE_ID,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,parent,inode,function(e2,dirList){handleDirectoryListings(e2,inode,dirList)})}})}}else{this.findINodeAndDirListing(tx,parent,handleDirectoryListings)}};AsyncKeyValueFileSystem2.prototype.findINode=function findINode(tx,p,cb){var this$1=this;this._findINode(tx,path.dirname(p),path.basename(p),function(e,id){if(noError(e,cb)){this$1.getINode(tx,p,id,cb)}})};AsyncKeyValueFileSystem2.prototype.getINode=function getINode(tx,p,id,cb){tx.get(id,function(e,data){if(noError(e,cb)){if(data===void 0){cb(ApiError.ENOENT(p))}else{cb(null,Inode.fromBuffer(data))}}})};AsyncKeyValueFileSystem2.prototype.getDirListing=function getDirListing(tx,p,inode,cb){if(!inode.isDirectory()){cb(ApiError.ENOTDIR(p))}else{tx.get(inode.id,function(e,data){if(noError(e,cb)){try{cb(null,JSON.parse(data.toString()))}catch(e2){cb(ApiError.ENOENT(p))}}})}};AsyncKeyValueFileSystem2.prototype.findINodeAndDirListing=function findINodeAndDirListing(tx,p,cb){var this$1=this;this.findINode(tx,p,function(e,inode){if(noError(e,cb)){this$1.getDirListing(tx,p,inode,function(e2,listing){if(noError(e2,cb)){cb(null,inode,listing)}})}})};AsyncKeyValueFileSystem2.prototype.addNewNode=function addNewNode(tx,data,cb){var retries=0,currId;var reroll=function(){if(++retries===5){cb(new ApiError(ErrorCode.EIO,"Unable to commit data to key-value store."))}else{currId=GenerateRandomID();tx.put(currId,data,false,function(e,committed){if(e||!committed){reroll()}else{cb(null,currId)}})}};reroll()};AsyncKeyValueFileSystem2.prototype.commitNewFile=function commitNewFile(tx,p,type,mode,data,cb){var this$1=this;var parentDir=path.dirname(p),fname=path.basename(p),currTime=new Date().getTime();if(p==="/"){return cb(ApiError.EEXIST(p))}this.findINodeAndDirListing(tx,parentDir,function(e,parentNode,dirListing){if(noErrorTx(e,tx,cb)){if(dirListing[fname]){tx.abort(function(){cb(ApiError.EEXIST(p))})}else{this$1.addNewNode(tx,data,function(e2,dataId){if(noErrorTx(e2,tx,cb)){var fileInode=new Inode(dataId,data.length,mode|type,currTime,currTime,currTime);this$1.addNewNode(tx,fileInode.toBuffer(),function(e3,fileInodeId){if(noErrorTx(e3,tx,cb)){dirListing[fname]=fileInodeId;tx.put(parentNode.id,Buffer2.from(JSON.stringify(dirListing)),true,function(e4){if(noErrorTx(e4,tx,cb)){tx.commit(function(e5){if(noErrorTx(e5,tx,cb)){cb(null,fileInode)}})}})}})}})}}})};AsyncKeyValueFileSystem2.prototype.removeEntry=function removeEntry(p,isDir,cb){var this$1=this;var tx=this.store.beginTransaction("readwrite"),parent=path.dirname(p),fileName=path.basename(p);this.findINodeAndDirListing(tx,parent,function(e,parentNode,parentListing){if(noErrorTx(e,tx,cb)){if(!parentListing[fileName]){tx.abort(function(){cb(ApiError.ENOENT(p))})}else{var fileNodeId=parentListing[fileName];delete parentListing[fileName];this$1.getINode(tx,p,fileNodeId,function(e2,fileNode){if(noErrorTx(e2,tx,cb)){if(!isDir&&fileNode.isDirectory()){tx.abort(function(){cb(ApiError.EISDIR(p))})}else if(isDir&&!fileNode.isDirectory()){tx.abort(function(){cb(ApiError.ENOTDIR(p))})}else{tx.del(fileNode.id,function(e3){if(noErrorTx(e3,tx,cb)){tx.del(fileNodeId,function(e4){if(noErrorTx(e4,tx,cb)){tx.put(parentNode.id,Buffer2.from(JSON.stringify(parentListing)),true,function(e5){if(noErrorTx(e5,tx,cb)){tx.commit(cb)}})}})}})}}})}}})};return AsyncKeyValueFileSystem2}(BaseFileSystem);var InMemoryStore=function InMemoryStore2(){this.store={}};InMemoryStore.prototype.name=function name(){return InMemoryFileSystem.Name};InMemoryStore.prototype.clear=function clear(){this.store={}};InMemoryStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};InMemoryStore.prototype.get=function get(key){return this.store[key]};InMemoryStore.prototype.put=function put(key,data,overwrite){if(!overwrite&&this.store.hasOwnProperty(key)){return false}this.store[key]=data;return true};InMemoryStore.prototype.del=function del(key){delete this.store[key]};var InMemoryFileSystem=function(SyncKeyValueFileSystem$$1){function InMemoryFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new InMemoryStore})}if(SyncKeyValueFileSystem$$1)InMemoryFileSystem2.__proto__=SyncKeyValueFileSystem$$1;InMemoryFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);InMemoryFileSystem2.prototype.constructor=InMemoryFileSystem2;InMemoryFileSystem2.Create=function Create(options,cb){cb(null,new InMemoryFileSystem2)};return InMemoryFileSystem2}(SyncKeyValueFileSystem);InMemoryFileSystem.Name="InMemory";InMemoryFileSystem.Options={};var indexedDB=global$1.indexedDB||global$1.mozIndexedDB||global$1.webkitIndexedDB||global$1.msIndexedDB;function convertError$2(e,message){if(message===void 0)message=e.toString();switch(e.name){case"NotFoundError":return new ApiError(ErrorCode.ENOENT,message);case"QuotaExceededError":return new ApiError(ErrorCode.ENOSPC,message);default:return new ApiError(ErrorCode.EIO,message)}}function onErrorHandler(cb,code,message){if(code===void 0)code=ErrorCode.EIO;if(message===void 0)message=null;return function(e){e.preventDefault();cb(new ApiError(code,message!==null?message:void 0))}}var IndexedDBROTransaction=function IndexedDBROTransaction2(tx,store){this.tx=tx;this.store=store};IndexedDBROTransaction.prototype.get=function get(key,cb){try{var r=this.store.get(key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){var result=event.target.result;if(result===void 0){cb(null,result)}else{cb(null,arrayBuffer2Buffer(result))}}}catch(e){cb(convertError$2(e))}};var IndexedDBRWTransaction=function(IndexedDBROTransaction2){function IndexedDBRWTransaction2(tx,store){IndexedDBROTransaction2.call(this,tx,store)}if(IndexedDBROTransaction2)IndexedDBRWTransaction2.__proto__=IndexedDBROTransaction2;IndexedDBRWTransaction2.prototype=Object.create(IndexedDBROTransaction2&&IndexedDBROTransaction2.prototype);IndexedDBRWTransaction2.prototype.constructor=IndexedDBRWTransaction2;IndexedDBRWTransaction2.prototype.put=function put(key,data,overwrite,cb){try{var arraybuffer=buffer2ArrayBuffer(data);var r;if(overwrite){r=this.store.put(arraybuffer,key)}else{r=this.store.add(arraybuffer,key)}r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb(null,true)}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.del=function del(key,cb){try{var r=this.store["delete"](key);r.onerror=onErrorHandler(cb);r.onsuccess=function(event){cb()}}catch(e){cb(convertError$2(e))}};IndexedDBRWTransaction2.prototype.commit=function commit(cb){setTimeout(cb,0)};IndexedDBRWTransaction2.prototype.abort=function abort(cb){var _e=null;try{this.tx.abort()}catch(e){_e=convertError$2(e)}finally{cb(_e)}};return IndexedDBRWTransaction2}(IndexedDBROTransaction);var IndexedDBStore=function IndexedDBStore2(cb,storeName){var this$1=this;if(storeName===void 0)storeName="browserfs";this.storeName=storeName;var openReq=indexedDB.open(this.storeName,1);openReq.onupgradeneeded=function(event){var db=event.target.result;if(db.objectStoreNames.contains(this$1.storeName)){db.deleteObjectStore(this$1.storeName)}db.createObjectStore(this$1.storeName)};openReq.onsuccess=function(event){this$1.db=event.target.result;cb(null,this$1)};openReq.onerror=onErrorHandler(cb,ErrorCode.EACCES)};IndexedDBStore.prototype.name=function name(){return IndexedDBFileSystem.Name+" - "+this.storeName};IndexedDBStore.prototype.clear=function clear(cb){try{var tx=this.db.transaction(this.storeName,"readwrite"),objectStore=tx.objectStore(this.storeName),r=objectStore.clear();r.onsuccess=function(event){setTimeout(cb,0)};r.onerror=onErrorHandler(cb)}catch(e){cb(convertError$2(e))}};IndexedDBStore.prototype.beginTransaction=function beginTransaction(type){if(type===void 0)type="readonly";var tx=this.db.transaction(this.storeName,type),objectStore=tx.objectStore(this.storeName);if(type==="readwrite"){return new IndexedDBRWTransaction(tx,objectStore)}else if(type==="readonly"){return new IndexedDBROTransaction(tx,objectStore)}else{throw new ApiError(ErrorCode.EINVAL,"Invalid transaction type.")}};var IndexedDBFileSystem=function(AsyncKeyValueFileSystem$$1){function IndexedDBFileSystem2(cb,storeName,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;AsyncKeyValueFileSystem$$1.call(this);this.store=new IndexedDBStore(function(e){if(e){cb(e)}else{this$1.init(this$1.store,function(e2){cb(e2,this$1)})}},storeName);deprecationMessage(deprecateMsg,IndexedDBFileSystem2.Name,{storeName})}if(AsyncKeyValueFileSystem$$1)IndexedDBFileSystem2.__proto__=AsyncKeyValueFileSystem$$1;IndexedDBFileSystem2.prototype=Object.create(AsyncKeyValueFileSystem$$1&&AsyncKeyValueFileSystem$$1.prototype);IndexedDBFileSystem2.prototype.constructor=IndexedDBFileSystem2;IndexedDBFileSystem2.Create=function Create(opts,cb){new IndexedDBFileSystem2(cb,opts.storeName,false)};IndexedDBFileSystem2.isAvailable=function isAvailable(){try{return typeof indexedDB!=="undefined"&&null!==indexedDB.open("__browserfs_test__")}catch(e){return false}};return IndexedDBFileSystem2}(AsyncKeyValueFileSystem);IndexedDBFileSystem.Name="IndexedDB";IndexedDBFileSystem.Options={storeName:{type:"string",optional:true,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."}};var supportsBinaryString=false;var binaryEncoding;try{global$1.localStorage.setItem("__test__",String.fromCharCode(55296));supportsBinaryString=global$1.localStorage.getItem("__test__")===String.fromCharCode(55296)}catch(e){supportsBinaryString=false}binaryEncoding=supportsBinaryString?"binary_string":"binary_string_ie";if(!Buffer2.isEncoding(binaryEncoding)){binaryEncoding="base64"}var LocalStorageStore=function LocalStorageStore2(){};LocalStorageStore.prototype.name=function name(){return LocalStorageFileSystem.Name};LocalStorageStore.prototype.clear=function clear(){global$1.localStorage.clear()};LocalStorageStore.prototype.beginTransaction=function beginTransaction(type){return new SimpleSyncRWTransaction(this)};LocalStorageStore.prototype.get=function get(key){try{var data=global$1.localStorage.getItem(key);if(data!==null){return Buffer2.from(data,binaryEncoding)}}catch(e){}return void 0};LocalStorageStore.prototype.put=function put(key,data,overwrite){try{if(!overwrite&&global$1.localStorage.getItem(key)!==null){return false}global$1.localStorage.setItem(key,data.toString(binaryEncoding));return true}catch(e){throw new ApiError(ErrorCode.ENOSPC,"LocalStorage is full.")}};LocalStorageStore.prototype.del=function del(key){try{global$1.localStorage.removeItem(key)}catch(e){throw new ApiError(ErrorCode.EIO,"Unable to delete key "+key+": "+e)}};var LocalStorageFileSystem=function(SyncKeyValueFileSystem$$1){function LocalStorageFileSystem2(){SyncKeyValueFileSystem$$1.call(this,{store:new LocalStorageStore})}if(SyncKeyValueFileSystem$$1)LocalStorageFileSystem2.__proto__=SyncKeyValueFileSystem$$1;LocalStorageFileSystem2.prototype=Object.create(SyncKeyValueFileSystem$$1&&SyncKeyValueFileSystem$$1.prototype);LocalStorageFileSystem2.prototype.constructor=LocalStorageFileSystem2;LocalStorageFileSystem2.Create=function Create(options,cb){cb(null,new LocalStorageFileSystem2)};LocalStorageFileSystem2.isAvailable=function isAvailable(){return typeof global$1.localStorage!=="undefined"};return LocalStorageFileSystem2}(SyncKeyValueFileSystem);LocalStorageFileSystem.Name="LocalStorage";LocalStorageFileSystem.Options={};var MountableFileSystem=function(BaseFileSystem$$1){function MountableFileSystem2(){BaseFileSystem$$1.call(this);this.mountList=[];this.mntMap={};this.rootFs=new InMemoryFileSystem}if(BaseFileSystem$$1)MountableFileSystem2.__proto__=BaseFileSystem$$1;MountableFileSystem2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);MountableFileSystem2.prototype.constructor=MountableFileSystem2;MountableFileSystem2.Create=function Create(opts,cb){var fs4=new MountableFileSystem2;Object.keys(opts).forEach(function(mountPoint){fs4.mount(mountPoint,opts[mountPoint])});cb(null,fs4)};MountableFileSystem2.isAvailable=function isAvailable(){return true};MountableFileSystem2.prototype.mount=function mount(mountPoint,fs4){if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already taken.")}mkdirpSync(mountPoint,511,this.rootFs);this.mntMap[mountPoint]=fs4;this.mountList.push(mountPoint);this.mountList=this.mountList.sort(function(a,b){return b.length-a.length})};MountableFileSystem2.prototype.umount=function umount(mountPoint){var this$1=this;if(mountPoint[0]!=="/"){mountPoint="/"+mountPoint}mountPoint=path.resolve(mountPoint);if(!this.mntMap[mountPoint]){throw new ApiError(ErrorCode.EINVAL,"Mount point "+mountPoint+" is already unmounted.")}delete this.mntMap[mountPoint];this.mountList.splice(this.mountList.indexOf(mountPoint),1);while(mountPoint!=="/"){if(this$1.rootFs.readdirSync(mountPoint).length===0){this$1.rootFs.rmdirSync(mountPoint);mountPoint=path.dirname(mountPoint)}else{break}}};MountableFileSystem2.prototype._getFs=function _getFs(path$$1){var this$1=this;var mountList=this.mountList,len=mountList.length;for(var i2=0;i21?mountPoint.length:0);if(path$$1===""){path$$1="/"}return{fs:this$1.mntMap[mountPoint],path:path$$1}}}return{fs:this.rootFs,path:path$$1}};MountableFileSystem2.prototype.getName=function getName(){return MountableFileSystem2.Name};MountableFileSystem2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};MountableFileSystem2.prototype.isReadOnly=function isReadOnly(){return false};MountableFileSystem2.prototype.supportsLinks=function supportsLinks(){return false};MountableFileSystem2.prototype.supportsProps=function supportsProps(){return false};MountableFileSystem2.prototype.supportsSynch=function supportsSynch(){return true};MountableFileSystem2.prototype.standardizeError=function standardizeError(err,path$$1,realPath){var index=err.message.indexOf(path$$1);if(index!==-1){err.message=err.message.substr(0,index)+realPath+err.message.substr(index+path$$1.length);err.path=realPath}return err};MountableFileSystem2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){return fs1rv.fs.rename(fs1rv.path,fs2rv.path,function(e){if(e){this$1.standardizeError(this$1.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath)}cb(e)})}return _fsMock.readFile(oldPath,function(err,data){if(err){return cb(err)}_fsMock.writeFile(newPath,data,function(err2){if(err2){return cb(err2)}_fsMock.unlink(oldPath,cb)})})};MountableFileSystem2.prototype.renameSync=function renameSync(oldPath,newPath){var fs1rv=this._getFs(oldPath);var fs2rv=this._getFs(newPath);if(fs1rv.fs===fs2rv.fs){try{return fs1rv.fs.renameSync(fs1rv.path,fs2rv.path)}catch(e){this.standardizeError(this.standardizeError(e,fs1rv.path,oldPath),fs2rv.path,newPath);throw e}}var data=_fsMock.readFileSync(oldPath);_fsMock.writeFileSync(newPath,data);return _fsMock.unlinkSync(oldPath)};MountableFileSystem2.prototype.readdirSync=function readdirSync(p){var fsInfo=this._getFs(p);var rv=null;if(fsInfo.fs!==this.rootFs){try{rv=this.rootFs.readdirSync(p)}catch(e){}}try{var rv2=fsInfo.fs.readdirSync(fsInfo.path);if(rv===null){return rv2}else{return rv2.concat(rv.filter(function(val){return rv2.indexOf(val)===-1}))}}catch(e){if(rv===null){throw this.standardizeError(e,fsInfo.path,p)}else{return rv}}};MountableFileSystem2.prototype.readdir=function readdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);fsInfo.fs.readdir(fsInfo.path,function(err,files){if(fsInfo.fs!==this$1.rootFs){try{var rv=this$1.rootFs.readdirSync(p);if(files){files=files.concat(rv.filter(function(val){return files.indexOf(val)===-1}))}else{files=rv}}catch(e){if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}}}else if(err){return cb(this$1.standardizeError(err,fsInfo.path,p))}cb(null,files)})};MountableFileSystem2.prototype.rmdirSync=function rmdirSync(p){var fsInfo=this._getFs(p);if(this._containsMountPt(p)){throw ApiError.ENOTEMPTY(p)}else{try{fsInfo.fs.rmdirSync(fsInfo.path)}catch(e){throw this.standardizeError(e,fsInfo.path,p)}}};MountableFileSystem2.prototype.rmdir=function rmdir(p,cb){var this$1=this;var fsInfo=this._getFs(p);if(this._containsMountPt(p)){cb(ApiError.ENOTEMPTY(p))}else{fsInfo.fs.rmdir(fsInfo.path,function(err){cb(err?this$1.standardizeError(err,fsInfo.path,p):null)})}};MountableFileSystem2.prototype._containsMountPt=function _containsMountPt(p){var mountPoints=this.mountList,len=mountPoints.length;for(var i2=0;i2=p.length&&pt.slice(0,p.length)===p){return true}}return false};return MountableFileSystem2}(BaseFileSystem);MountableFileSystem.Name="MountableFileSystem";MountableFileSystem.Options={};function defineFcn(name,isSync,numArgs){if(isSync){return function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;try{return rv.fs[name].apply(rv.fs,args)}catch(e){this.standardizeError(e,rv.path,path$$1);throw e}}}else{return function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var path$$1=args[0];var rv=this._getFs(path$$1);args[0]=rv.path;if(typeof args[args.length-1]==="function"){var cb=args[args.length-1];args[args.length-1]=function(){var args2=[],len2=arguments.length;while(len2--)args2[len2]=arguments[len2];if(args2.length>0&&args2[0]instanceof ApiError){this$1.standardizeError(args2[0],rv.path,path$$1)}cb.apply(null,args2)}}return rv.fs[name].apply(rv.fs,args)}}}var fsCmdMap=[["exists","unlink","readlink"],["stat","mkdir","realpath","truncate"],["open","readFile","chmod","utimes"],["chown"],["writeFile","appendFile"]];for(var i=0;i0){var fn=timeouts.shift();return fn()}}};if(gScope.addEventListener){gScope.addEventListener("message",handleMessage,true)}else{gScope.attachEvent("onmessage",handleMessage)}}else if(gScope.MessageChannel){var channel=new gScope.MessageChannel;channel.port1.onmessage=function(event){if(timeouts.length>0){return timeouts.shift()()}};bfsSetImmediate=function(fn){timeouts.push(fn);channel.port2.postMessage("")}}else{bfsSetImmediate=function(fn){return setTimeout(fn,0)}}}var setImmediate$3=bfsSetImmediate;var Mutex=function Mutex2(){this._locked=false;this._waiters=[]};Mutex.prototype.lock=function lock(cb){if(this._locked){this._waiters.push(cb);return}this._locked=true;cb()};Mutex.prototype.unlock=function unlock(){if(!this._locked){throw new Error("unlock of a non-locked mutex")}var next=this._waiters.shift();if(next){setImmediate$3(next);return}this._locked=false};Mutex.prototype.tryLock=function tryLock(){if(this._locked){return false}this._locked=true;return true};Mutex.prototype.isLocked=function isLocked(){return this._locked};var LockedFS=function LockedFS2(fs4){this._fs=fs4;this._mu=new Mutex};LockedFS.prototype.getName=function getName(){return"LockedFS<"+this._fs.getName()+">"};LockedFS.prototype.getFSUnlocked=function getFSUnlocked(){return this._fs};LockedFS.prototype.initialize=function initialize3(cb){this._fs.initialize(cb)};LockedFS.prototype.diskSpace=function diskSpace(p,cb){this._fs.diskSpace(p,cb)};LockedFS.prototype.isReadOnly=function isReadOnly(){return this._fs.isReadOnly()};LockedFS.prototype.supportsLinks=function supportsLinks(){return this._fs.supportsLinks()};LockedFS.prototype.supportsProps=function supportsProps(){return this._fs.supportsProps()};LockedFS.prototype.supportsSynch=function supportsSynch(){return this._fs.supportsSynch()};LockedFS.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rename(oldPath,newPath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.renameSync=function renameSync(oldPath,newPath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.renameSync(oldPath,newPath)};LockedFS.prototype.stat=function stat(p,isLstat,cb){var this$1=this;this._mu.lock(function(){this$1._fs.stat(p,isLstat,function(err,stat2){this$1._mu.unlock();cb(err,stat2)})})};LockedFS.prototype.statSync=function statSync(p,isLstat){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.statSync(p,isLstat)};LockedFS.prototype.open=function open(p,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.open(p,flag,mode,function(err,fd){this$1._mu.unlock();cb(err,fd)})})};LockedFS.prototype.openSync=function openSync(p,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.openSync(p,flag,mode)};LockedFS.prototype.unlink=function unlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.unlink(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.unlinkSync=function unlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.unlinkSync(p)};LockedFS.prototype.rmdir=function rmdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.rmdir(p,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.rmdirSync=function rmdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.rmdirSync(p)};LockedFS.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.mkdir(p,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.mkdirSync=function mkdirSync(p,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.mkdirSync(p,mode)};LockedFS.prototype.readdir=function readdir(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readdir(p,function(err,files){this$1._mu.unlock();cb(err,files)})})};LockedFS.prototype.readdirSync=function readdirSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readdirSync(p)};LockedFS.prototype.exists=function exists2(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.exists(p,function(exists3){this$1._mu.unlock();cb(exists3)})})};LockedFS.prototype.existsSync=function existsSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.existsSync(p)};LockedFS.prototype.realpath=function realpath(p,cache,cb){var this$1=this;this._mu.lock(function(){this$1._fs.realpath(p,cache,function(err,resolvedPath){this$1._mu.unlock();cb(err,resolvedPath)})})};LockedFS.prototype.realpathSync=function realpathSync(p,cache){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.realpathSync(p,cache)};LockedFS.prototype.truncate=function truncate(p,len,cb){var this$1=this;this._mu.lock(function(){this$1._fs.truncate(p,len,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.truncateSync=function truncateSync(p,len){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.truncateSync(p,len)};LockedFS.prototype.readFile=function readFile2(fname,encoding,flag,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readFile(fname,encoding,flag,function(err,data){this$1._mu.unlock();cb(err,data)})})};LockedFS.prototype.readFileSync=function readFileSync(fname,encoding,flag){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readFileSync(fname,encoding,flag)};LockedFS.prototype.writeFile=function writeFile2(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.writeFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.writeFileSync=function writeFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.writeFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.appendFile=function appendFile3(fname,data,encoding,flag,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.appendFile(fname,data,encoding,flag,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.appendFileSync=function appendFileSync(fname,data,encoding,flag,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.appendFileSync(fname,data,encoding,flag,mode)};LockedFS.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chmod(p,isLchmod,mode,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chmodSync=function chmodSync(p,isLchmod,mode){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chmodSync(p,isLchmod,mode)};LockedFS.prototype.chown=function chown(p,isLchown,uid,gid,cb){var this$1=this;this._mu.lock(function(){this$1._fs.chown(p,isLchown,uid,gid,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.chownSync=function chownSync(p,isLchown,uid,gid){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.chownSync(p,isLchown,uid,gid)};LockedFS.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;this._mu.lock(function(){this$1._fs.utimes(p,atime,mtime,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.utimesSync=function utimesSync(p,atime,mtime){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.utimesSync(p,atime,mtime)};LockedFS.prototype.link=function link(srcpath,dstpath,cb){var this$1=this;this._mu.lock(function(){this$1._fs.link(srcpath,dstpath,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.linkSync=function linkSync(srcpath,dstpath){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.linkSync(srcpath,dstpath)};LockedFS.prototype.symlink=function symlink(srcpath,dstpath,type,cb){var this$1=this;this._mu.lock(function(){this$1._fs.symlink(srcpath,dstpath,type,function(err){this$1._mu.unlock();cb(err)})})};LockedFS.prototype.symlinkSync=function symlinkSync(srcpath,dstpath,type){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.symlinkSync(srcpath,dstpath,type)};LockedFS.prototype.readlink=function readlink(p,cb){var this$1=this;this._mu.lock(function(){this$1._fs.readlink(p,function(err,linkString){this$1._mu.unlock();cb(err,linkString)})})};LockedFS.prototype.readlinkSync=function readlinkSync(p){if(this._mu.isLocked()){throw new Error("invalid sync call")}return this._fs.readlinkSync(p)};var deletionLogPath="/.deletedFiles.log";function makeModeWritable(mode){return 146|mode}function getFlag(f){return FileFlag.getFileFlag(f)}var OverlayFile=function(PreloadFile$$1){function OverlayFile2(fs4,path$$1,flag,stats,data){PreloadFile$$1.call(this,fs4,path$$1,flag,stats,data)}if(PreloadFile$$1)OverlayFile2.__proto__=PreloadFile$$1;OverlayFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);OverlayFile2.prototype.constructor=OverlayFile2;OverlayFile2.prototype.sync=function sync(cb){var this$1=this;if(!this.isDirty()){cb(null);return}this._fs._syncAsync(this,function(err){this$1.resetDirty();cb(err)})};OverlayFile2.prototype.syncSync=function syncSync(){if(this.isDirty()){this._fs._syncSync(this);this.resetDirty()}};OverlayFile2.prototype.close=function close(cb){this.sync(cb)};OverlayFile2.prototype.closeSync=function closeSync(){this.syncSync()};return OverlayFile2}(PreloadFile);var UnlockedOverlayFS=function(BaseFileSystem$$1){function UnlockedOverlayFS2(writable,readable){BaseFileSystem$$1.call(this);this._isInitialized=false;this._initializeCallbacks=[];this._deletedFiles={};this._deleteLog="";this._deleteLogUpdatePending=false;this._deleteLogUpdateNeeded=false;this._deleteLogError=null;this._writable=writable;this._readable=readable;if(this._writable.isReadOnly()){throw new ApiError(ErrorCode.EINVAL,"Writable file system must be writable.")}}if(BaseFileSystem$$1)UnlockedOverlayFS2.__proto__=BaseFileSystem$$1;UnlockedOverlayFS2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);UnlockedOverlayFS2.prototype.constructor=UnlockedOverlayFS2;UnlockedOverlayFS2.isAvailable=function isAvailable(){return true};UnlockedOverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return{readable:this._readable,writable:this._writable}};UnlockedOverlayFS2.prototype._syncAsync=function _syncAsync(file,cb){var this$1=this;this.createParentDirectoriesAsync(file.getPath(),function(err){if(err){return cb(err)}this$1._writable.writeFile(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode,cb)})};UnlockedOverlayFS2.prototype._syncSync=function _syncSync(file){this.createParentDirectories(file.getPath());this._writable.writeFileSync(file.getPath(),file.getBuffer(),null,getFlag("w"),file.getStats().mode)};UnlockedOverlayFS2.prototype.getName=function getName(){return OverlayFS.Name};UnlockedOverlayFS2.prototype.initialize=function initialize3(cb){var this$1=this;var callbackArray=this._initializeCallbacks;var end=function(e){this$1._isInitialized=!e;this$1._initializeCallbacks=[];callbackArray.forEach(function(cb2){return cb2(e)})};if(this._isInitialized){return cb()}callbackArray.push(cb);if(callbackArray.length!==1){return}this._writable.readFile(deletionLogPath,"utf8",getFlag("r"),function(err,data){if(err){if(err.errno!==ErrorCode.ENOENT){return end(err)}}else{this$1._deleteLog=data}this$1._reparseDeletionLog();end()})};UnlockedOverlayFS2.prototype.isReadOnly=function isReadOnly(){return false};UnlockedOverlayFS2.prototype.supportsSynch=function supportsSynch(){return this._readable.supportsSynch()&&this._writable.supportsSynch()};UnlockedOverlayFS2.prototype.supportsLinks=function supportsLinks(){return false};UnlockedOverlayFS2.prototype.supportsProps=function supportsProps(){return this._readable.supportsProps()&&this._writable.supportsProps()};UnlockedOverlayFS2.prototype.getDeletionLog=function getDeletionLog(){return this._deleteLog};UnlockedOverlayFS2.prototype.restoreDeletionLog=function restoreDeletionLog(log){this._deleteLog=log;this._reparseDeletionLog();this.updateLog("")};UnlockedOverlayFS2.prototype.rename=function rename(oldPath,newPath,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(oldPath,cb)||this.checkPathAsync(newPath,cb)){return}if(oldPath===deletionLogPath||newPath===deletionLogPath){return cb(ApiError.EPERM("Cannot rename deletion log."))}if(oldPath===newPath){return cb()}this.stat(oldPath,false,function(oldErr,oldStats){if(oldErr){return cb(oldErr)}return this$1.stat(newPath,false,function(newErr,newStats){var self2=this$1;function copyDirContents(files){var file=files.shift();if(!file){return cb()}var oldFile=path.resolve(oldPath,file);var newFile=path.resolve(newPath,file);self2.rename(oldFile,newFile,function(err){if(err){return cb(err)}copyDirContents(files)})}var mode=511;if(oldStats.isDirectory()){if(newErr){if(newErr.errno!==ErrorCode.ENOENT){return cb(newErr)}return this$1._writable.exists(oldPath,function(exists2){if(exists2){return this$1._writable.rename(oldPath,newPath,cb)}this$1._writable.mkdir(newPath,mode,function(mkdirErr){if(mkdirErr){return cb(mkdirErr)}this$1._readable.readdir(oldPath,function(err,files){if(err){return cb()}copyDirContents(files)})})})}mode=newStats.mode;if(!newStats.isDirectory()){return cb(ApiError.ENOTDIR(newPath))}this$1.readdir(newPath,function(readdirErr,files){if(files&&files.length){return cb(ApiError.ENOTEMPTY(newPath))}this$1._readable.readdir(oldPath,function(err,files2){if(err){return cb()}copyDirContents(files2)})})}if(newStats&&newStats.isDirectory()){return cb(ApiError.EISDIR(newPath))}this$1.readFile(oldPath,null,getFlag("r"),function(err,data){if(err){return cb(err)}return this$1.writeFile(newPath,data,null,getFlag("w"),oldStats.mode,function(err2){if(err2){return cb(err2)}return this$1.unlink(oldPath,cb)})})})})};UnlockedOverlayFS2.prototype.renameSync=function renameSync(oldPath,newPath){var this$1=this;this.checkInitialized();this.checkPath(oldPath);this.checkPath(newPath);if(oldPath===deletionLogPath||newPath===deletionLogPath){throw ApiError.EPERM("Cannot rename deletion log.")}var oldStats=this.statSync(oldPath,false);if(oldStats.isDirectory()){if(oldPath===newPath){return}var mode=511;if(this.existsSync(newPath)){var stats=this.statSync(newPath,false);mode=stats.mode;if(stats.isDirectory()){if(this.readdirSync(newPath).length>0){throw ApiError.ENOTEMPTY(newPath)}}else{throw ApiError.ENOTDIR(newPath)}}if(this._writable.existsSync(oldPath)){this._writable.renameSync(oldPath,newPath)}else if(!this._writable.existsSync(newPath)){this._writable.mkdirSync(newPath,mode)}if(this._readable.existsSync(oldPath)){this._readable.readdirSync(oldPath).forEach(function(name){this$1.renameSync(path.resolve(oldPath,name),path.resolve(newPath,name))})}}else{if(this.existsSync(newPath)&&this.statSync(newPath,false).isDirectory()){throw ApiError.EISDIR(newPath)}this.writeFileSync(newPath,this.readFileSync(oldPath,null,getFlag("r")),null,getFlag("w"),oldStats.mode)}if(oldPath!==newPath&&this.existsSync(oldPath)){this.unlinkSync(oldPath)}};UnlockedOverlayFS2.prototype.stat=function stat(p,isLstat,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this._writable.stat(p,isLstat,function(err,stat2){if(err&&err.errno===ErrorCode.ENOENT){if(this$1._deletedFiles[p]){cb(ApiError.ENOENT(p))}this$1._readable.stat(p,isLstat,function(err2,stat3){if(stat3){stat3=stat3.clone();stat3.mode=makeModeWritable(stat3.mode)}cb(err2,stat3)})}else{cb(err,stat2)}})};UnlockedOverlayFS2.prototype.statSync=function statSync(p,isLstat){this.checkInitialized();try{return this._writable.statSync(p,isLstat)}catch(e){if(this._deletedFiles[p]){throw ApiError.ENOENT(p)}var oldStat=this._readable.statSync(p,isLstat).clone();oldStat.mode=makeModeWritable(oldStat.mode);return oldStat}};UnlockedOverlayFS2.prototype.open=function open(p,flag,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.stat(p,false,function(err,stats){if(stats){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}this$1._writable.open(p,flag,mode,cb)});case ActionType.NOP:return this$1._writable.exists(p,function(exists2){if(exists2){this$1._writable.open(p,flag,mode,cb)}else{stats=stats.clone();stats.mode=mode;this$1._readable.readFile(p,null,getFlag("r"),function(readFileErr,data){if(readFileErr){return cb(readFileErr)}if(stats.size===-1){stats.size=data.length}var f=new OverlayFile(this$1,p,flag,stats,data);cb(null,f)})}});default:return cb(ApiError.EEXIST(p))}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:return this$1.createParentDirectoriesAsync(p,function(err2){if(err2){return cb(err2)}return this$1._writable.open(p,flag,mode,cb)});default:return cb(ApiError.ENOENT(p))}}})};UnlockedOverlayFS2.prototype.openSync=function openSync(p,flag,mode){this.checkInitialized();this.checkPath(p);if(p===deletionLogPath){throw ApiError.EPERM("Cannot open deletion log.")}if(this.existsSync(p)){switch(flag.pathExistsAction()){case ActionType.TRUNCATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);case ActionType.NOP:if(this._writable.existsSync(p)){return this._writable.openSync(p,flag,mode)}else{var buf=this._readable.readFileSync(p,null,getFlag("r"));var stats=this._readable.statSync(p,false).clone();stats.mode=mode;return new OverlayFile(this,p,flag,stats,buf)}default:throw ApiError.EEXIST(p)}}else{switch(flag.pathNotExistsAction()){case ActionType.CREATE_FILE:this.createParentDirectories(p);return this._writable.openSync(p,flag,mode);default:throw ApiError.ENOENT(p)}}};UnlockedOverlayFS2.prototype.unlink=function unlink(p,cb){var this$1=this;if(!this.checkInitAsync(cb)||this.checkPathAsync(p,cb)){return}this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){return this$1._writable.unlink(p,function(err){if(err){return cb(err)}this$1.exists(p,function(readableExists){if(readableExists){this$1.deletePath(p)}cb(null)})})}else{this$1.deletePath(p);cb(null)}})})};UnlockedOverlayFS2.prototype.unlinkSync=function unlinkSync(p){this.checkInitialized();this.checkPath(p);if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.unlinkSync(p)}if(this.existsSync(p)){this.deletePath(p)}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.rmdir=function rmdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}var rmdirLower=function(){this$1.readdir(p,function(err,files){if(err){return cb(err)}if(files.length){return cb(ApiError.ENOTEMPTY(p))}this$1.deletePath(p);cb(null)})};this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(writableExists){if(writableExists){this$1._writable.rmdir(p,function(err){if(err){return cb(err)}this$1._readable.exists(p,function(readableExists){if(readableExists){rmdirLower()}else{cb()}})})}else{rmdirLower()}})})};UnlockedOverlayFS2.prototype.rmdirSync=function rmdirSync(p){this.checkInitialized();if(this.existsSync(p)){if(this._writable.existsSync(p)){this._writable.rmdirSync(p)}if(this.existsSync(p)){if(this.readdirSync(p).length>0){throw ApiError.ENOTEMPTY(p)}else{this.deletePath(p)}}}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.mkdir=function mkdir(p,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.exists(p,function(exists2){if(exists2){return cb(ApiError.EEXIST(p))}this$1.createParentDirectoriesAsync(p,function(err){if(err){return cb(err)}this$1._writable.mkdir(p,mode,cb)})})};UnlockedOverlayFS2.prototype.mkdirSync=function mkdirSync(p,mode){this.checkInitialized();if(this.existsSync(p)){throw ApiError.EEXIST(p)}else{this.createParentDirectories(p);this._writable.mkdirSync(p,mode)}};UnlockedOverlayFS2.prototype.readdir=function readdir(p,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.stat(p,false,function(err,dirStats){if(err){return cb(err)}if(!dirStats.isDirectory()){return cb(ApiError.ENOTDIR(p))}this$1._writable.readdir(p,function(err2,wFiles){if(err2&&err2.code!=="ENOENT"){return cb(err2)}else if(err2||!wFiles){wFiles=[]}this$1._readable.readdir(p,function(err3,rFiles){if(err3||!rFiles){rFiles=[]}var seenMap={};var filtered=wFiles.concat(rFiles.filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]})).filter(function(fPath){var result=!seenMap[fPath];seenMap[fPath]=true;return result});cb(null,filtered)})})})};UnlockedOverlayFS2.prototype.readdirSync=function readdirSync(p){var this$1=this;this.checkInitialized();var dirStats=this.statSync(p,false);if(!dirStats.isDirectory()){throw ApiError.ENOTDIR(p)}var contents=[];try{contents=contents.concat(this._writable.readdirSync(p))}catch(e){}try{contents=contents.concat(this._readable.readdirSync(p).filter(function(fPath){return!this$1._deletedFiles[p+"/"+fPath]}))}catch(e){}var seenMap={};return contents.filter(function(fileP){var result=!seenMap[fileP];seenMap[fileP]=true;return result})};UnlockedOverlayFS2.prototype.exists=function exists2(p,cb){var this$1=this;this.checkInitialized();this._writable.exists(p,function(existsWritable){if(existsWritable){return cb(true)}this$1._readable.exists(p,function(existsReadable){cb(existsReadable&&this$1._deletedFiles[p]!==true)})})};UnlockedOverlayFS2.prototype.existsSync=function existsSync(p){this.checkInitialized();return this._writable.existsSync(p)||this._readable.existsSync(p)&&this._deletedFiles[p]!==true};UnlockedOverlayFS2.prototype.chmod=function chmod(p,isLchmod,mode,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chmod(p,isLchmod,mode,cb)}})};UnlockedOverlayFS2.prototype.chmodSync=function chmodSync(p,isLchmod,mode){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chmodSync(p,isLchmod,mode)})};UnlockedOverlayFS2.prototype.chown=function chown(p,isLchmod,uid,gid,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.chown(p,isLchmod,uid,gid,cb)}})};UnlockedOverlayFS2.prototype.chownSync=function chownSync(p,isLchown,uid,gid){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.chownSync(p,isLchown,uid,gid)})};UnlockedOverlayFS2.prototype.utimes=function utimes(p,atime,mtime,cb){var this$1=this;if(!this.checkInitAsync(cb)){return}this.operateOnWritableAsync(p,function(err){if(err){return cb(err)}else{this$1._writable.utimes(p,atime,mtime,cb)}})};UnlockedOverlayFS2.prototype.utimesSync=function utimesSync(p,atime,mtime){var this$1=this;this.checkInitialized();this.operateOnWritable(p,function(){this$1._writable.utimesSync(p,atime,mtime)})};UnlockedOverlayFS2.prototype.deletePath=function deletePath(p){this._deletedFiles[p]=true;this.updateLog("d"+p+"\n")};UnlockedOverlayFS2.prototype.updateLog=function updateLog(addition){var this$1=this;this._deleteLog+=addition;if(this._deleteLogUpdatePending){this._deleteLogUpdateNeeded=true}else{this._deleteLogUpdatePending=true;this._writable.writeFile(deletionLogPath,this._deleteLog,"utf8",FileFlag.getFileFlag("w"),420,function(e){this$1._deleteLogUpdatePending=false;if(e){this$1._deleteLogError=e}else if(this$1._deleteLogUpdateNeeded){this$1._deleteLogUpdateNeeded=false;this$1.updateLog("")}})}};UnlockedOverlayFS2.prototype._reparseDeletionLog=function _reparseDeletionLog(){var this$1=this;this._deletedFiles={};this._deleteLog.split("\n").forEach(function(path$$1){this$1._deletedFiles[path$$1.slice(1)]=path$$1.slice(0,1)==="d"})};UnlockedOverlayFS2.prototype.checkInitialized=function checkInitialized(){if(!this._isInitialized){throw new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.")}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;throw e}};UnlockedOverlayFS2.prototype.checkInitAsync=function checkInitAsync(cb){if(!this._isInitialized){cb(new ApiError(ErrorCode.EPERM,"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it."));return false}else if(this._deleteLogError!==null){var e=this._deleteLogError;this._deleteLogError=null;cb(e);return false}return true};UnlockedOverlayFS2.prototype.checkPath=function checkPath(p){if(p===deletionLogPath){throw ApiError.EPERM(p)}};UnlockedOverlayFS2.prototype.checkPathAsync=function checkPathAsync(p,cb){if(p===deletionLogPath){cb(ApiError.EPERM(p));return true}return false};UnlockedOverlayFS2.prototype.createParentDirectoriesAsync=function createParentDirectoriesAsync(p,cb){var parent=path.dirname(p);var toCreate=[];var self2=this;this._writable.stat(parent,false,statDone);function statDone(err,stat){if(err){toCreate.push(parent);parent=path.dirname(parent);self2._writable.stat(parent,false,statDone)}else{createParents()}}function createParents(){if(!toCreate.length){return cb()}var dir=toCreate.pop();self2._readable.stat(dir,false,function(err,stats){if(!stats){return cb()}self2._writable.mkdir(dir,stats.mode,function(err2){if(err2){return cb(err2)}createParents()})})}};UnlockedOverlayFS2.prototype.createParentDirectories=function createParentDirectories(p){var this$1=this;var parent=path.dirname(p),toCreate=[];while(!this._writable.existsSync(parent)){toCreate.push(parent);parent=path.dirname(parent)}toCreate=toCreate.reverse();toCreate.forEach(function(p2){this$1._writable.mkdirSync(p2,this$1.statSync(p2,false).mode)})};UnlockedOverlayFS2.prototype.operateOnWritable=function operateOnWritable(p,f){if(this.existsSync(p)){if(!this._writable.existsSync(p)){this.copyToWritable(p)}f()}else{throw ApiError.ENOENT(p)}};UnlockedOverlayFS2.prototype.operateOnWritableAsync=function operateOnWritableAsync(p,cb){var this$1=this;this.exists(p,function(exists2){if(!exists2){return cb(ApiError.ENOENT(p))}this$1._writable.exists(p,function(existsWritable){if(existsWritable){cb()}else{return this$1.copyToWritableAsync(p,cb)}})})};UnlockedOverlayFS2.prototype.copyToWritable=function copyToWritable(p){var pStats=this.statSync(p,false);if(pStats.isDirectory()){this._writable.mkdirSync(p,pStats.mode)}else{this.writeFileSync(p,this._readable.readFileSync(p,null,getFlag("r")),null,getFlag("w"),this.statSync(p,false).mode)}};UnlockedOverlayFS2.prototype.copyToWritableAsync=function copyToWritableAsync(p,cb){var this$1=this;this.stat(p,false,function(err,pStats){if(err){return cb(err)}if(pStats.isDirectory()){return this$1._writable.mkdir(p,pStats.mode,cb)}this$1._readable.readFile(p,null,getFlag("r"),function(err2,data){if(err2){return cb(err2)}this$1.writeFile(p,data,null,getFlag("w"),pStats.mode,cb)})})};return UnlockedOverlayFS2}(BaseFileSystem);var OverlayFS=function(LockedFS$$1){function OverlayFS2(writable,readable,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;LockedFS$$1.call(this,new UnlockedOverlayFS(writable,readable));deprecationMessage(deprecateMsg,OverlayFS2.Name,{readable:"readable file system",writable:"writable file system"})}if(LockedFS$$1)OverlayFS2.__proto__=LockedFS$$1;OverlayFS2.prototype=Object.create(LockedFS$$1&&LockedFS$$1.prototype);OverlayFS2.prototype.constructor=OverlayFS2;OverlayFS2.Create=function Create(opts,cb){try{var fs4=new OverlayFS2(opts.writable,opts.readable,false);fs4.initialize(function(e){cb(e,fs4)},false)}catch(e){cb(e)}};OverlayFS2.isAvailable=function isAvailable(){return UnlockedOverlayFS.isAvailable()};OverlayFS2.prototype.initialize=function initialize3(cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[OverlayFS] OverlayFS.initialize() is deprecated and will be removed in the next major release. Please use 'OverlayFS.Create({readable: readable file system instance, writable: writable file system instance}, cb)' to create and initialize OverlayFS instances.")}LockedFS$$1.prototype.initialize.call(this,cb)};OverlayFS2.prototype.getOverlayedFileSystems=function getOverlayedFileSystems(){return LockedFS$$1.prototype.getFSUnlocked.call(this).getOverlayedFileSystems()};OverlayFS2.prototype.unwrap=function unwrap(){return LockedFS$$1.prototype.getFSUnlocked.call(this)};return OverlayFS2}(LockedFS);OverlayFS.Name="OverlayFS";OverlayFS.Options={writable:{type:"object",description:"The file system to write modified files to."},readable:{type:"object",description:"The file system that initially populates this file system."}};var SpecialArgType;(function(SpecialArgType2){SpecialArgType2[SpecialArgType2["CB"]=0]="CB";SpecialArgType2[SpecialArgType2["FD"]=1]="FD";SpecialArgType2[SpecialArgType2["API_ERROR"]=2]="API_ERROR";SpecialArgType2[SpecialArgType2["STATS"]=3]="STATS";SpecialArgType2[SpecialArgType2["PROBE"]=4]="PROBE";SpecialArgType2[SpecialArgType2["FILEFLAG"]=5]="FILEFLAG";SpecialArgType2[SpecialArgType2["BUFFER"]=6]="BUFFER";SpecialArgType2[SpecialArgType2["ERROR"]=7]="ERROR"})(SpecialArgType||(SpecialArgType={}));var CallbackArgumentConverter=function CallbackArgumentConverter2(){this._callbacks={};this._nextId=0};CallbackArgumentConverter.prototype.toRemoteArg=function toRemoteArg(cb){var id=this._nextId++;this._callbacks[id]=cb;return{type:SpecialArgType.CB,id}};CallbackArgumentConverter.prototype.toLocalArg=function toLocalArg(id){var cb=this._callbacks[id];delete this._callbacks[id];return cb};var FileDescriptorArgumentConverter=function FileDescriptorArgumentConverter2(){this._fileDescriptors={};this._nextId=0};FileDescriptorArgumentConverter.prototype.toRemoteArg=function toRemoteArg(fd,p,flag,cb){var id=this._nextId++;var data;var stat;this._fileDescriptors[id]=fd;fd.stat(function(err,stats){if(err){cb(err)}else{stat=bufferToTransferrableObject(stats.toBuffer());if(flag.isReadable()){fd.read(Buffer2.alloc(stats.size),0,stats.size,0,function(err2,bytesRead,buff){if(err2){cb(err2)}else{data=bufferToTransferrableObject(buff);cb(null,{type:SpecialArgType.FD,id,data,stat,path:p,flag:flag.getFlagString()})}})}else{cb(null,{type:SpecialArgType.FD,id,data:new ArrayBuffer(0),stat,path:p,flag:flag.getFlagString()})}}})};FileDescriptorArgumentConverter.prototype.applyFdAPIRequest=function applyFdAPIRequest(request,cb){var this$1=this;var fdArg=request.args[0];this._applyFdChanges(fdArg,function(err,fd){if(err){cb(err)}else{fd[request.method](function(e){if(request.method==="close"){delete this$1._fileDescriptors[fdArg.id]}cb(e)})}})};FileDescriptorArgumentConverter.prototype._applyFdChanges=function _applyFdChanges(remoteFd,cb){var fd=this._fileDescriptors[remoteFd.id],data=transferrableObjectToBuffer(remoteFd.data),remoteStats=Stats.fromBuffer(transferrableObjectToBuffer(remoteFd.stat));var flag=FileFlag.getFileFlag(remoteFd.flag);if(flag.isWriteable()){fd.write(data,0,data.length,flag.isAppendable()?fd.getPos():0,function(e){function applyStatChanges(){fd.stat(function(e2,stats){if(e2){cb(e2)}else{if(stats.mode!==remoteStats.mode){fd.chmod(remoteStats.mode,function(e3){cb(e3,fd)})}else{cb(e2,fd)}}})}if(e){cb(e)}else{if(!flag.isAppendable()){fd.truncate(data.length,function(){applyStatChanges()})}else{applyStatChanges()}}})}else{cb(null,fd)}};function apiErrorLocal2Remote(e){return{type:SpecialArgType.API_ERROR,errorData:bufferToTransferrableObject(e.writeToBuffer())}}function apiErrorRemote2Local(e){return ApiError.fromBuffer(transferrableObjectToBuffer(e.errorData))}function errorLocal2Remote(e){return{type:SpecialArgType.ERROR,name:e.name,message:e.message,stack:e.stack}}function errorRemote2Local(e){var cnstr=global$1[e.name];if(typeof cnstr!=="function"){cnstr=Error}var err=new cnstr(e.message);err.stack=e.stack;return err}function statsLocal2Remote(stats){return{type:SpecialArgType.STATS,statsData:bufferToTransferrableObject(stats.toBuffer())}}function statsRemote2Local(stats){return Stats.fromBuffer(transferrableObjectToBuffer(stats.statsData))}function fileFlagLocal2Remote(flag){return{type:SpecialArgType.FILEFLAG,flagStr:flag.getFlagString()}}function fileFlagRemote2Local(remoteFlag){return FileFlag.getFileFlag(remoteFlag.flagStr)}function bufferToTransferrableObject(buff){return buffer2ArrayBuffer(buff)}function transferrableObjectToBuffer(buff){return arrayBuffer2Buffer(buff)}function bufferLocal2Remote(buff){return{type:SpecialArgType.BUFFER,data:bufferToTransferrableObject(buff)}}function bufferRemote2Local(buffArg){return transferrableObjectToBuffer(buffArg.data)}function isAPIRequest(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}function isAPIResponse(data){return data&&typeof data==="object"&&data.hasOwnProperty("browserfsMessage")&&data["browserfsMessage"]}var WorkerFile=function(PreloadFile$$1){function WorkerFile2(_fs,_path,_flag,_stat,remoteFdId,contents){PreloadFile$$1.call(this,_fs,_path,_flag,_stat,contents);this._remoteFdId=remoteFdId}if(PreloadFile$$1)WorkerFile2.__proto__=PreloadFile$$1;WorkerFile2.prototype=Object.create(PreloadFile$$1&&PreloadFile$$1.prototype);WorkerFile2.prototype.constructor=WorkerFile2;WorkerFile2.prototype.getRemoteFdId=function getRemoteFdId(){return this._remoteFdId};WorkerFile2.prototype.toRemoteArg=function toRemoteArg(){return{type:SpecialArgType.FD,id:this._remoteFdId,data:bufferToTransferrableObject(this.getBuffer()),stat:bufferToTransferrableObject(this.getStats().toBuffer()),path:this.getPath(),flag:this.getFlag().getFlagString()}};WorkerFile2.prototype.sync=function sync(cb){this._syncClose("sync",cb)};WorkerFile2.prototype.close=function close(cb){this._syncClose("close",cb)};WorkerFile2.prototype._syncClose=function _syncClose(type,cb){var this$1=this;if(this.isDirty()){this._fs.syncClose(type,this,function(e){if(!e){this$1.resetDirty()}cb(e)})}else{cb()}};return WorkerFile2}(PreloadFile);var WorkerFS=function(BaseFileSystem$$1){function WorkerFS2(worker,deprecateMsg){var this$1=this;if(deprecateMsg===void 0)deprecateMsg=true;BaseFileSystem$$1.call(this);this._callbackConverter=new CallbackArgumentConverter;this._isInitialized=false;this._isReadOnly=false;this._supportLinks=false;this._supportProps=false;this._worker=worker;deprecationMessage(deprecateMsg,WorkerFS2.Name,{worker:"Web Worker instance"});this._worker.addEventListener("message",function(e){var resp=e.data;if(isAPIResponse(resp)){var i2;var args=resp.args;var fixedArgs=new Array(args.length);for(i2=0;i20){countdown=-1;message={browserfsMessage:true,cbId,args:[apiErrorLocal2Remote(err)]};worker.postMessage(message)}}for(i2=0;i20){var inode=void 0;var next=queue.pop();var pwd=next[0];var tree=next[1];var parent=next[2];for(var node in tree){if(tree.hasOwnProperty(node)){var children=tree[node];var name=pwd+"/"+node;if(children){idx._index[name]=inode=new DirInode;queue.push([name,children,inode])}else{inode=new FileInode(new Stats(FileType.FILE,-1,365))}if(parent){parent._ls[node]=inode}}}}return idx};FileIndex.prototype.fileIterator=function fileIterator(cb){var this$1=this;for(var path$$1 in this$1._index){if(this$1._index.hasOwnProperty(path$$1)){var dir=this$1._index[path$$1];var files=dir.getListing();for(var i2=0,list2=files;i20&&prefixUrl.charAt(prefixUrl.length-1)!=="/"){prefixUrl=prefixUrl+"/"}this.prefixUrl=prefixUrl;var listing=null;if(typeof listingUrlOrObj==="string"){listing=this._requestFileSync(listingUrlOrObj,"json");if(!listing){throw new Error("Unable to find listing at URL: ${listingUrlOrObj}")}}else{listing=listingUrlOrObj}deprecationMessage(deprecateMsg,XmlHttpRequest2.Name,{index:typeof listingUrlOrObj==="string"?listingUrlOrObj:"file index as an object",baseUrl:prefixUrl});this._index=FileIndex.fromListing(listing)}if(BaseFileSystem$$1)XmlHttpRequest2.__proto__=BaseFileSystem$$1;XmlHttpRequest2.prototype=Object.create(BaseFileSystem$$1&&BaseFileSystem$$1.prototype);XmlHttpRequest2.prototype.constructor=XmlHttpRequest2;XmlHttpRequest2.Create=function Create(opts,cb){if(opts.index===void 0){opts.index="index.json"}if(typeof opts.index==="string"){XmlHttpRequest2.FromURL(opts.index,cb,opts.baseUrl,false)}else{cb(null,new XmlHttpRequest2(opts.index,opts.baseUrl,false))}};XmlHttpRequest2.isAvailable=function isAvailable(){return typeof XMLHttpRequest!=="undefined"&&XMLHttpRequest!==null};XmlHttpRequest2.FromURL=function FromURL(url,cb,baseUrl,deprecateMsg){if(baseUrl===void 0)baseUrl=url.slice(0,url.lastIndexOf("/")+1);if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn(`[XmlHttpRequest] XmlHttpRequest.FromURL() is deprecated and will be removed in the next major release. Please use 'XmlHttpRequest.Create({ index: "`+url+'", baseUrl: "'+baseUrl+`" }, cb)' instead.`)}asyncDownloadFile(url,"json",function(e,data){if(e){cb(e)}else{cb(null,new XmlHttpRequest2(data,baseUrl,false))}})};XmlHttpRequest2.prototype.empty=function empty(){this._index.fileIterator(function(file){file.fileData=null})};XmlHttpRequest2.prototype.getName=function getName(){return XmlHttpRequest2.Name};XmlHttpRequest2.prototype.diskSpace=function diskSpace(path$$1,cb){cb(0,0)};XmlHttpRequest2.prototype.isReadOnly=function isReadOnly(){return true};XmlHttpRequest2.prototype.supportsLinks=function supportsLinks(){return false};XmlHttpRequest2.prototype.supportsProps=function supportsProps(){return false};XmlHttpRequest2.prototype.supportsSynch=function supportsSynch(){return true};XmlHttpRequest2.prototype.preloadFile=function preloadFile(path$$1,buffer$$1){var inode=this._index.getInode(path$$1);if(isFileInode(inode)){if(inode===null){throw ApiError.ENOENT(path$$1)}var stats=inode.getData();stats.size=buffer$$1.length;stats.fileData=buffer$$1}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.stat=function stat(path$$1,isLstat,cb){var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){this._requestFileSizeAsync(path$$1,function(e,size){if(e){return cb(e)}stats.size=size;cb(null,stats.clone())})}else{cb(null,stats.clone())}}else if(isDirInode(inode)){stats=inode.getStats();cb(null,stats)}else{cb(ApiError.FileError(ErrorCode.EINVAL,path$$1))}};XmlHttpRequest2.prototype.statSync=function statSync(path$$1,isLstat){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}var stats;if(isFileInode(inode)){stats=inode.getData();if(stats.size<0){stats.size=this._requestFileSizeSync(path$$1)}}else if(isDirInode(inode)){stats=inode.getStats()}else{throw ApiError.FileError(ErrorCode.EINVAL,path$$1)}return stats};XmlHttpRequest2.prototype.open=function open(path$$1,flags,mode,cb){if(flags.isWriteable()){return cb(new ApiError(ErrorCode.EPERM,path$$1))}var self2=this;var inode=this._index.getInode(path$$1);if(inode===null){return cb(ApiError.ENOENT(path$$1))}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:return cb(ApiError.EEXIST(path$$1));case ActionType.NOP:if(stats.fileData){return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),stats.fileData))}this._requestFileAsync(path$$1,"buffer",function(err,buffer$$1){if(err){return cb(err)}stats.size=buffer$$1.length;stats.fileData=buffer$$1;return cb(null,new NoSyncFile(self2,path$$1,flags,stats.clone(),buffer$$1))});break;default:return cb(new ApiError(ErrorCode.EINVAL,"Invalid FileMode object."))}}else{return cb(ApiError.EISDIR(path$$1))}};XmlHttpRequest2.prototype.openSync=function openSync(path$$1,flags,mode){if(flags.isWriteable()){throw new ApiError(ErrorCode.EPERM,path$$1)}var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}if(isFileInode(inode)){var stats=inode.getData();switch(flags.pathExistsAction()){case ActionType.THROW_EXCEPTION:case ActionType.TRUNCATE_FILE:throw ApiError.EEXIST(path$$1);case ActionType.NOP:if(stats.fileData){return new NoSyncFile(this,path$$1,flags,stats.clone(),stats.fileData)}var buffer$$1=this._requestFileSync(path$$1,"buffer");stats.size=buffer$$1.length;stats.fileData=buffer$$1;return new NoSyncFile(this,path$$1,flags,stats.clone(),buffer$$1);default:throw new ApiError(ErrorCode.EINVAL,"Invalid FileMode object.")}}else{throw ApiError.EISDIR(path$$1)}};XmlHttpRequest2.prototype.readdir=function readdir(path$$1,cb){try{cb(null,this.readdirSync(path$$1))}catch(e){cb(e)}};XmlHttpRequest2.prototype.readdirSync=function readdirSync(path$$1){var inode=this._index.getInode(path$$1);if(inode===null){throw ApiError.ENOENT(path$$1)}else if(isDirInode(inode)){return inode.getListing()}else{throw ApiError.ENOTDIR(path$$1)}};XmlHttpRequest2.prototype.readFile=function readFile2(fname,encoding,flag,cb){var oldCb=cb;this.open(fname,flag,420,function(err,fd){if(err){return cb(err)}cb=function(err2,arg){fd.close(function(err22){if(!err2){err2=err22}return oldCb(err2,arg)})};var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){cb(err,copyingSlice(fdBuff))}else{tryToString(fdBuff,encoding,cb)}})};XmlHttpRequest2.prototype.readFileSync=function readFileSync(fname,encoding,flag){var fd=this.openSync(fname,flag,420);try{var fdCast=fd;var fdBuff=fdCast.getBuffer();if(encoding===null){return copyingSlice(fdBuff)}return fdBuff.toString(encoding)}finally{fd.closeSync()}};XmlHttpRequest2.prototype.getXhrPath=function getXhrPath(filePath){if(filePath.charAt(0)==="/"){filePath=filePath.slice(1)}return this.prefixUrl+filePath};XmlHttpRequest2.prototype._requestFileAsync=function _requestFileAsync(p,type,cb){asyncDownloadFile(this.getXhrPath(p),type,cb)};XmlHttpRequest2.prototype._requestFileSync=function _requestFileSync(p,type){return syncDownloadFile(this.getXhrPath(p),type)};XmlHttpRequest2.prototype._requestFileSizeAsync=function _requestFileSizeAsync(path$$1,cb){getFileSizeAsync(this.getXhrPath(path$$1),cb)};XmlHttpRequest2.prototype._requestFileSizeSync=function _requestFileSizeSync(path$$1){return getFileSizeSync(this.getXhrPath(path$$1))};return XmlHttpRequest2}(BaseFileSystem);XmlHttpRequest.Name="XmlHttpRequest";XmlHttpRequest.Options={index:{type:["string","object"],optional:true,description:"URL to a file index as a JSON file or the file index object itself, generated with the make_xhrfs_index script. Defaults to `index.json`."},baseUrl:{type:"string",optional:true,description:"Used as the URL prefix for fetched files. Default: Fetch files relative to the index."}};var ExtendedASCII=function ExtendedASCII2(){};ExtendedASCII.str2byte=function str2byte(str,buf){var length=str.length>buf.length?buf.length:str.length;for(var i2=0;i2127){var charIdx=ExtendedASCII.extendedChars.indexOf(str.charAt(i2));if(charIdx>-1){charCode=charIdx+128}}buf[charCode]=i2}return length};ExtendedASCII.byte2str=function byte2str(buff){var chars=new Array(buff.length);for(var i2=0;i2127){chars[i2]=ExtendedASCII.extendedChars[charCode-128]}else{chars[i2]=String.fromCharCode(charCode)}}return chars.join("")};ExtendedASCII.byteLength=function byteLength(str){return str.length};ExtendedASCII.extendedChars=["\xC7","\xFC","\xE9","\xE2","\xE4","\xE0","\xE5","\xE7","\xEA","\xEB","\xE8","\xEF","\xEE","\xEC","\xC4","\xC5","\xC9","\xE6","\xC6","\xF4","\xF6","\xF2","\xFB","\xF9","\xFF","\xD6","\xDC","\xF8","\xA3","\xD8","\xD7","\u0192","\xE1","\xED","\xF3","\xFA","\xF1","\xD1","\xAA","\xBA","\xBF","\xAE","\xAC","\xBD","\xBC","\xA1","\xAB","\xBB","_","_","_","\xA6","\xA6","\xC1","\xC2","\xC0","\xA9","\xA6","\xA6","+","+","\xA2","\xA5","+","+","-","-","+","-","+","\xE3","\xC3","+","+","-","-","\xA6","-","+","\xA4","\xF0","\xD0","\xCA","\xCB","\xC8","i","\xCD","\xCE","\xCF","+","+","_","_","\xA6","\xCC","_","\xD3","\xDF","\xD4","\xD2","\xF5","\xD5","\xB5","\xFE","\xDE","\xDA","\xDB","\xD9","\xFD","\xDD","\xAF","\xB4","\xAD","\xB1","_","\xBE","\xB6","\xA7","\xF7","\xB8","\xB0","\xA8","\xB7","\xB9","\xB3","\xB2","_"," "];var inflateRaw=__webpack_require__(31).inflateRaw;var decompressionMethods={};var ExternalFileAttributeType;(function(ExternalFileAttributeType2){ExternalFileAttributeType2[ExternalFileAttributeType2["MSDOS"]=0]="MSDOS";ExternalFileAttributeType2[ExternalFileAttributeType2["AMIGA"]=1]="AMIGA";ExternalFileAttributeType2[ExternalFileAttributeType2["OPENVMS"]=2]="OPENVMS";ExternalFileAttributeType2[ExternalFileAttributeType2["UNIX"]=3]="UNIX";ExternalFileAttributeType2[ExternalFileAttributeType2["VM_CMS"]=4]="VM_CMS";ExternalFileAttributeType2[ExternalFileAttributeType2["ATARI_ST"]=5]="ATARI_ST";ExternalFileAttributeType2[ExternalFileAttributeType2["OS2_HPFS"]=6]="OS2_HPFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MAC"]=7]="MAC";ExternalFileAttributeType2[ExternalFileAttributeType2["Z_SYSTEM"]=8]="Z_SYSTEM";ExternalFileAttributeType2[ExternalFileAttributeType2["CP_M"]=9]="CP_M";ExternalFileAttributeType2[ExternalFileAttributeType2["NTFS"]=10]="NTFS";ExternalFileAttributeType2[ExternalFileAttributeType2["MVS"]=11]="MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["VSE"]=12]="VSE";ExternalFileAttributeType2[ExternalFileAttributeType2["ACORN_RISC"]=13]="ACORN_RISC";ExternalFileAttributeType2[ExternalFileAttributeType2["VFAT"]=14]="VFAT";ExternalFileAttributeType2[ExternalFileAttributeType2["ALT_MVS"]=15]="ALT_MVS";ExternalFileAttributeType2[ExternalFileAttributeType2["BEOS"]=16]="BEOS";ExternalFileAttributeType2[ExternalFileAttributeType2["TANDEM"]=17]="TANDEM";ExternalFileAttributeType2[ExternalFileAttributeType2["OS_400"]=18]="OS_400";ExternalFileAttributeType2[ExternalFileAttributeType2["OSX"]=19]="OSX"})(ExternalFileAttributeType||(ExternalFileAttributeType={}));var CompressionMethod;(function(CompressionMethod2){CompressionMethod2[CompressionMethod2["STORED"]=0]="STORED";CompressionMethod2[CompressionMethod2["SHRUNK"]=1]="SHRUNK";CompressionMethod2[CompressionMethod2["REDUCED_1"]=2]="REDUCED_1";CompressionMethod2[CompressionMethod2["REDUCED_2"]=3]="REDUCED_2";CompressionMethod2[CompressionMethod2["REDUCED_3"]=4]="REDUCED_3";CompressionMethod2[CompressionMethod2["REDUCED_4"]=5]="REDUCED_4";CompressionMethod2[CompressionMethod2["IMPLODE"]=6]="IMPLODE";CompressionMethod2[CompressionMethod2["DEFLATE"]=8]="DEFLATE";CompressionMethod2[CompressionMethod2["DEFLATE64"]=9]="DEFLATE64";CompressionMethod2[CompressionMethod2["TERSE_OLD"]=10]="TERSE_OLD";CompressionMethod2[CompressionMethod2["BZIP2"]=12]="BZIP2";CompressionMethod2[CompressionMethod2["LZMA"]=14]="LZMA";CompressionMethod2[CompressionMethod2["TERSE_NEW"]=18]="TERSE_NEW";CompressionMethod2[CompressionMethod2["LZ77"]=19]="LZ77";CompressionMethod2[CompressionMethod2["WAVPACK"]=97]="WAVPACK";CompressionMethod2[CompressionMethod2["PPMD"]=98]="PPMD"})(CompressionMethod||(CompressionMethod={}));function msdos2date(time,date){var day=date&31;var month=(date>>5&15)-1;var year=(date>>9)+1980;var second=time&31;var minute=time>>5&63;var hour=time>>11;return new Date(year,month,day,hour,minute,second)}function safeToString(buff,useUTF8,start,length){if(length===0){return""}else if(useUTF8){return buff.toString("utf8",start,start+length)}else{return ExtendedASCII.byte2str(buff.slice(start,start+length))}}var FileHeader=function FileHeader2(data){this.data=data;if(data.readUInt32LE(0)!==67324752){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Local file header has invalid signature: "+this.data.readUInt32LE(0))}};FileHeader.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(4)};FileHeader.prototype.flags=function flags(){return this.data.readUInt16LE(6)};FileHeader.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(8)};FileHeader.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(10),this.data.readUInt16LE(12))};FileHeader.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(10)};FileHeader.prototype.crc32=function crc32(){return this.data.readUInt32LE(14)};FileHeader.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(26)};FileHeader.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(28)};FileHeader.prototype.fileName=function fileName(){return safeToString(this.data,this.useUTF8(),30,this.fileNameLength())};FileHeader.prototype.extraField=function extraField(){var start=30+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};FileHeader.prototype.totalSize=function totalSize(){return 30+this.fileNameLength()+this.extraFieldLength()};FileHeader.prototype.useUTF8=function useUTF8(){return(this.flags()&2048)===2048};var FileData=function FileData2(header,record,data){this.header=header;this.record=record;this.data=data};FileData.prototype.decompress=function decompress(){var compressionMethod=this.header.compressionMethod();var fcn=decompressionMethods[compressionMethod];if(fcn){return fcn(this.data,this.record.compressedSize(),this.record.uncompressedSize(),this.record.flag())}else{var name=CompressionMethod[compressionMethod];if(!name){name="Unknown: "+compressionMethod}throw new ApiError(ErrorCode.EINVAL,"Invalid compression method on file '"+this.header.fileName()+"': "+name)}};FileData.prototype.getHeader=function getHeader(){return this.header};FileData.prototype.getRecord=function getRecord(){return this.record};FileData.prototype.getRawData=function getRawData(){return this.data};var DataDescriptor=function DataDescriptor2(data){this.data=data};DataDescriptor.prototype.crc32=function crc32(){return this.data.readUInt32LE(0)};DataDescriptor.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(4)};DataDescriptor.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(8)};var ArchiveExtraDataRecord=function ArchiveExtraDataRecord2(data){this.data=data;if(this.data.readUInt32LE(0)!==134630224){throw new ApiError(ErrorCode.EINVAL,"Invalid archive extra data record signature: "+this.data.readUInt32LE(0))}};ArchiveExtraDataRecord.prototype.length=function length(){return this.data.readUInt32LE(4)};ArchiveExtraDataRecord.prototype.extraFieldData=function extraFieldData(){return this.data.slice(8,8+this.length())};var DigitalSignature=function DigitalSignature2(data){this.data=data;if(this.data.readUInt32LE(0)!==84233040){throw new ApiError(ErrorCode.EINVAL,"Invalid digital signature signature: "+this.data.readUInt32LE(0))}};DigitalSignature.prototype.size=function size(){return this.data.readUInt16LE(4)};DigitalSignature.prototype.signatureData=function signatureData(){return this.data.slice(6,6+this.size())};var CentralDirectory=function CentralDirectory2(zipData,data){this.zipData=zipData;this.data=data;if(this.data.readUInt32LE(0)!==33639248){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: Central directory record has invalid signature: "+this.data.readUInt32LE(0))}this._filename=this.produceFilename()};CentralDirectory.prototype.versionMadeBy=function versionMadeBy(){return this.data.readUInt16LE(4)};CentralDirectory.prototype.versionNeeded=function versionNeeded(){return this.data.readUInt16LE(6)};CentralDirectory.prototype.flag=function flag(){return this.data.readUInt16LE(8)};CentralDirectory.prototype.compressionMethod=function compressionMethod(){return this.data.readUInt16LE(10)};CentralDirectory.prototype.lastModFileTime=function lastModFileTime(){return msdos2date(this.data.readUInt16LE(12),this.data.readUInt16LE(14))};CentralDirectory.prototype.rawLastModFileTime=function rawLastModFileTime(){return this.data.readUInt32LE(12)};CentralDirectory.prototype.crc32=function crc32(){return this.data.readUInt32LE(16)};CentralDirectory.prototype.compressedSize=function compressedSize(){return this.data.readUInt32LE(20)};CentralDirectory.prototype.uncompressedSize=function uncompressedSize(){return this.data.readUInt32LE(24)};CentralDirectory.prototype.fileNameLength=function fileNameLength(){return this.data.readUInt16LE(28)};CentralDirectory.prototype.extraFieldLength=function extraFieldLength(){return this.data.readUInt16LE(30)};CentralDirectory.prototype.fileCommentLength=function fileCommentLength(){return this.data.readUInt16LE(32)};CentralDirectory.prototype.diskNumberStart=function diskNumberStart(){return this.data.readUInt16LE(34)};CentralDirectory.prototype.internalAttributes=function internalAttributes(){return this.data.readUInt16LE(36)};CentralDirectory.prototype.externalAttributes=function externalAttributes(){return this.data.readUInt32LE(38)};CentralDirectory.prototype.headerRelativeOffset=function headerRelativeOffset(){return this.data.readUInt32LE(42)};CentralDirectory.prototype.produceFilename=function produceFilename(){var fileName=safeToString(this.data,this.useUTF8(),46,this.fileNameLength());return fileName.replace(/\\/g,"/")};CentralDirectory.prototype.fileName=function fileName(){return this._filename};CentralDirectory.prototype.rawFileName=function rawFileName(){return this.data.slice(46,46+this.fileNameLength())};CentralDirectory.prototype.extraField=function extraField(){var start=44+this.fileNameLength();return this.data.slice(start,start+this.extraFieldLength())};CentralDirectory.prototype.fileComment=function fileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return safeToString(this.data,this.useUTF8(),start,this.fileCommentLength())};CentralDirectory.prototype.rawFileComment=function rawFileComment(){var start=46+this.fileNameLength()+this.extraFieldLength();return this.data.slice(start,start+this.fileCommentLength())};CentralDirectory.prototype.totalSize=function totalSize(){return 46+this.fileNameLength()+this.extraFieldLength()+this.fileCommentLength()};CentralDirectory.prototype.isDirectory=function isDirectory(){var fileName=this.fileName();return(this.externalAttributes()&16?true:false)||fileName.charAt(fileName.length-1)==="/"};CentralDirectory.prototype.isFile=function isFile(){return!this.isDirectory()};CentralDirectory.prototype.useUTF8=function useUTF8(){return(this.flag()&2048)===2048};CentralDirectory.prototype.isEncrypted=function isEncrypted(){return(this.flag()&1)===1};CentralDirectory.prototype.getFileData=function getFileData(){var start=this.headerRelativeOffset();var header=new FileHeader(this.zipData.slice(start));return new FileData(header,this,this.zipData.slice(start+header.totalSize()))};CentralDirectory.prototype.getData=function getData(){return this.getFileData().decompress()};CentralDirectory.prototype.getRawData=function getRawData(){return this.getFileData().getRawData()};CentralDirectory.prototype.getStats=function getStats(){return new Stats(FileType.FILE,this.uncompressedSize(),365,new Date,this.lastModFileTime())};var EndOfCentralDirectory=function EndOfCentralDirectory2(data){this.data=data;if(this.data.readUInt32LE(0)!==101010256){throw new ApiError(ErrorCode.EINVAL,"Invalid Zip file: End of central directory record has invalid signature: "+this.data.readUInt32LE(0))}};EndOfCentralDirectory.prototype.diskNumber=function diskNumber(){return this.data.readUInt16LE(4)};EndOfCentralDirectory.prototype.cdDiskNumber=function cdDiskNumber(){return this.data.readUInt16LE(6)};EndOfCentralDirectory.prototype.cdDiskEntryCount=function cdDiskEntryCount(){return this.data.readUInt16LE(8)};EndOfCentralDirectory.prototype.cdTotalEntryCount=function cdTotalEntryCount(){return this.data.readUInt16LE(10)};EndOfCentralDirectory.prototype.cdSize=function cdSize(){return this.data.readUInt32LE(12)};EndOfCentralDirectory.prototype.cdOffset=function cdOffset(){return this.data.readUInt32LE(16)};EndOfCentralDirectory.prototype.cdZipCommentLength=function cdZipCommentLength(){return this.data.readUInt16LE(20)};EndOfCentralDirectory.prototype.cdZipComment=function cdZipComment(){return safeToString(this.data,true,22,this.cdZipCommentLength())};EndOfCentralDirectory.prototype.rawCdZipComment=function rawCdZipComment(){return this.data.slice(22,22+this.cdZipCommentLength())};var ZipTOC=function ZipTOC2(index,directoryEntries,eocd,data){this.index=index;this.directoryEntries=directoryEntries;this.eocd=eocd;this.data=data};var ZipFS=function(SynchronousFileSystem$$1){function ZipFS2(input,name,deprecateMsg){if(name===void 0)name="";if(deprecateMsg===void 0)deprecateMsg=true;SynchronousFileSystem$$1.call(this);this.name=name;this._index=new FileIndex;this._directoryEntries=[];this._eocd=null;deprecationMessage(deprecateMsg,ZipFS2.Name,{zipData:"zip data as a Buffer",name});if(input instanceof ZipTOC){this._index=input.index;this._directoryEntries=input.directoryEntries;this._eocd=input.eocd;this.data=input.data}else{this.data=input;this.populateIndex()}}if(SynchronousFileSystem$$1)ZipFS2.__proto__=SynchronousFileSystem$$1;ZipFS2.prototype=Object.create(SynchronousFileSystem$$1&&SynchronousFileSystem$$1.prototype);ZipFS2.prototype.constructor=ZipFS2;ZipFS2.Create=function Create(opts,cb){try{ZipFS2.computeIndex(opts.zipData,function(zipTOC){var fs4=new ZipFS2(zipTOC,opts.name,false);cb(null,fs4)},false)}catch(e){cb(e)}};ZipFS2.isAvailable=function isAvailable(){return true};ZipFS2.RegisterDecompressionMethod=function RegisterDecompressionMethod(m,fcn){decompressionMethods[m]=fcn};ZipFS2.computeIndex=function computeIndex(data,cb,deprecateMsg){if(deprecateMsg===void 0)deprecateMsg=true;if(deprecateMsg){console.warn("[ZipFS] ZipFS.computeIndex is now deprecated, and will be removed in the next major release. Please update your code to use 'ZipFS.Create({ zipData: zip file as a Buffer}, cb)' instead.")}var index=new FileIndex;var eocd=ZipFS2.getEOCD(data);if(eocd.diskNumber()!==eocd.cdDiskNumber()){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support spanned zip files.")}var cdPtr=eocd.cdOffset();if(cdPtr===4294967295){throw new ApiError(ErrorCode.EINVAL,"ZipFS does not support Zip64.")}var cdEnd=cdPtr+eocd.cdSize();ZipFS2.computeIndexResponsive(data,index,cdPtr,cdEnd,cb,[],eocd)};ZipFS2.getEOCD=function getEOCD(data){var startOffset=22;var endOffset=Math.min(startOffset+65535,data.length-1);for(var i2=startOffset;i2-1};DirectoryRecord.prototype.getRockRidgeOffset=function getRockRidgeOffset(){return this._rockRidgeOffset};DirectoryRecord.prototype.rootCheckForRockRidge=function rootCheckForRockRidge(isoData){var dir=this.getDirectory(isoData);this._rockRidgeOffset=dir.getDotEntry(isoData)._getRockRidgeOffset(isoData);if(this._rockRidgeOffset>-1){this._fileOrDir=null}};DirectoryRecord.prototype.length=function length(){return this._data[0]};DirectoryRecord.prototype.extendedAttributeRecordLength=function extendedAttributeRecordLength(){return this._data[1]};DirectoryRecord.prototype.lba=function lba(){return this._data.readUInt32LE(2)*2048};DirectoryRecord.prototype.dataLength=function dataLength(){return this._data.readUInt32LE(10)};DirectoryRecord.prototype.recordingDate=function recordingDate(){return getShortFormDate(this._data,18)};DirectoryRecord.prototype.fileFlags=function fileFlags(){return this._data[25]};DirectoryRecord.prototype.fileUnitSize=function fileUnitSize(){return this._data[26]};DirectoryRecord.prototype.interleaveGapSize=function interleaveGapSize(){return this._data[27]};DirectoryRecord.prototype.volumeSequenceNumber=function volumeSequenceNumber(){return this._data.readUInt16LE(28)};DirectoryRecord.prototype.identifier=function identifier(){return this._getString(33,this._data[32])};DirectoryRecord.prototype.fileName=function fileName(isoData){if(this.hasRockRidge()){var fn=this._rockRidgeFilename(isoData);if(fn!==null){return fn}}var ident=this.identifier();if(this.isDirectory(isoData)){return ident}var versionSeparator=ident.indexOf(";");if(versionSeparator===-1){return ident}else if(ident[versionSeparator-1]==="."){return ident.slice(0,versionSeparator-1)}else{return ident.slice(0,versionSeparator)}};DirectoryRecord.prototype.isDirectory=function isDirectory(isoData){var rv=!!(this.fileFlags()&2);if(!rv&&this.hasRockRidge()){rv=this.getSUEntries(isoData).filter(function(e){return e instanceof CLEntry}).length>0}return rv};DirectoryRecord.prototype.isSymlink=function isSymlink(isoData){return this.hasRockRidge()&&this.getSUEntries(isoData).filter(function(e){return e instanceof SLEntry}).length>0};DirectoryRecord.prototype.getSymlinkPath=function getSymlinkPath(isoData){var p="";var entries=this.getSUEntries(isoData);var getStr=this._getGetString();for(var i2=0,list2=entries;i21&&p[p.length-1]==="/"){return p.slice(0,p.length-1)}else{return p}};DirectoryRecord.prototype.getFile=function getFile(isoData){if(this.isDirectory(isoData)){throw new Error("Tried to get a File from a directory.")}if(this._fileOrDir===null){this._fileOrDir=isoData.slice(this.lba(),this.lba()+this.dataLength())}return this._fileOrDir};DirectoryRecord.prototype.getDirectory=function getDirectory(isoData){if(!this.isDirectory(isoData)){throw new Error("Tried to get a Directory from a file.")}if(this._fileOrDir===null){this._fileOrDir=this._constructDirectory(isoData)}return this._fileOrDir};DirectoryRecord.prototype.getSUEntries=function getSUEntries(isoData){if(!this._suEntries){this._constructSUEntries(isoData)}return this._suEntries};DirectoryRecord.prototype._rockRidgeFilename=function _rockRidgeFilename(isoData){var nmEntries=this.getSUEntries(isoData).filter(function(e2){return e2 instanceof NMEntry});if(nmEntries.length===0||nmEntries[0].flags()&(2|4)){return null}var str="";var getString=this._getGetString();for(var i2=0,list2=nmEntries;i20){var spEntry=suEntries[0];if(spEntry instanceof SPEntry&&spEntry.checkBytesPass()){for(var i2=1;i2K_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer2.prototype;return buf}function Buffer2(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new Error("If encoding is specified then the first argument must be a string")}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer2[Symbol.species]===Buffer2){Object.defineProperty(Buffer2,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer2.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer2.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer2.prototype.__proto__=Uint8Array.prototype;Buffer2.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be a number')}else if(size<0){throw new RangeError('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==void 0){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer2.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer2.allocUnsafe=function(size){return allocUnsafe(size)};Buffer2.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer2.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding')}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer2.alloc(+length)}Buffer2.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};Buffer2.compare=function compare(a,b){if(!Buffer2.isBuffer(a)||!Buffer2.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer2.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===void 0||start<0){start=0}if(start>this.length){return""}if(end===void 0||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer2.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer2.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer2.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer2.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===void 0){start=0}if(end===void 0){end=target?target.length:0}if(thisStart===void 0){thisStart=0}if(thisEnd===void 0){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer2.from(val,encoding)}if(Buffer2.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==void 0){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i2){if(indexSize===1){return buf[i2]}else{return buf.readUInt16BE(i2*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===void 0)encoding="utf8"}else{encoding=length;length=void 0}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===void 0||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer2.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer2.prototype.readUIntLE=function readUIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){checkOffset(offset,byteLength2,this.length)}var val=this[offset+--byteLength2];var mul=1;while(byteLength2>0&&(mul*=256)){val+=this[offset+--byteLength2]*mul}return val};Buffer2.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer2.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer2.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer2.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer2.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer2.prototype.readIntLE=function readIntLE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readIntBE=function readIntBE(offset,byteLength2,noAssert){offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert)checkOffset(offset,byteLength2,this.length);var i=byteLength2;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength2);return val};Buffer2.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer2.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer2.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer2.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer2.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer2.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer2.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer2.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer2.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer2.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength2=byteLength2>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength2)-1;checkInt(this,value,offset,byteLength2,maxBytes,0)}var i=byteLength2-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength2};Buffer2.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer2.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer2.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer2.prototype.writeIntLE=function writeIntLE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeIntBE=function writeIntBE(value,offset,byteLength2,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength2-1);checkInt(this,value,offset,byteLength2,limit-1,-limit)}var i=byteLength2-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength2};Buffer2.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer2.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer2.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer2.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer2.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer2.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer2.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer2.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer2.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer2.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3){for(i=0;i>>0;end=end===void 0?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function isArrayBufferView(obj){return typeof ArrayBuffer.isView==="function"&&ArrayBuffer.isView(obj)}function numberIsNaN(obj){return obj!==obj}}).call(exports2,__webpack_require__(1))},function(module2,exports2){"use strict";exports2.byteLength=byteLength;exports2.toByteArray=toByteArray;exports2.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len2-2]==="="?2:b64[len2-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i2,j,l,tmp,placeHolders,arr;var len2=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len2*3/4-placeHolders);l=placeHolders>0?len2-4:len2;var L=0;for(i2=0,j=0;i2>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i2=start;i2len22?len22:i2+maxChunkLength))}if(extraBytes===1){tmp=uint8[len2-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len2-2]<<8)+uint8[len2-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},function(module2,exports2){exports2.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports2.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},function(module2,exports2){module2.exports=function(module3){if(!module3.webpackPolyfill){module3.deprecate=function(){};module3.paths=[];module3.children=[];module3.webpackPolyfill=1}return module3}},function(module2,exports2,__webpack_require__){"use strict";var Process=__webpack_require__(7);var process=new Process,processProxy={};function defineKey(key2){if(processProxy[key2]){return}if(typeof process[key2]==="function"){processProxy[key2]=function(){return process[key2].apply(process,arguments)}}else{processProxy[key2]=process[key2]}}for(var key in process){defineKey(key)}processProxy.initializeTTYs=function(){if(process.stdin===null){process.initializeTTYs();processProxy.stdin=process.stdin;processProxy.stdout=process.stdout;processProxy.stderr=process.stderr}};process.nextTick(function(){processProxy.initializeTTYs()});module2.exports=processProxy},function(module2,exports2,__webpack_require__){(function(__dirname){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var events=__webpack_require__(8);var path=null;var Item=function(){function Item2(fun,array){this.fun=fun;this.array=array}Item2.prototype.run=function(){this.fun.apply(null,this.array)};return Item2}();var NextTickQueue=function(){function NextTickQueue2(){this._queue=[];this._draining=false;this._currentQueue=null;this._queueIndex=-1}NextTickQueue2.prototype.push=function(item){var _this=this;if(this._queue.push(item)===1&&!this._draining){setTimeout(function(){return _this._drainQueue()},0)}};NextTickQueue2.prototype._cleanUpNextTick=function(){this._draining=false;if(this._currentQueue&&this._currentQueue.length){this._queue=this._currentQueue.concat(this._queue)}else{this._queueIndex=-1}if(this._queue.length){this._drainQueue()}};NextTickQueue2.prototype._drainQueue=function(){var _this=this;if(this._draining){return}var timeout=setTimeout(function(){return _this._cleanUpNextTick()});this._draining=true;var len=this._queue.length;while(len){this._currentQueue=this._queue;this._queue=[];while(++this._queueIndex0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},function(module2,exports2,__webpack_require__){(function(process){"use strict";var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;function posixSplitPath(filename){var out=splitPathRe.exec(filename);out.shift();return out}var path=function(){function path2(){}path2.normalize=function(p){if(p===""){p="."}var absolute=p.charAt(0)===path2.sep;p=path2._removeDuplicateSeps(p);var components=p.split(path2.sep);var goodComponents=[];for(var idx=0;idx0&&goodComponents[0]!=="..")){goodComponents.pop()}else{goodComponents.push(c)}}if(!absolute&&goodComponents.length<2){switch(goodComponents.length){case 1:if(goodComponents[0]===""){goodComponents.unshift(".")}break;default:goodComponents.push(".")}}p=goodComponents.join(path2.sep);if(absolute&&p.charAt(0)!==path2.sep){p=path2.sep+p}return p};path2.join=function(){var paths=[];for(var _i=0;_i1&&resolved.charAt(resolved.length-1)===path2.sep){return resolved.substr(0,resolved.length-1)}if(resolved.charAt(0)!==path2.sep){if(resolved.charAt(0)==="."&&(resolved.length===1||resolved.charAt(1)===path2.sep)){resolved=resolved.length===1?"":resolved.substr(2)}var cwd=process.cwd();if(resolved!==""){resolved=this.normalize(cwd+(cwd!=="/"?path2.sep:"")+resolved)}else{resolved=cwd}}return resolved};path2.relative=function(from,to){var i;from=path2.resolve(from);to=path2.resolve(to);var fromSegs=from.split(path2.sep);var toSegs=to.split(path2.sep);toSegs.shift();fromSegs.shift();var upCount=0;var downSegs=[];for(i=0;ifromSegs.length){upCount=fromSegs.length}var rv="";for(i=0;i1&&rv.charAt(rv.length-1)===path2.sep){rv=rv.substr(0,rv.length-1)}return rv};path2.dirname=function(p){p=path2._removeDuplicateSeps(p);var absolute=p.charAt(0)===path2.sep;var sections=p.split(path2.sep);if(sections.pop()===""&§ions.length>0){sections.pop()}if(sections.length>1||sections.length===1&&!absolute){return sections.join(path2.sep)}else if(absolute){return path2.sep}else{return"."}};path2.basename=function(p,ext){if(ext===void 0){ext=""}if(p===""){return p}p=path2.normalize(p);var sections=p.split(path2.sep);var lastPart=sections[sections.length-1];if(lastPart===""&§ions.length>1){return sections[sections.length-2]}if(ext.length>0){var lastPartExt=lastPart.substr(lastPart.length-ext.length);if(lastPartExt===ext){return lastPart.substr(0,lastPart.length-ext.length)}}return lastPart};path2.extname=function(p){p=path2.normalize(p);var sections=p.split(path2.sep);p=sections.pop();if(p===""&§ions.length>0){p=sections.pop()}if(p===".."){return""}var i=p.lastIndexOf(".");if(i===-1||i===0){return""}return p.substr(i)};path2.isAbsolute=function(p){return p.length>0&&p.charAt(0)===path2.sep};path2._makeLong=function(p){return p};path2.parse=function(p){var allParts=posixSplitPath(p);return{root:allParts[0],dir:allParts[0]+allParts[1].slice(0,-1),base:allParts[2],ext:allParts[3],name:allParts[2].slice(0,allParts[2].length-allParts[3].length)}};path2.format=function(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError("Parameter 'pathObject' must be an object, not "+typeof pathObject)}var root=pathObject.root||"";if(typeof root!=="string"){throw new TypeError("'pathObject.root' must be a string or undefined, not "+typeof pathObject.root)}var dir=pathObject.dir?pathObject.dir+path2.sep:"";var base=pathObject.base||"";return dir+base};path2._removeDuplicateSeps=function(p){p=p.replace(this._replaceRegex,this.sep);return p};path2.sep="/";path2._replaceRegex=new RegExp("//+","g");path2.delimiter=":";path2.posix=path2;path2.win32=path2;return path2}();var _=path;module2.exports=path}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(Buffer2){"use strict";var __extends=this&&this.__extends||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)};var stream=__webpack_require__(11);var TTY=function(_super){__extends(TTY2,_super);function TTY2(){_super.call(this);this.isRaw=false;this.columns=80;this.rows=120;this.isTTY=true;this._bufferedWrites=[];this._waitingForWrites=false}TTY2.prototype.setRawMode=function(mode){if(this.isRaw!==mode){this.isRaw=mode;this.emit("modeChange")}};TTY2.prototype.changeColumns=function(columns){if(columns!==this.columns){this.columns=columns;this.emit("resize")}};TTY2.prototype.changeRows=function(rows){if(rows!==this.rows){this.rows=rows;this.emit("resize")}};TTY2.isatty=function(fd){return fd&&fd instanceof TTY2};TTY2.prototype._write=function(chunk,encoding,cb){var error;try{var data;if(typeof chunk==="string"){data=new Buffer2(chunk,encoding)}else{data=chunk}this._bufferedWrites.push(data);if(this._waitingForWrites){this._read(1024)}}catch(e){error=e}finally{cb(error)}};TTY2.prototype._read=function(size){if(this._bufferedWrites.length===0){this._waitingForWrites=true}else{while(this._bufferedWrites.length>0){this._waitingForWrites=this.push(this._bufferedWrites.shift());if(!this._waitingForWrites){break}}}};return TTY2}(stream.Duplex);module2.exports=TTY}).call(exports2,__webpack_require__(1))},function(module2,exports2,__webpack_require__){module2.exports=Stream;var EE=__webpack_require__(8).EventEmitter;var inherits=__webpack_require__(12);inherits(Stream,EE);Stream.Readable=__webpack_require__(13);Stream.Writable=__webpack_require__(27);Stream.Duplex=__webpack_require__(28);Stream.Transform=__webpack_require__(29);Stream.PassThrough=__webpack_require__(30);Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},function(module2,exports2){if(typeof Object.create==="function"){module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module2.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},function(module2,exports2,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(11)}catch(_){}}();exports2=module2.exports=__webpack_require__(14);exports2.Stream=Stream||exports2;exports2.Readable=exports2;exports2.Writable=__webpack_require__(22);exports2.Duplex=__webpack_require__(21);exports2.Transform=__webpack_require__(25);exports2.PassThrough=__webpack_require__(26);if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module2.exports=Stream}}).call(exports2,__webpack_require__(6))},function(module2,exports2,__webpack_require__){(function(process){"use strict";module2.exports=Readable;var processNextTick=__webpack_require__(15);var isArray=__webpack_require__(16);var Duplex;Readable.ReadableState=ReadableState;var EE=__webpack_require__(8).EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var debugUtil=__webpack_require__(19);var debug=void 0;if(debugUtil&&debugUtil.debuglog){debug=debugUtil.debuglog("stream")}else{debug=function(){}}var BufferList=__webpack_require__(20);var StringDecoder;util.inherits(Readable,Stream);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=__webpack_require__(24).StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){Duplex=Duplex||__webpack_require__(21);if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=bufferShim.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer2.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;iMAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===void 0){enc=void 0;_fill=0}var buf=new Buffer2(size);if(typeof _fill==="string"){var fillBuf=new Buffer2(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer2(size)};exports2.from=function from(value,encodingOrOffset,length){if(typeof Buffer2.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer2.from)){return Buffer2.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer2(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer2(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer2(value.slice(offset,offset+len))}if(Buffer2.isBuffer(value)){var out=new Buffer2(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer2(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer2(value.data)}}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")};exports2.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer2.allocUnsafeSlow==="function"){return Buffer2.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(exports2,function(){return this}())},function(module2,exports2,__webpack_require__){(function(Buffer2){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports2.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports2.isBoolean=isBoolean;function isNull(arg){return arg===null}exports2.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports2.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports2.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports2.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports2.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports2.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports2.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports2.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports2.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports2.isError=isError;function isFunction(arg){return typeof arg==="function"}exports2.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports2.isPrimitive=isPrimitive;exports2.isBuffer=Buffer2.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(exports2,__webpack_require__(1))},function(module2,exports2){},function(module2,exports2,__webpack_require__){"use strict";var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);module2.exports=BufferList;function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},function(module2,exports2,__webpack_require__){"use strict";var objectKeys=Object.keys||function(obj){var keys2=[];for(var key in obj){keys2.push(key)}return keys2};module2.exports=Duplex;var processNextTick=__webpack_require__(15);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var Readable=__webpack_require__(14);var Writable=__webpack_require__(22);util.inherits(Duplex,Readable);var keys=objectKeys(Writable.prototype);for(var v=0;v-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=__webpack_require__(18);util.inherits=__webpack_require__(12);var internalUtil={deprecate:__webpack_require__(23)};var Stream;(function(){try{Stream=__webpack_require__(11)}catch(_){}finally{if(!Stream)Stream=__webpack_require__(8).EventEmitter}})();var Buffer2=__webpack_require__(2).Buffer;var bufferShim=__webpack_require__(17);util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}function WritableState(options,stream){Duplex=Duplex||__webpack_require__(21);options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||__webpack_require__(21);if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==void 0&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=Buffer2.isBuffer(chunk);if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){chunk=decodeChunk(state,chunk,encoding);if(Buffer2.isBuffer(chunk))encoding="buffer"}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},function(module2,exports2,__webpack_require__){"use strict";module2.exports=Transform;var Duplex=__webpack_require__(21);var util=__webpack_require__(18);util.inherits=__webpack_require__(12);util.inherits(Transform,Duplex);function TransformState(stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null;this.writeencoding=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==void 0)stream.push(data);cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length=0&&opt.windowBits<16){opt.windowBits=-opt.windowBits;if(opt.windowBits===0){opt.windowBits=-15}}if(opt.windowBits>=0&&opt.windowBits<16&&!(options&&options.windowBits)){opt.windowBits+=32}if(opt.windowBits>15&&opt.windowBits<48){if((opt.windowBits&15)===0){opt.windowBits|=15}}this.err=0;this.msg="";this.ended=false;this.chunks=[];this.strm=new ZStream;this.strm.avail_out=0;var status=zlib_inflate.inflateInit2(this.strm,opt.windowBits);if(status!==c.Z_OK){throw new Error(msg[status])}this.header=new GZheader;zlib_inflate.inflateGetHeader(this.strm,this.header)}Inflate.prototype.push=function(data,mode){var strm=this.strm;var chunkSize=this.options.chunkSize;var dictionary=this.options.dictionary;var status,_mode;var next_out_utf8,tail,utf8str;var dict;var allowBufError=false;if(this.ended){return false}_mode=mode===~~mode?mode:mode===true?c.Z_FINISH:c.Z_NO_FLUSH;if(typeof data==="string"){strm.input=strings.binstring2buf(data)}else if(toString.call(data)==="[object ArrayBuffer]"){strm.input=new Uint8Array(data)}else{strm.input=data}strm.next_in=0;strm.avail_in=strm.input.length;do{if(strm.avail_out===0){strm.output=new utils.Buf8(chunkSize);strm.next_out=0;strm.avail_out=chunkSize}status=zlib_inflate.inflate(strm,c.Z_NO_FLUSH);if(status===c.Z_NEED_DICT&&dictionary){if(typeof dictionary==="string"){dict=strings.string2buf(dictionary)}else if(toString.call(dictionary)==="[object ArrayBuffer]"){dict=new Uint8Array(dictionary)}else{dict=dictionary}status=zlib_inflate.inflateSetDictionary(this.strm,dict)}if(status===c.Z_BUF_ERROR&&allowBufError===true){status=c.Z_OK;allowBufError=false}if(status!==c.Z_STREAM_END&&status!==c.Z_OK){this.onEnd(status);this.ended=true;return false}if(strm.next_out){if(strm.avail_out===0||status===c.Z_STREAM_END||strm.avail_in===0&&(_mode===c.Z_FINISH||_mode===c.Z_SYNC_FLUSH)){if(this.options.to==="string"){next_out_utf8=strings.utf8border(strm.output,strm.next_out);tail=strm.next_out-next_out_utf8;utf8str=strings.buf2string(strm.output,next_out_utf8);strm.next_out=tail;strm.avail_out=chunkSize-tail;if(tail){utils.arraySet(strm.output,strm.output,next_out_utf8,tail,0)}this.onData(utf8str)}else{this.onData(utils.shrinkBuf(strm.output,strm.next_out))}}}if(strm.avail_in===0&&strm.avail_out===0){allowBufError=true}}while((strm.avail_in>0||strm.avail_out===0)&&status!==c.Z_STREAM_END);if(status===c.Z_STREAM_END){_mode=c.Z_FINISH}if(_mode===c.Z_FINISH){status=zlib_inflate.inflateEnd(this.strm);this.onEnd(status);this.ended=true;return status===c.Z_OK}if(_mode===c.Z_SYNC_FLUSH){this.onEnd(c.Z_OK);strm.avail_out=0;return true}return true};Inflate.prototype.onData=function(chunk){this.chunks.push(chunk)};Inflate.prototype.onEnd=function(status){if(status===c.Z_OK){if(this.options.to==="string"){this.result=this.chunks.join("")}else{this.result=utils.flattenChunks(this.chunks)}}this.chunks=[];this.err=status;this.msg=this.strm.msg};function inflate(input,options){var inflator=new Inflate(options);inflator.push(input,true);if(inflator.err){throw inflator.msg||msg[inflator.err]}return inflator.result}function inflateRaw(input,options){options=options||{};options.raw=true;return inflate(input,options)}exports2.Inflate=Inflate;exports2.inflate=inflate;exports2.inflateRaw=inflateRaw;exports2.ungzip=inflate},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var adler32=__webpack_require__(34);var crc32=__webpack_require__(35);var inflate_fast=__webpack_require__(36);var inflate_table=__webpack_require__(37);var CODES=0;var LENS=1;var DISTS=2;var Z_FINISH=4;var Z_BLOCK=5;var Z_TREES=6;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_MEM_ERROR=-4;var Z_BUF_ERROR=-5;var Z_DEFLATED=8;var HEAD=1;var FLAGS=2;var TIME=3;var OS=4;var EXLEN=5;var EXTRA=6;var NAME=7;var COMMENT=8;var HCRC=9;var DICTID=10;var DICT=11;var TYPE=12;var TYPEDO=13;var STORED=14;var COPY_=15;var COPY=16;var TABLE=17;var LENLENS=18;var CODELENS=19;var LEN_=20;var LEN=21;var LENEXT=22;var DIST=23;var DISTEXT=24;var MATCH=25;var LIT=26;var CHECK=27;var LENGTH=28;var DONE=29;var BAD=30;var MEM=31;var SYNC=32;var ENOUGH_LENS=852;var ENOUGH_DISTS=592;var MAX_WBITS=15;var DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0;this.last=false;this.wrap=0;this.havedict=false;this.flags=0;this.dmax=0;this.check=0;this.total=0;this.head=null;this.wbits=0;this.wsize=0;this.whave=0;this.wnext=0;this.window=null;this.hold=0;this.bits=0;this.length=0;this.offset=0;this.extra=0;this.lencode=null;this.distcode=null;this.lenbits=0;this.distbits=0;this.ncode=0;this.nlen=0;this.ndist=0;this.have=0;this.next=null;this.lens=new utils.Buf16(320);this.work=new utils.Buf16(288);this.lendyn=null;this.distdyn=null;this.sane=0;this.back=0;this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;strm.total_in=strm.total_out=state.total=0;strm.msg="";if(state.wrap){strm.adler=state.wrap&1}state.mode=HEAD;state.last=0;state.havedict=0;state.dmax=32768;state.head=null;state.hold=0;state.bits=0;state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS);state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS);state.sane=1;state.back=-1;return Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;state.wsize=0;state.whave=0;state.wnext=0;return inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap;var state;if(!strm||!strm.state){return Z_STREAM_ERROR}state=strm.state;if(windowBits<0){wrap=0;windowBits=-windowBits}else{wrap=(windowBits>>4)+1;if(windowBits<48){windowBits&=15}}if(windowBits&&(windowBits<8||windowBits>15)){return Z_STREAM_ERROR}if(state.window!==null&&state.wbits!==windowBits){state.window=null}state.wrap=wrap;state.wbits=windowBits;return inflateReset(strm)}function inflateInit2(strm,windowBits){var ret;var state;if(!strm){return Z_STREAM_ERROR}state=new InflateState;strm.state=state;state.window=null;ret=inflateReset2(strm,windowBits);if(ret!==Z_OK){strm.state=null}return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=true;var lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512);distfix=new utils.Buf32(32);sym=0;while(sym<144){state.lens[sym++]=8}while(sym<256){state.lens[sym++]=9}while(sym<280){state.lens[sym++]=7}while(sym<288){state.lens[sym++]=8}inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9});sym=0;while(sym<32){state.lens[sym++]=5}inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5});virgin=false}state.lencode=lenfix;state.lenbits=9;state.distcode=distfix;state.distbits=5}function updatewindow(strm,src,end,copy){var dist;var state=strm.state;if(state.window===null){state.wsize=1<=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize}else{dist=state.wsize-state.wnext;if(dist>copy){dist=copy}utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize}else{state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0}if(state.whave>>8&255;state.check=crc32(state.check,hbuf,2,0);hold=0;bits=0;state.mode=FLAGS;break}state.flags=0;if(state.head){state.head.done=false}if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg="incorrect header check";state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg="unknown compression method";state.mode=BAD;break}hold>>>=4;bits-=4;len=(hold&15)+8;if(state.wbits===0){state.wbits=len}else if(len>state.wbits){strm.msg="invalid window size";state.mode=BAD;break}state.dmax=1<>8&1}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=TIME;case TIME:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;hbuf[2]=hold>>>16&255;hbuf[3]=hold>>>24&255;state.check=crc32(state.check,hbuf,4,0)}hold=0;bits=0;state.mode=OS;case OS:while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>8}if(state.flags&512){hbuf[0]=hold&255;hbuf[1]=hold>>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0;state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0){break inf_leave}have--;hold+=input[next++]<>>8&255;state.check=crc32(state.check,hbuf,2,0)}hold=0;bits=0}else if(state.head){state.head.extra=null}state.mode=EXTRA;case EXTRA:if(state.flags&1024){copy=state.length;if(copy>have){copy=have}if(copy){if(state.head){len=state.head.extra_len-state.length;if(!state.head.extra){state.head.extra=new Array(state.head.extra_len)}utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512){state.check=crc32(state.check,input,copy,next)}have-=copy;next+=copy;state.length-=copy}if(state.length){break inf_leave}}state.length=0;state.mode=NAME;case NAME:if(state.flags&2048){if(have===0){break inf_leave}copy=0;do{len=input[next+copy++];if(state.head&&len&&state.length<65536){state.head.name+=String.fromCharCode(len)}}while(len&©>9&1;state.head.done=true}strm.adler=state.check=0;state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=bits&7;bits-=bits&7;state.mode=CHECK;break}while(bits<3){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=1;bits-=1;switch(hold&3){case 0:state.mode=STORED;break;case 1:fixedtables(state);state.mode=LEN_;if(flush===Z_TREES){hold>>>=2;bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg="invalid block type";state.mode=BAD}hold>>>=2;bits-=2;break;case STORED:hold>>>=bits&7;bits-=bits&7;while(bits<32){if(have===0){break inf_leave}have--;hold+=input[next++]<>>16^65535)){strm.msg="invalid stored block lengths";state.mode=BAD;break}state.length=hold&65535;hold=0;bits=0;state.mode=COPY_;if(flush===Z_TREES){break inf_leave}case COPY_:state.mode=COPY;case COPY:copy=state.length;if(copy){if(copy>have){copy=have}if(copy>left){copy=left}if(copy===0){break inf_leave}utils.arraySet(output,input,next,copy,put);have-=copy;next+=copy;left-=copy;put+=copy;state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0){break inf_leave}have--;hold+=input[next++]<>>=5;bits-=5;state.ndist=(hold&31)+1;hold>>>=5;bits-=5;state.ncode=(hold&15)+4;hold>>>=4;bits-=4;if(state.nlen>286||state.ndist>30){strm.msg="too many length or distance symbols";state.mode=BAD;break}state.have=0;state.mode=LENLENS;case LENLENS:while(state.have>>=3;bits-=3}while(state.have<19){state.lens[order[state.have++]]=0}state.lencode=state.lendyn;state.lenbits=7;opts={bits:state.lenbits};ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid code lengths set";state.mode=BAD;break}state.have=0;state.mode=CODELENS;case CODELENS:while(state.have>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=here_bits;bits-=here_bits;state.lens[state.have++]=here_val}else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits;bits-=here_bits;if(state.have===0){strm.msg="invalid bit length repeat";state.mode=BAD;break}len=state.lens[state.have-1];copy=3+(hold&3);hold>>>=2;bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits;bits-=here_bits;len=0;copy=3+(hold&7);hold>>>=3;bits-=3}else{n=here_bits+7;while(bits>>=here_bits;bits-=here_bits;len=0;copy=11+(hold&127);hold>>>=7;bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg="invalid bit length repeat";state.mode=BAD;break}while(copy--){state.lens[state.have++]=len}}}if(state.mode===BAD){break}if(state.lens[256]===0){strm.msg="invalid code -- missing end-of-block";state.mode=BAD;break}state.lenbits=9;opts={bits:state.lenbits};ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts);state.lenbits=opts.bits;if(ret){strm.msg="invalid literal/lengths set";state.mode=BAD;break}state.distbits=6;state.distcode=state.distdyn;opts={bits:state.distbits};ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts);state.distbits=opts.bits;if(ret){strm.msg="invalid distances set";state.mode=BAD;break}state.mode=LEN_;if(flush===Z_TREES){break inf_leave}case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){strm.next_out=put;strm.avail_out=left;strm.next_in=next;strm.avail_in=have;state.hold=hold;state.bits=bits;inflate_fast(strm,_out);put=strm.next_out;output=strm.output;left=strm.avail_out;next=strm.next_in;input=strm.input;have=strm.avail_in;hold=state.hold;bits=state.bits;if(state.mode===TYPE){state.back=-1}break}state.back=0;for(;;){here=state.lencode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;state.length=here_val;if(here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1;state.mode=TYPE;break}if(here_op&64){strm.msg="invalid literal/length code";state.mode=BAD;break}state.extra=here_op&15;state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}state.was=state.length;state.mode=DIST;case DIST:for(;;){here=state.distcode[hold&(1<>>24;here_op=here>>>16&255;here_val=here&65535;if(here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>last_bits)];here_bits=here>>>24;here_op=here>>>16&255;here_val=here&65535;if(last_bits+here_bits<=bits){break}if(have===0){break inf_leave}have--;hold+=input[next++]<>>=last_bits;bits-=last_bits;state.back+=last_bits}hold>>>=here_bits;bits-=here_bits;state.back+=here_bits;if(here_op&64){strm.msg="invalid distance code";state.mode=BAD;break}state.offset=here_val;state.extra=here_op&15;state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra;bits-=state.extra;state.back+=state.extra}if(state.offset>state.dmax){strm.msg="invalid distance too far back";state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0){break inf_leave}copy=_out-left;if(state.offset>copy){copy=state.offset-copy;if(copy>state.whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break}}if(copy>state.wnext){copy-=state.wnext;from=state.wsize-copy}else{from=state.wnext-copy}if(copy>state.length){copy=state.length}from_source=state.window}else{from_source=output;from=put-state.offset;copy=state.length}if(copy>left){copy=left}left-=copy;state.length-=copy;do{output[put++]=from_source[from++]}while(--copy);if(state.length===0){state.mode=LEN}break;case LIT:if(left===0){break inf_leave}output[put++]=state.length;left--;state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0){break inf_leave}have--;hold|=input[next++]<>>16&65535|0,n=0;while(len!==0){n=len>2e3?2e3:len;len-=n;do{s1=s1+buf[pos++]|0;s2=s2+s1|0}while(--n);s1%=65521;s2%=65521}return s1|s2<<16|0}module2.exports=adler32},function(module2,exports2){"use strict";function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?3988292384^c>>>1:c>>>1}table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255]}return crc^-1}module2.exports=crc32},function(module2,exports2){"use strict";var BAD=30;var TYPE=12;module2.exports=function inflate_fast(strm,start){var state;var _in;var last;var _out;var beg;var end;var dmax;var wsize;var whave;var wnext;var s_window;var hold;var bits;var lcode;var dcode;var lmask;var dmask;var here;var op;var len;var dist;var from;var from_source;var input,output;state=strm.state;_in=strm.next_in;input=strm.input;last=_in+(strm.avail_in-5);_out=strm.next_out;output=strm.output;beg=_out-(start-strm.avail_out);end=_out+(strm.avail_out-257);dmax=state.dmax;wsize=state.wsize;whave=state.whave;wnext=state.wnext;s_window=state.window;hold=state.hold;bits=state.bits;lcode=state.lencode;dcode=state.distcode;lmask=(1<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op===0){output[_out++]=here&65535}else if(op&16){len=here&65535;op&=15;if(op){if(bits>>=op;bits-=op}if(bits<15){hold+=input[_in++]<>>24;hold>>>=op;bits-=op;op=here>>>16&255;if(op&16){dist=here&65535;op&=15;if(bitsdmax){strm.msg="invalid distance too far back";state.mode=BAD;break top}hold>>>=op;bits-=op;op=_out-beg;if(dist>op){op=dist-op;if(op>whave){if(state.sane){strm.msg="invalid distance too far back";state.mode=BAD;break top}}from=0;from_source=s_window;if(wnext===0){from+=wsize-op;if(op2){output[_out++]=from_source[from++];output[_out++]=from_source[from++];output[_out++]=from_source[from++];len-=3}if(len){output[_out++]=from_source[from++];if(len>1){output[_out++]=from_source[from++]}}}else{from=_out-dist;do{output[_out++]=output[from++];output[_out++]=output[from++];output[_out++]=output[from++];len-=3}while(len>2);if(len){output[_out++]=output[from++];if(len>1){output[_out++]=output[from++]}}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3;_in-=len;bits-=len<<3;hold&=(1<=1;max--){if(count[max]!==0){break}}if(root>max){root=max}if(max===0){table[table_index++]=1<<24|64<<16|0;table[table_index++]=1<<24|64<<16|0;opts.bits=1;return 0}for(min=1;min0&&(type===CODES||max!==1)){return-1}offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}for(;;){here_bits=len-drop;if(work[sym]end){here_op=extra[extra_index+work[sym]];here_val=base[base_index+work[sym]]}else{here_op=32+64;here_val=0}incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0}while(fill!==0);incr=1<>=1}if(incr!==0){huff&=incr-1;huff+=incr}else{huff=0}sym++;if(--count[len]===0){if(len===max){break}len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0){drop=root}next+=min;curr=len-drop;left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS){return 1}low=huff&mask;table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0){table[next+huff]=len-drop<<24|64<<16|0}opts.bits=root;return 0}},function(module2,exports2,__webpack_require__){"use strict";var utils=__webpack_require__(33);var STR_APPLY_OK=true;var STR_APPLY_UIA_OK=true;try{String.fromCharCode.apply(null,[0])}catch(__){STR_APPLY_OK=false}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(__){STR_APPLY_UIA_OK=false}var _utf8len=new utils.Buf8(256);for(var q=0;q<256;q++){_utf8len[q]=q>=252?6:q>=248?5:q>=240?4:q>=224?3:q>=192?2:1}_utf8len[254]=_utf8len[254]=1;exports2.string2buf=function(str){var buf,c,c2,m_pos,i,str_len=str.length,buf_len=0;for(m_pos=0;m_pos>>6;buf[i++]=128|c&63}else if(c<65536){buf[i++]=224|c>>>12;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}else{buf[i++]=240|c>>>18;buf[i++]=128|c>>>12&63;buf[i++]=128|c>>>6&63;buf[i++]=128|c&63}}return buf};function buf2binstring(buf,len){if(len<65537){if(buf.subarray&&STR_APPLY_UIA_OK||!buf.subarray&&STR_APPLY_OK){return String.fromCharCode.apply(null,utils.shrinkBuf(buf,len))}}var result="";for(var i=0;i4){utf16buf[out++]=65533;i+=c_len-1;continue}c&=c_len===2?31:c_len===3?15:7;while(c_len>1&&i1){utf16buf[out++]=65533;continue}if(c<65536){utf16buf[out++]=c}else{c-=65536;utf16buf[out++]=55296|c>>10&1023;utf16buf[out++]=56320|c&1023}}return buf2binstring(utf16buf,out)};exports2.utf8border=function(buf,max){var pos;max=max||buf.length;if(max>buf.length){max=buf.length}pos=max-1;while(pos>=0&&(buf[pos]&192)===128){pos--}if(pos<0){return max}if(pos===0){return max}return pos+_utf8len[buf[pos]]>max?pos:max}},function(module2,exports2){"use strict";module2.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(module2,exports2){"use strict";module2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(module2,exports2){"use strict";function ZStream(){this.input=null;this.next_in=0;this.avail_in=0;this.total_in=0;this.output=null;this.next_out=0;this.avail_out=0;this.total_out=0;this.msg="";this.state=null;this.data_type=2;this.adler=0}module2.exports=ZStream},function(module2,exports2){"use strict";function GZheader(){this.text=0;this.time=0;this.xflags=0;this.os=0;this.extra=null;this.extra_len=0;this.name="";this.comment="";this.hcrc=0;this.done=false}module2.exports=GZheader}])})}});var CSV=class{constructor(onOpen=this.onOpen,saveButtonId=null,openButtonId=null){this.onOpen=onOpen;this.notes=[];if(saveButtonId!==null){document.getElementById(saveButtonId).addEventListener("click",this.saveCSV)}if(openButtonId!==null){document.getElementById(openButtonId).addEventListener("click",this.openCSV)}}processArraysForCSV(data=["1|2|3","3|2|1"],delimiter="|",header="a,b,c",saveNotes=false){let csvDat=header+"\n";let noteIdx=0;data.forEach((line,i)=>{if(data[i]==="string"&&delimiter!==","){csvDat+=line.split(delimiter).join(",")}else{csvData+=line.join(",")}if(saveNotes===true){if(this.notes[noteIdx].idx===i){line+=this.notes[noteIdx].text;noteIdx++}}if(line.indexOf("\n")<0){csvDat+="\n"}});return csvDat}static saveCSV(csvDat="a,b,c\n1,2,3\n3,2,1\n",name=new Date().toISOString()){var hiddenElement=document.createElement("a");hiddenElement.href="data:text/csv;charset=utf-8,"+encodeURI(csvDat);hiddenElement.target="_blank";if(name!==""){hiddenElement.download=name}else{hiddenElement.download=new Date().toISOString()+".csv"}hiddenElement.click()}static openCSV(delimiter=",",onOpen=(csvDat,header,path)=>{return csvDat,header,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;var tempcsvArr=tempcsvData.split("\n");let header=[];var csvDat=[];tempcsvArr.pop();tempcsvArr.forEach((row,i)=>{if(i==0){header=row.split(delimiter)}else{var temp=row.split(delimiter);csvDat.push(temp)}});onOpen(csvDat,header,input.value);input.value="";res({data:csvDat,header,filename:input.value})};reader.readAsText(file)};input.click()})}static openCSVRaw(onOpen=(csvDat,path)=>{return csvDat,path}){return new Promise((res,rej)=>{var input=document.createElement("input");input.accept=".csv";input.type="file";input.onchange=e=>{var file=e.target.files[0];var reader=new FileReader;reader.onload=event=>{var tempcsvData=event.target.result;onOpen(tempcsvData,input.value);input.value="";res({data:tempcsvData,filename:input.value})};reader.readAsText(file)};input.click()})}onOpen(csvDat=[],header=[]){console.log("CSV Opened!",header,csvDat)}};var parseCSVData=(data,filename,head,hasend=true,parser=(lines,filename2,head2)=>{let result={filename:filename2};let header=head2;if(typeof head2==="string")header=head2.split(",");result.header=header;for(let i=0;i{let lines;if(data.includes("\r"))lines=data.split("\r\n");else lines=data.split("\n");if(!head)head=lines[0];lines.shift();if(hasend===false)lines.pop();let result=parser(lines,filename,head);return result};function toISOLocal(d){d=new Date(d);var z=n=>("0"+n).slice(-2);var zz=n=>("00"+n).slice(-3);var off=d.getTimezoneOffset();var sign=off<0?"+":"-";off=Math.abs(off);return d.getFullYear()+"-"+z(d.getMonth()+1)+"-"+z(d.getDate())+"T"+z(d.getHours())+":"+z(d.getMinutes())+":"+z(d.getSeconds())+"."+zz(d.getMilliseconds())+"(UTC"+sign+z(off/60|0)+":00)"}var processDataForCSV=(options={})=>{if(!options.data)return void 0;if(!Array.isArray(options.data))options.data=[options.data];if(options.data&&!options.header)options.header=Object.keys(options.data[0]);let head=[...options.header];if(head.indexOf("timestamp")>-1){head.splice(head.indexOf("timestamp")+1,0,"localized")}let header=head.join(",");let headeridx=0;let lines=[];let foreach=(obj,i)=>{if(Array.isArray(obj)){for(let j=0;j{if(exists2)appendFile(options.filename,joined,options.dir);else appendFile(options.filename,header+joined,options.dir)})}return result};var BrowserFS=__toESM(require_browserfs());var fsInited=false;var fs2=BrowserFS.BFSRequire("fs");var BFSBuffer=BrowserFS.BFSRequire("buffer").Buffer;var initPromise;var initFS=async(dirs=["data"],oninit=(exists2=[])=>{},onerror=e=>{},filesystem="IndexedDB")=>{if(fsInited){if(initPromise){await initPromise}return true}else{fsInited=true;initPromise=new Promise((resolve,reject)=>{BrowserFS.FileSystem[filesystem].Create({},(e,mountableFileSystem)=>{if(e){reject(e);return}if(!mountableFileSystem){onerror(e);reject(new Error(`Error creating BrowserFS`));return}BrowserFS.initialize(mountableFileSystem);let promises=[];dirs.forEach(async dir=>{promises.push(dirExists(fs2,dir))});Promise.all(promises).then(values=>{oninit(values);resolve(true)})})});return await initPromise}};var exists=async(path="")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.exists("/"+path,function(exists2){resolve(exists2)})})};var readFile=async(path="data")=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{fs2.readFile("/"+path,function(e,output){resolve(output)})})};async function readFileChunk(path="data",begin=0,end=5120,onread=data=>{}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);if(path!=""){return await new Promise(async(resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})}else{console.error("Path name is not defined");return void 0}}var getFilenames=async(directory="data",onload=directory2=>{})=>{if(!fsInited)await initFS([directory]);else await dirExists(fs2,directory);return await new Promise((resolve,reject)=>{fs2.readdir("/"+directory,(e,dir)=>{if(e){reject(e);return}if(dir){onload(dir);resolve(dir)}else resolve(void 0)})})};var writeFile=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.writeFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var appendFile2=async(path,data,onwrite=data2=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.appendFile("/"+path,data,err=>{if(err){reject(err);return}onwrite(data);resolve(true)})})};var deleteFile=async(path="data",ondelete=()=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(resolve=>{if(path!=""){fs2.unlink("/"+path,e=>{if(e)console.error(e);ondelete();resolve(true)})}else{console.error("Path name is not defined");resolve(false)}})};var readFileAsText=async(path="data",end="end",begin=0,onread=(data,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise(async(resolve,reject)=>{let size=await getFileSize(path);if(end==="end"){end=size}else if(typeof end==="number"){if(end>size)end=size}fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,end,begin,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();fs2.close(fd,()=>{onread(data,path);resolve(data)})}else resolve(void 0)})})})};var listFiles=async(dir="data",onload=directory=>{})=>{if(!fsInited)await initFS([dir]);else await dirExists(fs2,dir);return await new Promise((resolve,reject)=>{fs2.readdir("/"+dir,(e,directory)=>{if(e){reject(e);return}if(directory){onload(directory)}resolve(directory)})})};var getFileSize=async(path="data",onread=size=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;onread(filesize);resolve(filesize)})})};var getCSVHeader=async(path="data",onopen=(header,filename)=>{})=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{fs2.open("/"+path,"r",(e,fd)=>{if(e){reject(e);return}fs2.read(fd,65535,0,"utf-8",(er,output,bytesRead)=>{if(er){reject(er);return}if(bytesRead!==0){let data=output.toString();let lines=data.split("\n");let header=lines[0];fs2.close(fd,()=>{onopen(header,path);resolve(header)})}else resolve(void 0)})})})};var writeToCSVFromDB=async(path="data",fileSizeLimitMb=10)=>{if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);return await new Promise((resolve,reject)=>{if(path!=""){fs2.stat("/"+path,(e,stats)=>{if(e){reject(e);return}let filesize=stats.size;fs2.open(path,"r",(e2,fd)=>{if(e2){reject(e2);return}let i=0;let maxFileSize=fileSizeLimitMb*1024*1024;let end=maxFileSize;if(filesize{if(e3){reject(e3);return}if(bytesRead!==0)CSV.saveCSV(output.toString(),path.split("/")[1]);fs2.close(fd);resolve(true)})}else{const writeChunkToFile=async()=>{if(ifilesize){end=filesize-i}let chunk=0;fs2.read(fd,end,i,"utf-8",(e3,output,bytesRead)=>{if(e3){reject(e3);return}if(bytesRead!==0){CSV.saveCSV(output.toString(),path.split("/")[1]+"_"+chunk);i+=maxFileSize;chunk++;writeChunkToFile();fs2.close(fd);resolve(true)}})}}}})})}else{console.error("File name is not defined.");resolve(false)}})};async function processCSVChunksFromDB(path="data",onData=(csvdata,start2,end2,size)=>{},maxChunkSize=1e4,start=0,end="end",options={}){let size=await getFileSize(path);let partition=start;return await new Promise((res,rej)=>{let processPartition=()=>{let endChunk=partition+maxChunkSize;if(endChunk>size){endChunk=size}readCSVChunkFromDB(path,partition,endChunk,options).then(async result=>{await onData(result,partition,endChunk,size);partition=endChunk;if(partition!==size){processPartition()}else{res(true)}}).catch(rej)};processPartition()})}async function readCSVChunkFromDB(path="data",start=0,end="end",options={}){if(!fsInited)await initFS([path.split("/")[0]]);else await dirExists(fs2,path.split("/")[0]);const transpose=options.transpose||false;let head=await getCSVHeader(path);if(head)head=head.split(",");else return void 0;let resultLengths=[];let resultNames=[];let results=transpose?[]:{};head.forEach(v=>{if(v){resultNames.push(v);resultLengths.push(1)}else resultLengths[resultLengths.length-1]++});let size=await getFileSize(path);if(end==="end")end=size;else if(end>size){start=size-(end-start);end=size}let data=(await readFileChunk(path,start,end))?.split("\n").slice(1,-1);let preprocess=value=>{try{value=JSON.parse(value)}catch{}return value};if(data)data.forEach((r,i)=>{let row=r.split(",");if(transpose){const entry={};if(options.json)row.forEach((v,idx)=>{if(options.json)entry[resultNames[idx]]=preprocess(v);else entry[resultNames[idx]]=v});results.push(entry)}else{row.forEach((v,i2)=>{const header=resultNames[i2];if(!results[header])results[header]=[];if(options.json)results[header].push(preprocess(v));else results[header].push(v)})}});return results}var directories={};var dirExists=async(fs3,directory)=>{if(!fsInited)await initFS([directory]);return await new Promise((resolve,reject)=>{if(!directory)reject(false);if(directories[directory]==="exists"||directories[directory]==="created"){resolve()}else{if(directory[0]==="/")directory=directory.substring(1);if(!directory)reject(false);fs3.exists(`/${directory}`,exists2=>{if(exists2){directories[directory]="exists";resolve()}else if(directories[directory]==="creating"){resolve()}else{directories[directory]="creating";fs3.mkdir(`/${directory}`,1,err=>{if(err){reject(err);return}directories[directory]="created";setTimeout(resolve,500)})}})}})};var BFSRoutes={initFS,dirExists,exists,readFile,readFileChunk,getFilenames,writeFile,appendFile:appendFile2,deleteFile,readFileAsText,getFileSize,getCSVHeader,listFiles};var CSV_REFERENCE={};function lerp(v0,v1,t){return(1-t)*v0+t*v1}function interpolerp(v0,v1,fit,floor=true){if(fit<=2)return[v0,v1];let a=1/fit;let result=new Array(fit);result[0]=v0;for(let i=1;i<=fit;i++){result[i]=lerp(v0,v1,a*i);if(floor)result[i]=Math.floor(result[i])}return result}var appendCSV=async(newData,filename,header,options)=>{if(!filename){let keys=Object.keys(CSV_REFERENCE);if(keys.length>0)filename=keys[keys.length-1];else filename=`csv${new Date().toISOString()}`}let csv=CSV_REFERENCE[filename];if(!csv){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);CSV_REFERENCE[filename]={header:header?header:["timestamp","localized",...keys],lastX:void 0,buffer:"",buffered:0,bufferSize:options?.bufferSize?options.bufferSize:0,toFixed:options?.toFixed?options.toFixed:0,xIncrement:options?.xIncrement?options.xIncrement:0};csv=CSV_REFERENCE[filename];const existingHeader=await getCSVHeader(filename).catch(()=>null);const isDifferent=!existingHeader||existingHeader!==csv.header.join(",");if(isDifferent)header=csv.header}if(!csv.header||csv.header?.length===0){let keys=Array.from(Object.keys(newData));if(keys.indexOf("timestamp")>-1)keys.splice(keys.indexOf("timestamp"),1);csv.header=header?header:["timestamp","localized",...keys]}else if(header)csv.header=header;let maxLen=1;for(const key in newData){const value=newData[key];if(csv.header.indexOf(key)>-1&&value&&Array.isArray(value)&&value?.length>maxLen)maxLen=value?.length}let x;if(csv.xIncrement){if(!csv.lastX){if(typeof newData[csv.header[0]]!=="undefined"){x=newData[csv.header[0]]}else if(csv.header[0].toLowerCase().includes("time")||csv.header[0].toLowerCase().includes("unix"))x=Date.now()}else{if(newData[csv.header[2]]){if(Array.isArray(newData[csv.header[2]]))x=csv.lastX+csv.xIncrement*newData[csv.header[2]].length;else x=csv.lastX+csv.xIncrement}else if(newData[csv.header[0]]){if(Array.isArray(newData[csv.header[0]]))x=csv.lastX+csv.xIncrement*newData[csv.header[0]].length;else x=csv.lastX+csv.xIncrement}else x=csv.lastX+csv.xIncrement}}else if(newData[csv.header[0]])x=newData[csv.header[0]];else x=Date.now();if(typeof csv.lastX==="undefined")csv.lastX=Array.isArray(x)?x[0]:x;if(typeof x==="undefined"){if(csv.header[0].includes("time")){let now=Date.now();if(maxLen===1)x=Date.now();else{x=interpolerp(csv.lastX,now,maxLen);x.shift()}}else{let newX=csv.lastX+1;if(maxLen>1){x=new Array(maxLen).fill("");x[maxLen-1]=newX}else x=newX}}else if(maxLen>1&&x?.length!==maxLen){if(!Array.isArray(x)||x.length===1){x=interpolerp(csv.lastX,x,maxLen,true);x.shift()}else{x=interpolerp(x[0],x[x.length-1],maxLen,true);x.shift()}}let toAppend=[];if(Array.isArray(x)){let curIdcs={};for(let i=0;icurIdcs[csv.header[j]]){curIdcs[csv.header[j]]++;toAppend[i][j]=d[curIdcs[csv.header[j]]]}else{toAppend[i][j]=""}}}}else{if(i===x.length-1){toAppend[i][j]=d}else{toAppend[i][j]=""}}if(typeof toAppend[i][j]==="number"&&Math.floor(toAppend[i][j])!==toAppend[i][j])toAppend[i][j]=toAppend[i][j].toFixed(CSV_REFERENCE[filename].toFixed)}}}else{toAppend.push([]);for(let j=0;j{csvProcessed+=(options?.json?arr.map(v=>JSON.stringify(v)):arr).join(",")+"\n";if(csv.bufferSize)csv.buffered++});csv.lastX=toAppend[toAppend.length-1][0];if(csv.bufferSize){csv.buffer+=csvProcessed;if(csv.buffered>csv.bufferSize){let r=new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csv.buffer,written=>{res(written)})}else{appendFile2(filename,csv.buffer,written=>{res(written)})}})});await r;csv.buffer="";csv.buffered=0;return r}else return await Promise.resolve(true)}else{return await new Promise((res,rej)=>{exists(filename).then(fileExists=>{if(!fileExists){writeFile(filename,csvProcessed,written=>{res(written)})}else{appendFile2(filename,csvProcessed,written=>{res(written)})}})})}};var updateCSVHeader=(header,filename)=>{if(CSV_REFERENCE[filename]){CSV_REFERENCE[filename].header=header}};var createCSV=(filename,header,toFixed=5,bufferSize=0,xIncrement)=>{if(!CSV_REFERENCE[filename]){if(header?.indexOf("timestamp")>1){header.splice(header.indexOf("timestamp"),1);header.unshift("timestamp")}if((header?.[0].toLowerCase().includes("time")||header?.[0].toLowerCase().includes("unix"))&&header[1]!=="localized"){header.splice(1,0,"localized")}CSV_REFERENCE[filename]={header,lastX:header[1]==="localized"?Date.now():0,bufferSize,buffer:"",buffered:0,toFixed,xIncrement};return new Promise((res,rej)=>{exists(filename).then(doesExist=>{if(!doesExist){writeFile(filename,CSV_REFERENCE[filename].header?CSV_REFERENCE[filename].header.join(",")+"\n":"",written=>{res(written)}).catch(rej)}})})}};var visualizeDirectory=(dir,parentNode=document.body)=>{return new Promise(async(res,rej)=>{if(parentNode.querySelector("#bfs"+dir))parentNode.querySelector("#bfs"+dir)?.remove();parentNode.insertAdjacentHTML("beforeend",`
`);let div=parentNode.querySelector("#bfs"+dir);await listFiles(dir).then(directory=>{if(directory.length===0)div.innerHTML="No Files!";else directory.forEach(listing=>{div?.insertAdjacentHTML("beforeend",`
- Data: - ${listing} - - ${listing.indexOf(".")>-1?``:""} -
`);if(document.getElementById(`delete${listing}`)){document.getElementById(`delete${listing}`).onclick=()=>{deleteFile(dir+"/"+listing,()=>{visualizeDirectory(dir,parentNode)})}}if(document.getElementById(`download${listing}`)){document.getElementById(`download${listing}`).onclick=()=>{writeToCSVFromDB(dir+"/"+listing,10)}}});res(directory)}).catch(rej)})};var csvRoutes={appendCSV,updateCSVHeader,createCSV,visualizeDirectory,openCSV:CSV.openCSV,saveCSV:CSV.saveCSV,openCSVRaw:CSV.openCSVRaw,parseCSVData,getCSVHeader,writeToCSVFromDB,readCSVChunkFromDB,processCSVChunksFromDB,toISOLocal};})(); -/*! Bundled license information: - -browserfs/dist/browserfs.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) -*/ diff --git a/src/extras/dist/loaders/methodstrings.d.ts b/src/extras/dist/loaders/methodstrings.d.ts deleted file mode 100644 index 978aabc8..00000000 --- a/src/extras/dist/loaders/methodstrings.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function methodstrings(node: any): void; diff --git a/src/extras/dist/services/ecs/ECS.service.d.ts b/src/extras/dist/services/ecs/ECS.service.d.ts deleted file mode 100644 index cb3252b8..00000000 --- a/src/extras/dist/services/ecs/ECS.service.d.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { GraphNode, GraphNodeProperties } from '../../core/Graph'; -import { Service, ServiceOptions } from '../Service'; -export type EntityProps = { - components: { - [key: string]: any; - }; -} & (GraphNodeProperties | GraphNode); -export type SystemProps = (GraphNodeProperties & { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; -}) | GraphNode; -export type Entity = { - components: { - [key: string]: any; - }; - [key: string]: any; -} & GraphNode; -export type System = { - __operator: (entities: { - [key: string]: Entity; - }) => any; - setupEntities: (entities: { - [key: string]: Entity; - }) => { - [key: string]: Entity; - }; - setupEntity: (entity: Entity) => Entity; - remove?: (entity: Entity, entitities: { - [key: string]: Entity; - }) => Entity; - entities: { - [key: string]: Entity; - }; - entityKeys: string[]; -} & GraphNode; -export type ECSOptions = { - entities: { - [key: string]: EntityProps; - }; - systems: { - [key: string]: SystemProps; - }; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class ECSService extends Service { - entities: { - [key: string]: Entity; - }; - systems: { - [key: string]: System; - }; - entityMap: Map; - entityKeyMap: Map; - order: string[]; - animating: boolean; - entityCt: number; - systemCt: number; - constructor(options?: ECSOptions); - updateEntities: (order?: string[], filter?: boolean, debug?: any) => void; - animateEntities: (filter?: boolean, order?: string[]) => void; - stop: () => void; - start: (filter?: boolean) => void; - addEntities: (prototype: EntityProps, components?: { - [key: string]: any; - }, count?: number) => string[]; - addEntity: (prototype?: EntityProps, components?: { - [key: string]: any; - }) => Entity; - addSystems: (systems?: { - [key: string]: SystemProps; - }, order?: string[]) => { - [key: string]: System; - }; - addSystem: (prototype: SystemProps, setupEntities?: (entities: { - [key: string]: Entity; - }) => any, setupEntity?: (entity: Entity) => any, operator?: (entities: any) => any, remove?: (entities: any) => any, order?: string[]) => System; - setupEntity: (entity: Entity) => void; - removeEntity: (tag: string) => string | GraphNode; - removeEntities(entities: string[] | { - [key: string]: Entity; - }): void; - removeSystem: (tag: string) => string | GraphNode; - filterObject(o: { - [key: string]: any; - }, filter: (string: any, any: any) => boolean | undefined): { - [k: string]: any; - }; - setEntities: (entities: string[] | { - [key: string]: Entity; - }, props: { - [key: string]: any; - }) => boolean; - setEntity: (entity: Entity, props: { - [key: string]: any; - }) => any; - bufferValues: (entities: { - [key: string]: Entity; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; -} diff --git a/src/extras/dist/src/core/EventHandler.d.ts b/src/extras/dist/src/core/EventHandler.d.ts deleted file mode 100644 index 2f00b243..00000000 --- a/src/extras/dist/src/core/EventHandler.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -export declare class EventHandler { - data: { - [key: string]: any; - }; - triggers: { - [key: string]: { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - }; - ctr: number; - constructor(data?: { - [key: string]: any; - }); - setState: (updateObj: { - [key: string]: any; - }) => { - [key: string]: any; - }; - setValue: (key: any, value: any) => void; - triggerEvent: (key: any, value: any) => void; - subscribeState: (onchange: (res: any) => void) => number; - unsubscribeState: (sub: number) => boolean; - subscribeEvent: (key: string, onchange: (res: any) => void, refObject?: { - [key: string]: any; - }, refKey?: string) => number; - unsubscribeEvent: (key: string, sub?: number) => boolean; - subscribeEventOnce: (key: string, onchange: (res: any) => void) => any; - getEvent: (key: any, sub?: any) => { - [key: string]: any; - sub: number; - onchange: Function; - } | { - [key: string]: any; - sub: number; - onchange: Function; - }[]; - getSnapshot: () => void; - onRemoved: (trigger: { - sub: number; - onchange: Function; - }) => void; -} diff --git a/src/extras/dist/src/core/Graph.d.ts b/src/extras/dist/src/core/Graph.d.ts deleted file mode 100644 index f77b09bd..00000000 --- a/src/extras/dist/src/core/Graph.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { EventHandler } from "./EventHandler"; -export declare const state: EventHandler; -export type GraphNodeProperties = { - __props?: Function | { - [key: string]: any; - } | GraphNodeProperties | GraphNode; - __operator?: ((...args: any[]) => any) | string; - __children?: { - [key: string]: any; - }; - __listeners?: { - [key: string]: true | string | ((result: any) => void) | { - __callback: string | ((result: any) => void) | true; - subInput?: boolean; - [key: string]: any; - }; - } | { - [key: string]: ((result: any) => void) | true | string; - }; - __onconnected?: ((node: any) => void | ((node: any) => void)[]); - __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); - __node?: { - tag?: string; - state?: EventHandler; - [key: string]: any; - }; - __args?: any[]; - __callable?: boolean; - [key: string]: any; -}; -export type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, properties: GraphNodeProperties, key: string) => void; -export type Roots = { - [key: string]: any; -}; -export type GraphOptions = { - roots?: Roots; - loaders?: { - [key: string]: Loader | { - init?: Loader; - connected?: (node: any) => void; - disconnected?: (node: any) => void; - }; - }; - state?: EventHandler; - mapGraphs?: false; - [key: string]: any; -}; -export type argObject = { - __input?: string | ((...args: any[]) => any); - __callback: string | ((...args: any[]) => any); - __args?: any[]; - __output?: string | argObject | ((...args: any[]) => any); -}; -export type Listener = { - __callback?: string; - __args?: (argObject | Function | string)[]; - sub: number; - node: GraphNode; - graph: Graph; - source?: string; - key?: string; - target?: string; - tkey?: string; - arguments?: Function[]; - subInput?: boolean; - onchange: Function; -}; -export declare class Callable extends Function { - __bound: Callable; - __call: ((...args: any[]) => any); - [key: string]: any; - constructor(); -} -export declare class GraphNode { - __node: { - tag: string; - unique: string; - state: EventHandler; - [key: string]: any; - }; - __children?: { - [key: string]: GraphNode; - }; - __parent?: Graph | GraphNode; - __operator?: any; - __listeners?: any; - __props?: any; - __args: any[]; - [key: string]: any; - constructor(properties: GraphNodeProperties, parent?: { - [key: string]: any; - }, graph?: Graph); - get __graph(): any; - set __graph(graph: any); - __setProperties: (properties: any, parent: any, graph: any) => void; - __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, target?: string, tkey?: string, args?: any[], callbackStr?: string) => any; - __unsubscribe: (sub?: number, key?: string, unsubInput?: boolean) => boolean; - __setOperator: (fn: (...args: any[]) => any) => any; - __addLocalState: (props?: { - [key: string]: any; - }, key?: string) => void; - __proxyObject: (obj: any) => void; - __addOnconnected(callback: (node: any) => void): void; - __addOndisconnected(callback: (node: any) => void): void; - __callConnected(node?: this): void; - __callDisconnected(node?: this): void; -} -export declare class Graph { - [key: string]: any; - __node: { - tag: string; - unique: string; - state: EventHandler; - nodes: Map; - roots: { - [key: string]: any; - }; - mapGraphs?: boolean; - [key: string]: any; - }; - constructor(options?: GraphOptions); - init: (options?: GraphOptions) => void; - load: (roots: { - [key: string]: any; - }, overwrite?: boolean) => { - [key: string]: any; - }; - setLoaders: (loaders: { - [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, roots: any, props: any, key: string) => void; - }, replace?: boolean) => any; - runLoaders: (node: any, parent: any, properties: any, key: any) => void; - add: (properties: any, parent?: GraphNode | string, overwrite?: boolean) => GraphNode; - recursiveSet: (originCpy: any, parent: any, listeners: any, origin: any, overwrite?: boolean) => any; - remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; - run: (node: string | GraphNode, ...args: any[]) => any; - /** - * - * Listeners are an object where each key is a node tag, and each value is an object specifying callbacks or multiple callback for events on the graph, e.g. function outputs or variable changes. - * { - * [node.__node.tag (or arbitrary)]:{ - * [node.key (key optional)]:{__callback:string|Function, __args?:[], subInput?:boolean} | Function (bound to main node tag if specified) | string - * } - * } - * - * __args can be strings referencing other nodes/methods or values to pass correct inputs into the callback if more than one is required, else the output of the thing listened to is used by default - */ - setListeners: (listeners: { - [key: string]: { - [key: string]: any; - }; - }) => void; - clearListeners: (node: GraphNode | string, listener?: string) => void; - get: (tag: string) => any; - getByUnique: (unique: string) => any; - set: (tag: string, node: GraphNode) => Map; - delete: (tag: string) => boolean; - list: () => string[]; - getListener: (nodeTag: string, key?: string, sub?: number) => Listener; - getProps: (node: GraphNode | string, getInitial?: boolean) => void; - subscribe: (nodeEvent: GraphNode | string, onEvent: string | GraphNode | ((...res: any) => void), args?: any[], key?: string | undefined, subInput?: boolean, target?: string | GraphNode, tkey?: string) => number; - unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; - setState: (update: { - [key: string]: any; - }) => void; -} -export declare function getAllProperties(obj: any): any[]; -export declare function instanceObject(obj: any): any; -export declare function isNativeClass(thing: any): boolean; -export declare function isFunction(x: any): "function" | "class" | "async" | "arrow" | ""; -export declare let getCallbackFromString: (a: any, graph: any) => (...inp: any[]) => any; -export declare const wrapArgs: (callback: any, argOrder: any, graph: any) => { - __callback: any; - __args: any[]; -}; diff --git a/src/extras/dist/src/extras/algorithms/accel_gyro.d.ts b/src/extras/dist/src/extras/algorithms/accel_gyro.d.ts deleted file mode 100644 index c98cb706..00000000 --- a/src/extras/dist/src/extras/algorithms/accel_gyro.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const accel_gyro: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/beat_detect.d.ts b/src/extras/dist/src/extras/algorithms/beat_detect.d.ts deleted file mode 100644 index bc3fb33d..00000000 --- a/src/extras/dist/src/extras/algorithms/beat_detect.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const beat_detect: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/blink.d.ts b/src/extras/dist/src/extras/algorithms/blink.d.ts deleted file mode 100644 index 4743de8d..00000000 --- a/src/extras/dist/src/extras/algorithms/blink.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const blink_detect: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/buffering.d.ts b/src/extras/dist/src/extras/algorithms/buffering.d.ts deleted file mode 100644 index 71e1efac..00000000 --- a/src/extras/dist/src/extras/algorithms/buffering.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const circularBuffer2d: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/coherence.d.ts b/src/extras/dist/src/extras/algorithms/coherence.d.ts deleted file mode 100644 index 0b35b736..00000000 --- a/src/extras/dist/src/extras/algorithms/coherence.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const coherence: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/dft.d.ts b/src/extras/dist/src/extras/algorithms/dft.d.ts deleted file mode 100644 index ccd239c3..00000000 --- a/src/extras/dist/src/extras/algorithms/dft.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from '../../core/Graph'; -export declare const dft: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/index.d.ts b/src/extras/dist/src/extras/algorithms/index.d.ts deleted file mode 100644 index c3ec990e..00000000 --- a/src/extras/dist/src/extras/algorithms/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -declare const algorithms: { - [key: string]: GraphNodeProperties; -}; -export { algorithms }; diff --git a/src/extras/dist/src/extras/algorithms/index.gpu.d.ts b/src/extras/dist/src/extras/algorithms/index.gpu.d.ts deleted file mode 100644 index fcfc3ef0..00000000 --- a/src/extras/dist/src/extras/algorithms/index.gpu.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare const gpualgorithms: { - dft: import("../../core/Graph").GraphNodeProperties; - coherence: import("../../core/Graph").GraphNodeProperties; -}; diff --git a/src/extras/dist/src/extras/algorithms/rms.d.ts b/src/extras/dist/src/extras/algorithms/rms.d.ts deleted file mode 100644 index 39ad84d0..00000000 --- a/src/extras/dist/src/extras/algorithms/rms.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { GraphNodeProperties } from "../../core/Graph"; -export declare const rms: GraphNodeProperties; diff --git a/src/extras/dist/src/extras/algorithms/util/ArrayManip.d.ts b/src/extras/dist/src/extras/algorithms/util/ArrayManip.d.ts deleted file mode 100644 index b6d5e3ad..00000000 --- a/src/extras/dist/src/extras/algorithms/util/ArrayManip.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; -export declare class ArrayManip { - static autoscale(array: any, lineIdx?: number, nLines?: number, centerZero?: boolean, ymin?: number, ymax?: number, clamp?: boolean): any; - static genTimestamps(ct: any, sps: any): any[]; - static absmax(array: any): number; - static downsample(array: any, fitCount: any, scalar?: number): any; - static upsample(array: any, fitCount: any, scalar?: number): any[]; - static interpolate(array: number[], fitCount: number, scalar?: number): any; - static HSLToRGB(h: any, s: any, l: any, scalar?: number): [number, number, number]; - static circularBuffer(arr: any[], newEntries: any[]): any[]; - static reformatData(data: { - [key: string]: number[] | number | { - values: number[] | number; - [key: string]: any; - }; - } | string | ((number | number[])[]) | number, key?: string): string | number | { - [key: string]: number | number[] | { - [key: string]: any; - values: number[] | number; - }; - } | (number | number[])[]; - static padTime(data: number[], //new data, assumed to be sequential between a gap - lastValue: number, //the last data point before the gap - time: number, //interval that's passed to determine slope between samples - targetFit: number): number[]; - static interpolateForTime(data: number[], //new data, assumed to be evenly spread over a time interval - time: number, //the time interval passed (s) - targetSPS: number): any; - static bufferValues: (objects: { - [key: string]: { - [key: string]: any; - }; - }, property: string, keys?: string[] | { - [key: string]: any; - }, buffer?: ArrayBufferLike) => ArrayBufferLike; - isTypedArray(x: any): boolean; - recursivelyAssign: (target: any, obj: any) => any; - spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; -} diff --git a/src/extras/dist/src/extras/algorithms/util/BiquadFilters.d.ts b/src/extras/dist/src/extras/algorithms/util/BiquadFilters.d.ts deleted file mode 100644 index fd1d4fc9..00000000 --- a/src/extras/dist/src/extras/algorithms/util/BiquadFilters.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -export type FilterSettings = { - sps: number; - useSMA4?: boolean; - useNotch50?: boolean; - useNotch60?: boolean; - useLowpass?: boolean; - lowpassHz?: number; - useBandpass?: boolean; - bandpassLower?: number; - bandpassUpper?: number; - useDCBlock?: boolean; - DCBresonance?: number; - useScaling?: boolean; - scalar?: number; - trimOutliers?: boolean; - outlierTolerance?: number; -}; -export declare class BiquadChannelFilterer { - idx: number; - sps: number; - bandpassLower?: number; - bandpassUpper?: number; - useSMA4?: boolean; - last4?: number[]; - filtered: number; - trimOutliers?: boolean; - outlierTolerance?: number; - useNotch50?: boolean; - useNotch60?: boolean; - useLowpass?: boolean; - lowpassHz?: number; - useBandpass?: boolean; - useDCBlock?: boolean; - DCBresonance?: number; - useScaling?: boolean; - scalar?: number; - notch50?: any; - notch60?: any; - lp1?: any; - bp1?: any; - dcb?: any; - constructor(options?: FilterSettings); - reset(sps?: number): void; - setBandpass(bandpassLower?: number, bandpassUpper?: number, sps?: number): void; - apply(latestData?: number): number; -} -export declare class Biquad { - type: string; - freq: number; - sps: number; - Q: number; - dbGain: number; - a0: number; - a1: number; - a2: number; - b0: number; - b1: number; - b2: number; - x1: number; - x2: number; - y1: number; - y2: number; - constructor(type: 'lowpass' | 'highpass' | 'bandpass' | 'notch' | 'peak' | 'lowshelf' | 'highshelf', freq: number, sps: number, Q?: number, dbGain?: number); - lowpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - highpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - bandpass(A: any, sn: any, cs: any, alpha: any, beta: any): void; - notch(A: any, sn: any, cs: any, alpha: any, beta: any): void; - peak(A: any, sn: any, cs: any, alpha: any, beta: any): void; - lowshelf(A: any, sn: any, cs: any, alpha: any, beta: any): void; - highshelf(A: any, sn: any, cs: any, alpha: any, beta: any): void; - applyFilter(signal_step: any): number; - zResult(freq: any): number; - static calcCenterFrequency(freqStart: any, freqEnd: any): number; - static calcBandwidth(freqStart: any, freqEnd: any): number; - static calcBandpassQ(frequency: any, bandwidth: any, resonance?: number): number; - static calcNotchQ(frequency: any, bandwidth: any, resonance?: number): number; -} -export declare class DCBlocker { - r: number; - x1: number; - x2: number; - y1: number; - y2: number; - constructor(r?: number); - applyFilter(signal_step: any): number; -} -export declare const makeNotchFilter: (frequency: any, sps: any, bandwidth: any) => Biquad; -export declare const makeBandpassFilter: (freqStart: any, freqEnd: any, sps: any, resonance?: number) => Biquad; diff --git a/src/extras/dist/src/extras/algorithms/util/ByteParser.d.ts b/src/extras/dist/src/extras/algorithms/util/ByteParser.d.ts deleted file mode 100644 index 178a7329..00000000 --- a/src/extras/dist/src/extras/algorithms/util/ByteParser.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { ArrayManip } from "./ArrayManip"; -export declare class ByteParser extends ArrayManip { - static codes: { - '\\n': number; - '\\r': number; - '\\t': number; - '\\s': number; - '\\b': number; - '\\f': number; - '\\': number; - }; - static toDataView(value: string | number | ArrayBufferLike | DataView | number[]): DataView; - static searchBuffer(buffer: number[] | ArrayBuffer, searchString: Uint8Array, limit?: number): any[]; - static bytesToInt16(x0: number, x1: number): number; - static bytesToUInt16(x0: number, x1: number): number; - static Uint16ToBytes(y: number): number[]; - static bytesToInt24(x0: number, x1: number, x2: number): number; - static bytesToUInt24(x0: number, x1: number, x2: number): number; - static Uint24ToBytes(y: number): number[]; - static bytesToInt32(x0: number, x1: number, x2: number, x3: number): number; - static bytesToUInt32(x0: number, x1: number, x2: number, x3: number): number; - static Uint32ToBytes(y: number): number[]; - static get2sCompliment(val: number, nbits: number): number; - static getSignedInt(...args: number[]): number; - static asUint8Array(input: any): Uint8Array; - static boyerMoore(patternBuffer: any): any; - static struct(format: string): Readonly<{ - unpack: (arrb: any) => any[]; - pack: (...values: any[]) => ArrayBuffer; - unpack_from: (arrb: any, offs: any) => any[]; - pack_into: (arrb: any, offs: any, ...values: any[]) => void; - iter_unpack: (arrb: any) => Generator; - format: string; - size: number; - }>; -} diff --git a/src/extras/dist/src/extras/index.services.d.ts b/src/extras/dist/src/extras/index.services.d.ts deleted file mode 100644 index 4c38107e..00000000 --- a/src/extras/dist/src/extras/index.services.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './struct/Struct.frontend'; -export * from './struct/Struct.backend'; -export * from './struct/genTimestamps'; -export * from './ecs/ECS.systems'; -export * from './webgl-plot/webglplot.routes'; -export { algorithms } from './algorithms/index'; diff --git a/src/extras/dist/src/extras/struct/Struct.backend.d.ts b/src/extras/dist/src/extras/struct/Struct.backend.d.ts deleted file mode 100644 index 278d1ebe..00000000 --- a/src/extras/dist/src/extras/struct/Struct.backend.d.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { ObjectId } from "./datastructures/bson.cjs"; -import { AuthorizationStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; -import { TimeSpecifier } from './genTimestamps'; -import { Service } from "../../services/Service"; -import { User } from '../../services/router/Router'; -export declare const toObjectId: (str: any) => any; -export declare const getStringId: (mongoid: string | ObjectId) => any; -type CollectionsType = { - [x: string]: CollectionType; -}; -type CollectionType = any | { - instance?: any; - reference: { - [key: string]: any; - }; -}; -export declare class StructBackend extends Service { - name: string; - debug: boolean; - db: any; - users: { - [key: string]: User; - }; - collections: CollectionsType; - mode: 'local' | 'mongo' | string; - useAuths: boolean; - useAccessTokens: boolean; - useRefreshTokens: boolean; - accessTokens: Map; - refreshTokens: Map; - constructor(options?: any, dboptions?: { - users?: { - [key: string]: User; - }; - mode?: 'local' | 'mongo' | string; - db?: any; - collections?: CollectionsType; - useAuths?: boolean; - debug?: boolean; - useAccessTokens?: boolean; - useRefreshTokens?: boolean; - }); - initDB: (dboptions: any) => void; - query: (requestingUserId: string, collection?: any, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - getUser: (requestingUserId: string, lookupId: string, basicInfo?: boolean, token?: string) => Promise; - setUser: (requestingUserId: string, struct: Partial, token: string) => Promise; - getUsersByIds: (requestingUserId: string, userIds: string[], basicInfo?: boolean) => Promise; - getUsersByRole: (requestingUserId: string, role: string) => Promise; - deleteUser: (requestingUserId: string, userId: string, deleteData?: boolean, token?: string) => Promise; - setData: (requestingUserId: string, structs: any[], notify?: boolean, token?: string) => Promise; - getData: (requestingUserId: string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number, token?: string) => Promise; - getDataByIds: (requestingUserId: string, structIds: string[], ownerId?: string, collection?: string, token?: string) => Promise; - getAllData: (requestingUserId: string, ownerId: string, excludedCollections?: string[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - deleteData: (requestingUserId: string, structIds: string[], token?: string) => Promise; - getUserGroups: (requestingUserId: string, userId?: string, groupId?: string) => Promise; - deleteGroup: (requestingUserId: string, groupId: string, token?: string) => Promise; - getAuthorizations: (requestingUserId: string, ownerId?: string, authId?: string, token?: string) => Promise; - deleteAuthorization: (requestingUserId: string, authId: string, token?: string) => Promise; - getToken: (user: Partial) => string; - notificationStruct: (parentStruct?: any) => { - structType: string; - timestamp: number; - _id: string; - note: string; - alert: boolean; - ownerId: string; - parentUserId: string; - parent: { - structType: any; - _id: any; - }; - }; - checkToNotify: (user: Partial, structs?: any[], mode?: string) => Promise; - queryMongo: (user: Partial, collection: string, queryObj?: any, findOne?: boolean, skip?: number, token?: string) => Promise; - setMongoData: (user: Partial, structs?: any[], notify?: boolean, token?: string) => Promise; - setMongoUser: (user: Partial, struct: Partial, token?: string) => Promise; - setGroup: (user: Partial, struct: any, mode?: string, token?: string) => Promise; - getMongoUser: (user: Partial, info?: string, requireAuth?: boolean, basicInfo?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - queryUsers: (user: Partial, info?: string, limit?: number, skip?: number, requireAuth?: boolean, token?: string) => Promise<{} | { - user: ProfileStruct; - authorizations: AuthorizationStruct[]; - groups: GroupStruct[] | { - user: ProfileStruct; - }; - }>; - getMongoUsersByIds: (user: Partial, userIds?: any[], basicInfo?: boolean) => Promise; - getMongoUsersByRole: (user: Partial, role: string) => Promise; - getMongoDataByIds: (user: Partial, structIds: string[], ownerId: string | undefined, collection: string | undefined, token?: string) => Promise; - getMongoData: (user: Partial, collection: string | undefined, ownerId: string | undefined, dict?: any | undefined, limit?: number, skip?: number, token?: string) => Promise; - getAllUserMongoData: (user: Partial, ownerId: any, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], token?: string) => Promise; - getMongoDataByRefs: (user: Partial, structRefs?: any[], token?: string) => Promise; - getMongoAuthorizations: (user: Partial, ownerId?: any, authId?: string, token?: string) => Promise; - getMongoGroups: (user: Partial, userId?: any, groupId?: string) => Promise; - deleteMongoData: (user: Partial, structRefs?: any[], token?: string) => Promise; - deleteMongoUser: (user: Partial, userId: any, deleteData?: boolean, token?: string) => Promise; - deleteMongoGroup: (user: Partial, groupId: any, token?: string) => Promise; - deleteMongoAuthorization: (user: Partial, authId: any, token?: string) => Promise; - setAuthorization: (user: Partial, authStruct: any, token?: string) => Promise; - checkAuthorization: (user: string | Partial | { - _id: string; - }, struct: any, request?: string, token?: string) => Promise; - wipeDB: () => Promise; - overwriteLocalData: (structs: any) => void; - setLocalData: (structs: any) => void; - getLocalData: (collection: any, query?: any) => any; - deleteLocalData: (struct: any) => boolean; -} -export {}; diff --git a/src/extras/dist/src/extras/struct/datastructures/DataStructures.d.ts b/src/extras/dist/src/extras/struct/datastructures/DataStructures.d.ts deleted file mode 100644 index 3da6e206..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/DataStructures.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -import * as types from './types'; -export declare function Struct(structType?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.Struct; -export declare const eegCoordinates: { - [x: string]: number[]; -}; -export declare function setCoordinate(channelDict: any, assignTo?: {}): any; -export declare function EEGCoordinates(channelDicts?: [], genCoherenceMap?: boolean): types.EEGStruct[]; -export declare function FrequencyBandsStruct(additionalBands?: types.FrequencyBandNames[], //add whatever tags -assignTo?: {}): types.FrequencyBandsStruct; -export declare function EEGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EEGStruct; -export declare function CoherenceStruct(coords?: { - 0: types.EEGStruct; - 1: types.EEGStruct; -}, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.CoherenceStruct; -export declare function CoherenceMap(opts?: { - channelDicts: any[]; - taggedOnly?: boolean; -}, _?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.CoherenceStruct[]; -export declare function FNIRSStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.FNIRSStruct; -export declare function IMUStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.IMUStruct; -export declare function EyeTrackerStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EyeTrackerStruct; -export declare function ECGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ECGStruct; -export declare function EDAStruct(_?: string, __?: {}, ___?: { - _id: string; -}, ____?: { - structType: string; - _id: string; -}): void; -export declare function PPGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.FNIRSStruct; -export declare function HRVStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ECGStruct; -export declare function EMGStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.EEGStruct; -export declare function ProfileStruct(tag?: string | number | undefined, assignProps?: types.ArbitraryObject, parentUser?: Partial | { - _id: string; -}, parentStruct?: types.ArbitraryObject): types.ProfileStruct; -export declare function AuthorizationStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.AuthorizationStruct; -export declare function GroupStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.GroupStruct; -export declare function Data(type: string, data: any): { - type: string; - data: any; - timestamp: number; -}; -export declare function DataStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.DataStruct; -export declare function EventStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.EventStruct; -export declare function ChatroomStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.ChatroomStruct; -export declare function CommentStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.CommentStruct; -export declare function NotificationStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.NotificationStruct; -export declare function ScheduleStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.ScheduleStruct; -export declare function DateStruct(tag?: string | number | undefined, assignProps?: {}, parentUser?: Partial | { - _id: string; -}, parentStruct?: { - structType: string; - _id: string; -}): types.DateStruct; -export declare const structRegistry: { - Struct: typeof Struct; - EEGStruct: typeof EEGStruct; - FNIRSStruct: typeof FNIRSStruct; - CoherenceStruct: typeof CoherenceStruct; - CoherenceMap: typeof CoherenceMap; - FrequencyBandsStruct: typeof FrequencyBandsStruct; - IMUStruct: typeof IMUStruct; - EyeTrackerStruct: typeof EyeTrackerStruct; - ECGStruct: typeof ECGStruct; - EDAStruct: typeof EDAStruct; - PPGStruct: typeof PPGStruct; - HRVStruct: typeof HRVStruct; - EMGStruct: typeof EMGStruct; - ProfileStruct: typeof ProfileStruct; - AuthorizationStruct: typeof AuthorizationStruct; - GroupStruct: typeof GroupStruct; - DataStruct: typeof DataStruct; - EventStruct: typeof EventStruct; - ChatroomStruct: typeof ChatroomStruct; - CommentStruct: typeof CommentStruct; - NotificationStruct: typeof NotificationStruct; - ScheduleStruct: typeof ScheduleStruct; - DateStruct: typeof DateStruct; -}; diff --git a/src/extras/dist/src/extras/struct/datastructures/DataTablet.d.ts b/src/extras/dist/src/extras/struct/datastructures/DataTablet.d.ts deleted file mode 100644 index 967adeae..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/DataTablet.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { ArbitraryObject, Struct } from './types'; -export declare class DataTablet { - workerId: any; - id: any; - threaded: boolean; - workers: any; - DS: any; - collections: Map; - data: any; - rolloverLimit: number; - dataSorts: Map; - watches: any; - constructor(props?: {}); - randomId(tag?: string): string; - setLocalData(structs: (Partial)[] | (Partial)): void; - getLocalData(collection: string, query: any): any; - onCollectionSet: (type: any, collection: any) => void; - runSort(key: string, dataObj?: {}, newdata?: any[], tablet?: this): any; - /** - * Unsorted data structs come in with a minimum 'structType' and 'timestamp' set of values. - * - * If a sort key matches the structType or dataType (from a data struct.data array), - * it can return a modified struct or push to the newdata array with a set of newly made structs. - * Return undefined to process the input data by default structType/dataType and timestamp into the tablet, so you can do this - * plus split up additional structs or processed structs into each other. This is intentionally vague until we refine this idea into clearer hooks. - * The newdata array accumulates all of the data structs supplied on a sort pass which gets sent to this.onSorted() at the end of the sorting pass. - */ - setSort(key: string | string[], response?: (data: any, newdata?: any[], tablet?: this) => void): void; - getSort(key: string): any; - checkWatches(sorted?: ArbitraryObject): void; - /** - * - pass the sorted structure to the accumulator object which is just an empty object you can do whatever with - * - ondata checks the data if it's relevant and keeps a record via the accumulator - * - if the accumlator condition is satisfied, return true which triggers ontrigger(accum), else return a falsey value - * - ontrigger function then is passed the accumulator object to do whatever with, - * e.g. supply it to an 'alert' struct, set alert:true, and data:accum, and update the server to notify any connected peers. - */ - setWatch(name: string, ownerId: string | undefined, ondata?: (sorted: any, accum: any, ownerId: string) => boolean, ontrigger?: (accum: any) => void): void; - getWatch(name: string): any; - sortStructsIntoTable(datastructs?: Struct[]): Promise; - onUpdate(_: any, __: any, ___?: any): void; - onSorted(_?: any[]): void; - getDataByTimestamp(timestamp: number, ownerId: string): any; - getDataByTimeRange(begin: number, end: number, type: string, ownerId: string): ArbitraryObject; - getDataByType(type: string, timestamp: number, ownerId: string): any; - filterSleepResults(unfiltered?: ArbitraryObject): ArbitraryObject; - sortObjectByPropName(object: ArbitraryObject): ArbitraryObject; - checkRollover(collection: string, limit?: number): boolean; -} diff --git a/src/extras/dist/src/extras/struct/datastructures/bson.d.cts b/src/extras/dist/src/extras/struct/datastructures/bson.d.cts deleted file mode 100644 index 2efd64df..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/bson.d.cts +++ /dev/null @@ -1,419 +0,0 @@ -declare var bson: Readonly<{ - __proto__: any; - Code: typeof Code; - BSONSymbol: typeof BSONSymbol; - DBRef: typeof DBRef; - Binary: typeof Binary; - ObjectId: typeof ObjectId; - UUID: typeof UUID; - Long: typeof Long; - Timestamp: typeof Timestamp; - Double: typeof Double; - Int32: typeof Int32; - MinKey: typeof MinKey; - MaxKey: typeof MaxKey; - BSONRegExp: typeof BSONRegExp; - Decimal128: typeof Decimal128; - setInternalBufferSize: typeof setInternalBufferSize; - serialize: typeof serialize; - serializeWithBufferAndIndex: typeof serializeWithBufferAndIndex; - deserialize: typeof deserialize; - calculateObjectSize: typeof calculateObjectSize; - deserializeStream: typeof deserializeStream; - BSONValue: typeof BSONValue; - BSONError: typeof BSONError; - BSONVersionError: typeof BSONVersionError; - BSONRuntimeError: typeof BSONRuntimeError; - BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; - }>; - EJSON: any; -}>; -export class BSONError extends Error { - static isBSONError(value: any): boolean; - constructor(message: any); - get bsonError(): boolean; - get name(): string; -} -export class BSONRegExp extends BSONValue { - static parseOptions(options: any): any; - static fromExtendedJSON(doc: any): any; - constructor(pattern: any, options: any); - get _bsontype(): string; - pattern: any; - options: any; - toExtendedJSON(options: any): { - $regex: any; - $options: any; - $regularExpression?: undefined; - } | { - $regularExpression: { - pattern: any; - options: any; - }; - $regex?: undefined; - $options?: undefined; - }; - inspect(): string; -} -export class BSONRuntimeError extends BSONError { -} -export class BSONSymbol extends BSONValue { - static fromExtendedJSON(doc: any): BSONSymbol; - constructor(value: any); - get _bsontype(): string; - value: any; - valueOf(): any; - toString(): any; - inspect(): string; - toJSON(): any; - toExtendedJSON(): { - $symbol: any; - }; -} -export const BSONType: Readonly<{ - double: 1; - string: 2; - object: 3; - array: 4; - binData: 5; - undefined: 6; - objectId: 7; - bool: 8; - date: 9; - null: 10; - regex: 11; - dbPointer: 12; - javascript: 13; - symbol: 14; - javascriptWithScope: 15; - int: 16; - timestamp: 17; - long: 18; - decimal: 19; - minKey: -1; - maxKey: 127; -}>; -export class BSONValue { -} -export class BSONVersionError extends BSONError { - constructor(); -} -export class Binary extends BSONValue { - static fromExtendedJSON(doc: any, options: any): Binary; - constructor(buffer: any, subType: any); - get _bsontype(): string; - sub_type: any; - buffer: any; - position: any; - put(byteValue: any): void; - write(sequence: any, offset: any): void; - read(position: any, length: any): any; - value(asRaw: any): any; - length(): any; - toJSON(): any; - toString(encoding: any): any; - toExtendedJSON(options: any): { - $binary: any; - $type: string; - } | { - $binary: { - base64: any; - subType: string; - }; - $type?: undefined; - }; - toUUID(): UUID; - inspect(): string; -} -export namespace Binary { - let BSON_BINARY_SUBTYPE_DEFAULT: number; - let BUFFER_SIZE: number; - let SUBTYPE_DEFAULT: number; - let SUBTYPE_FUNCTION: number; - let SUBTYPE_BYTE_ARRAY: number; - let SUBTYPE_UUID_OLD: number; - let SUBTYPE_UUID: number; - let SUBTYPE_MD5: number; - let SUBTYPE_ENCRYPTED: number; - let SUBTYPE_COLUMN: number; - let SUBTYPE_USER_DEFINED: number; -} -export class Code extends BSONValue { - static fromExtendedJSON(doc: any): Code; - constructor(code: any, scope: any); - get _bsontype(): string; - code: any; - scope: any; - toJSON(): { - code: any; - scope: any; - } | { - code: any; - scope?: undefined; - }; - toExtendedJSON(): { - $code: any; - $scope: any; - } | { - $code: any; - $scope?: undefined; - }; - inspect(): string; -} -export class DBRef extends BSONValue { - static fromExtendedJSON(doc: any): DBRef; - constructor(collection: any, oid: any, db: any, fields: any); - get _bsontype(): string; - collection: any; - oid: any; - db: any; - fields: any; - set namespace(value: any); - get namespace(): any; - toJSON(): any; - toExtendedJSON(options: any): { - $ref: any; - $id: any; - }; - inspect(): string; -} -export class Decimal128 extends BSONValue { - static fromString(representation: any): Decimal128; - static fromExtendedJSON(doc: any): Decimal128; - constructor(bytes: any); - get _bsontype(): string; - bytes: any; - toJSON(): { - $numberDecimal: string; - }; - toExtendedJSON(): { - $numberDecimal: string; - }; - inspect(): string; -} -export class Double extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Double; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toJSON(): number; - toString(radix: any): string; - toExtendedJSON(options: any): number | { - $numberDouble: string; - }; - inspect(): string; -} -export const EJSON: any; -export class Int32 extends BSONValue { - static fromExtendedJSON(doc: any, options: any): number | Int32; - constructor(value: any); - get _bsontype(): string; - value: number; - valueOf(): number; - toString(radix: any): string; - toJSON(): number; - toExtendedJSON(options: any): number | { - $numberInt: string; - }; - inspect(): string; -} -export class Long extends BSONValue { - static fromBits(lowBits: any, highBits: any, unsigned: any): Long; - static fromInt(value: any, unsigned: any): any; - static fromNumber(value: any, unsigned: any): any; - static fromBigInt(value: any, unsigned: any): any; - static fromString(str: any, unsigned: any, radix: any): any; - static fromBytes(bytes: any, unsigned: any, le: any): Long; - static fromBytesLE(bytes: any, unsigned: any): Long; - static fromBytesBE(bytes: any, unsigned: any): Long; - static isLong(value: any): boolean; - static fromValue(val: any, unsigned: any): any; - static fromExtendedJSON(doc: any, options: any): any; - constructor(low: number, high: any, unsigned: any); - get _bsontype(): string; - get __isLong__(): boolean; - low: number; - high: number; - unsigned: boolean; - add(addend: any): Long; - and(other: any): Long; - compare(other: any): 0 | 1 | -1; - comp(other: any): 0 | 1 | -1; - divide(divisor: any): any; - div(divisor: any): any; - equals(other: any): boolean; - eq(other: any): boolean; - getHighBits(): number; - getHighBitsUnsigned(): number; - getLowBits(): number; - getLowBitsUnsigned(): number; - getNumBitsAbs(): any; - greaterThan(other: any): boolean; - gt(other: any): boolean; - greaterThanOrEqual(other: any): boolean; - gte(other: any): boolean; - ge(other: any): boolean; - isEven(): boolean; - isNegative(): boolean; - isOdd(): boolean; - isPositive(): boolean; - isZero(): boolean; - lessThan(other: any): boolean; - lt(other: any): boolean; - lessThanOrEqual(other: any): boolean; - lte(other: any): boolean; - modulo(divisor: any): Long; - mod(divisor: any): Long; - rem(divisor: any): Long; - multiply(multiplier: any): any; - mul(multiplier: any): any; - negate(): Long; - neg(): Long; - not(): Long; - notEquals(other: any): boolean; - neq(other: any): boolean; - ne(other: any): boolean; - or(other: any): Long; - shiftLeft(numBits: any): Long; - shl(numBits: any): Long; - shiftRight(numBits: any): Long; - shr(numBits: any): Long; - shiftRightUnsigned(numBits: any): Long; - shr_u(numBits: any): Long; - shru(numBits: any): Long; - subtract(subtrahend: any): Long; - sub(subtrahend: any): Long; - toInt(): number; - toNumber(): number; - toBigInt(): bigint; - toBytes(le: any): number[]; - toBytesLE(): number[]; - toBytesBE(): number[]; - toSigned(): Long; - toString(radix: any): any; - toUnsigned(): Long; - xor(other: any): Long; - eqz(): boolean; - le(other: any): boolean; - toExtendedJSON(options: any): number | { - $numberLong: any; - }; - inspect(): string; -} -export namespace Long { - let TWO_PWR_24: any; - let MAX_UNSIGNED_VALUE: Long; - let ZERO: any; - let UZERO: any; - let ONE: any; - let UONE: any; - let NEG_ONE: any; - let MAX_VALUE: Long; - let MIN_VALUE: Long; -} -export class MaxKey extends BSONValue { - static fromExtendedJSON(): MaxKey; - get _bsontype(): string; - toExtendedJSON(): { - $maxKey: number; - }; - inspect(): string; -} -export class MinKey extends BSONValue { - static fromExtendedJSON(): MinKey; - get _bsontype(): string; - toExtendedJSON(): { - $minKey: number; - }; - inspect(): string; -} -export class ObjectId extends BSONValue { - static getInc(): number; - static generate(time: any): any; - static createPk(): ObjectId; - static createFromTime(time: any): ObjectId; - static createFromHexString(hexString: any): ObjectId; - static isValid(id: any): boolean; - static fromExtendedJSON(doc: any): ObjectId; - constructor(inputId: any); - get _bsontype(): string; - __id: any; - set id(value: any); - get id(): any; - toHexString(): any; - toString(encoding: any): any; - toJSON(): any; - equals(otherId: any): any; - getTimestamp(): Date; - toExtendedJSON(): { - $oid: any; - }; - inspect(): string; - [kId]: any; -} -export namespace ObjectId { - let index: number; -} -export class Timestamp extends Long { - static fromInt(value: any): Timestamp; - static fromNumber(value: any): Timestamp; - static fromBits(lowBits: any, highBits: any): Timestamp; - static fromString(str: any, optRadix: any): Timestamp; - static fromExtendedJSON(doc: any): Timestamp; - constructor(low: any); - toJSON(): { - $timestamp: any; - }; - toExtendedJSON(): { - $timestamp: { - t: number; - i: number; - }; - }; -} -export namespace Timestamp { - import MAX_VALUE_1 = Long.MAX_UNSIGNED_VALUE; - export { MAX_VALUE_1 as MAX_VALUE }; -} -export class UUID extends Binary { - static generate(): any; - static isValid(input: any): boolean; - static createFromHexString(hexString: any): UUID; - constructor(input: any); - __id: any; - set id(value: any); - get id(): any; - toHexString(includeDashes?: boolean): any; - equals(otherId: any): any; - toBinary(): Binary; -} -export function calculateObjectSize(object: any, options?: {}): number; -export function deserialize(buffer: any, options?: {}): {}; -export function deserializeStream(data: any, startIndex: any, numberOfDocuments: any, documents: any, docStartIndex: any, options: any): any; -export function serialize(object: any, options?: {}): any; -export function serializeWithBufferAndIndex(object: any, finalBuffer: any, options?: {}): number; -export function setInternalBufferSize(size: any): void; -declare const kId: unique symbol; -export { bson as BSON }; diff --git a/src/extras/dist/src/extras/struct/datastructures/index.d.ts b/src/extras/dist/src/extras/struct/datastructures/index.d.ts deleted file mode 100644 index 07efe2c4..00000000 --- a/src/extras/dist/src/extras/struct/datastructures/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './DataStructures'; -export * from './DataTablet'; -export * as DS from './DataStructures'; diff --git a/src/extras/dist/src/extras/struct/genTimestamps.d.ts b/src/extras/dist/src/extras/struct/genTimestamps.d.ts deleted file mode 100644 index 69253e3d..00000000 --- a/src/extras/dist/src/extras/struct/genTimestamps.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type TimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' | 'decade' | 'century' | 'millennium' | 'microsecond' | 'nanosecond'; -type Plural = `${T}s`; -export type TimeSpecifier = `now` | `last ${string} ${Plural}` | `last ${TimeUnit}`; -export declare let defaultSpecifiers: (TimeUnit | "now")[]; -export declare function genTimeSpecifiers(specifiers?: (TimeUnit | "now")[]): string[]; -export declare function genTimestampFromString(specifier: TimeSpecifier): number; -export {}; diff --git a/src/extras/dist/src/loaders/methodstrings.d.ts b/src/extras/dist/src/loaders/methodstrings.d.ts deleted file mode 100644 index 978aabc8..00000000 --- a/src/extras/dist/src/loaders/methodstrings.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function methodstrings(node: any): void; diff --git a/src/extras/dist/src/services/router/Router.d.ts b/src/extras/dist/src/services/router/Router.d.ts deleted file mode 100644 index 3d6e0348..00000000 --- a/src/extras/dist/src/services/router/Router.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { Graph, GraphNode } from "../../core/Graph"; -import { Service, ServiceOptions } from "../Service"; -export type User = { - _id: string; - send: (...args: any[]) => any; - request: (...args: any[]) => Promise | Promise[] | undefined; - post: (...args: any[]) => void; - run: (...args: any[]) => Promise | Promise[] | undefined; - subscribe: (...args: any[]) => Promise | Promise[] | undefined; - unsubscribe: (...args: any[]) => Promise | Promise[] | undefined; - sendAll?: (...args: any[]) => any; - requestAll?: (...args: any[]) => Promise | undefined; - postAll?: (...args: any[]) => void; - runAll?: (...args: any[]) => Promise | undefined; - subscribeAll?: (...args: any[]) => Promise | undefined; - unsubscribeAll?: (...args: any[]) => Promise | undefined; - terminate: (...args: any[]) => boolean; - onmessage?: (...args: any[]) => void; - onerror?: (...args: any[]) => void; - onclose?: ((user: User) => void) | ((...args: any[]) => void); - [key: string]: any; -}; -export type ConnectionProps = { - connection: GraphNode | Graph | { - [key: string]: any; - } | string; - service?: string | Graph | Service; - source?: string; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type ConnectionInfo = { - connection: GraphNode | Graph | { - [key: string]: any; - }; - service?: string | Service | Graph; - _id: string; - source: string; - connectionType?: string; - connectionsKey?: string; - send?: (message: any, ...a: any[]) => any; - request?: (message: any, method?: any, ...a: any[]) => Promise | Promise[]; - post?: (route: any, args?: any, method?: string, ...a: any[]) => void; - run?: (route: any, args?: any, method?: string, ...a: any[]) => Promise | Promise[]; - subscribe?: (route: any, callback?: ((res: any) => void) | string, ...a: any[]) => Promise | undefined; - unsubscribe?: (route: any, sub: number, ...arrayBuffer: any[]) => Promise | Promise[]; - terminate: (...a: any[]) => boolean; - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; -}; -export type RouterOptions = { - graph?: { - [key: string]: Service | Graph | any | { - service: Service | Graph | any; - connections: string[] | { - [key: string]: any; - }; - config?: { - [key: string]: { - _id?: string; - source?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - [key: string]: any; - }; - }; - }; - }; - timeout?: number; - order?: string[]; - [key: string]: any; -} & ServiceOptions; -export declare class Router extends Service { - name: string; - connections: { - [key: string]: ConnectionInfo; - }; - sources: { - [key: string]: { - [key: string]: ConnectionInfo; - }; - }; - services: { - [key: string]: Service; - }; - serviceConnections: { - [key: string]: { - [key: string]: { - [key: string]: any; - }; - }; - }; - users: { - [key: string]: User; - }; - userTimeout: number; - order: string[]; - constructor(options?: RouterOptions); - addUser: (info: { - _id: string; - } & { - onclose?: (connection: ConnectionInfo, ...args: any[]) => void; - }, connections?: { - [key: string]: string | ConnectionInfo | ConnectionProps; - }, config?: { - [key: string]: { - [key: string]: any; - service: Service; - _id?: string; - onclose?: (c: ConnectionInfo, ...args: any[]) => void; - args?: any[]; - }; - }, receiving?: boolean) => Promise; - removeUser(profile: string | User | { - _id: string; - [key: string]: any; - }, terminate?: boolean): boolean; - getConnection: (sourceId: string, hasMethod?: string, connectionId?: string) => User | ConnectionInfo | undefined; - getConnections: (sourceId: string, hasMethod?: string, props?: {}) => {}; - runConnection: (userId: string, method: 'run' | 'post' | 'subscribe' | 'unsubscribe' | 'terminate' | 'send' | 'request' | 'runAll' | 'postAll' | 'subscribeAll' | 'unsubscribeAll' | 'sendAll' | 'requestAll', args: any[], connectionId?: string) => Promise; - subscribeThroughConnection: (route: string, remoteRelay: string | ConnectionInfo, remoteEndpoint: string, callback: string | ((res: any) => void), ...args: any[]) => Promise; - addConnection: (options: ConnectionProps | ConnectionInfo | string, source?: string, autoRemove?: boolean) => ConnectionInfo; - removeConnection: (connection: string | ConnectionInfo | { - [key: string]: any; - _id: string; - }, terminate?: boolean) => boolean; - routeService: (service: Service, connections?: any, source?: string, order?: string[]) => void; - addServiceConnections: (service: Service | string, connectionsKey: any, source?: string) => {}; - openConnection: (service: string | Service, options: { - [key: string]: any; - }, source?: string, ...args: any[]) => Promise; - terminate: (connection: string | ConnectionInfo) => boolean; - routeConnections: (route: string, transmitter: string | ConnectionInfo, receiver: string | ConnectionInfo, ...args: any[]) => Promise; - setUserData: (user: string | User, data: string | { - [key: string]: any; - }) => boolean; -} -export declare function connectionHasId(connection: { - _id?: string; - [key: string]: any; -}, timeout?: number): Promise; diff --git a/src/extras/dist/src/services/utils.d.ts b/src/extras/dist/src/services/utils.d.ts deleted file mode 100644 index 9efee154..00000000 --- a/src/extras/dist/src/services/utils.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export declare let recursivelyStringifyFunctions: (obj: { - [key: string]: any; -}) => {}; -export declare function getFnParamNames(fn: any): any; -export declare let getFunctionHead: (methodString: any) => any; -export declare function parseFunctionFromText(method?: string): any; -export declare function reconstructObject(json?: string | { - [x: string]: any; -}): any; -export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyWithFunctionsAndCircularRefs: (obj: any, space?: any) => string; -export declare const stringifyFast: (obj: any, space?: any) => string; diff --git a/src/extras/storage/BFS_GDrive.ts b/src/extras/storage/BFS_GDrive.ts deleted file mode 100644 index ab9dcfdb..00000000 --- a/src/extras/storage/BFS_GDrive.ts +++ /dev/null @@ -1,669 +0,0 @@ - -import { fs, fsInited, initFS } from "./BFSUtils"; - -declare var window; - - - -export class GDrive { - //------------------------ - //-GOOGLE DRIVE FUNCTIONS- - //------------------------ - - google = (window as any).google; - gapi = (window as any).gapi; - tokenClient = (window as any).tokenClient; - gapiInited = this.gapi !== undefined; - gsiInited = this.google !== undefined; - isLoggedIn = false; - previousPageTokens = [] as any[]; - nextPageToken: any; previousPageToken:any; currentFolderId; - container:any; - - directory = "Graphscript" - fs = fs; - - constructor(apiKey?, googleClientId?) { - if(apiKey && googleClientId) - this.initGapi(apiKey, googleClientId); - } - - //this is deprecated now?: https://developers.google.com/identity/gsi/web/guides/overview - initGapi = async ( - apiKey:string, - googleClientID:string - ) => { - - return new Promise(async (resolve,rej) => { - - //console.log('initializing gapi'); - - const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'; - const SCOPES = 'https://www.googleapis.com/auth/drive'; - this.gapiInited = false; - this.gsiInited = false; - - - await Promise.all( - [new Promise((res) => { - const initializeGapiClient = async () => { - await this.gapi.client.init({ - apiKey: apiKey, - discoveryDocs: [DISCOVERY_DOC], - }); - this.gapiInited = true; - //console.log('gapi', window.gapi); - } - - const gapiLoaded = () => { - this.gapi = window.gapi; - this.gapi.load('client', initializeGapiClient); - } - - const script1 = document.createElement('script'); - script1.type = "text/javascript"; - script1.src = "https://apis.google.com/js/api.js"; - script1.async = true; - script1.defer = true; - script1.onload = gapiLoaded; - document.head.appendChild(script1); - - }), - new Promise((res) => { - - const gsiLoaded =() => { - this.google = window.google; - this.tokenClient = this.google.accounts.oauth2.initTokenClient({ - client_id: googleClientID, - scope: SCOPES, - callback: '', // defined later - }); - this.gsiInited = true; - //console.log('google', window.google) - res(true); - } - - const script2 = document.createElement('script'); - script2.type = "text/javascript"; - script2.src = "https://accounts.google.com/gsi/client"; - script2.async = true; - script2.defer = true; - script2.onload = gsiLoaded; - document.head.appendChild(script2); - - }) - ]); - - resolve(true); - - // function updateSigninStatus(isSignedIn) { - // if (isSignedIn) { - // console.log("Signed in with Google.") - // } else { - // console.log("Signed out of Google") - // } - // } - - }) - - } - - handleUserSignIn = () => { - return new Promise(async (res,rej) => { - if(!this.tokenClient) { - console.error('Google API not found'); - return; - } - - this.tokenClient.callback = async (resp) => { - if (resp.error !== undefined) { - rej(resp); - } - this.isLoggedIn = true; - res(resp); - }; - - if (this.gapi.client.getToken() === null) { - // Prompt the user to select a Google Account and ask for consent to share their data - // when establishing a new session. - this.tokenClient.requestAccessToken({prompt: 'consent'}); - } else { - // Skip display of account chooser and consent dialog for an existing session. - this.tokenClient.requestAccessToken({prompt: ''}); - } - }); - } - - checkFolder = ( - name=this.directory, - onResponse=(result)=>{} - ) => { - return new Promise((res,rej) => { - - this.gapi.client.drive.files.list({ - q:"name='"+name+"' and mimeType='application/vnd.google-apps.folder'", - }).then((response) => { - if(response.result.files.length === 0) { - this.createDriveFolder(); - if(onResponse) onResponse(response.result); - res(response.result as any); - } - else if(onResponse) onResponse(response.result); - res(response.result as any); - }); - }) - } - - createDriveFolder = ( - name=this.directory - ) => { - return new Promise((res,rej) => { - if(this.isLoggedIn) { - let data = new Object() as any; - data.name = name; - data.mimeType = "application/vnd.google-apps.folder"; - this.gapi.client.drive.files.create({'resource': data}).then((response)=>{ - console.log("Created Folder:",response.result); - res(response.result as any); - }); - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - res(await this.createDriveFolder(name)); //rerun - } - }); - } - }); - } - - async listFolders(directory = this.directory, parent='parents') { - try { - const response = await this.gapi.client.drive.files.list({ - q: `'${directory}' in ${parent} and mimeType='application/vnd.google-apps.folder'`, - fields: 'nextPageToken, files(id, name, mimeType)' - }); - return response.result.files || []; - } catch (error) { - console.error('Error listing folders:', error); - throw error; - } - } - - - async getFileMetadata(fileId) { - try { - const response = await this.gapi.client.drive.files.get({ - fileId, - fields: 'id, name, mimeType, parents', - }); - return response.result; - } catch (error) { - console.error('Error getting file metadata:', error); - throw error; - } - } - - async getFolderId(folderName, parentFolder = 'root') { - try { - const query = `mimeType='application/vnd.google-apps.folder' and name='${folderName}' ${parentFolder ? `and '${parentFolder}' ` : ``}in parents and trashed=false`; - const response = await this.gapi.client.drive.files.list({ - q: query, - fields: 'files(id, name)', - pageSize: 1 - }); - - const folder = response.result.files && response.result.files[0]; - if (folder) { - return folder.id; - } else { - console.error('Folder not found'); - return null; - } - } catch (error) { - console.error('Error getting folder ID:', error); - throw error; - } - } - - async downloadFile(fileId, mimeType) { - try { - const response = await this.gapi.client.drive.files.get({ - fileId, - alt: 'media' - }, { responseType: 'blob' }); - - const blob = new Blob([response.body], { type: mimeType }); - const link = document.createElement('a'); - link.href = URL.createObjectURL(blob); - link.download = 'downloaded_file'; - //document.body.appendChild(link); - link.click(); - //document.body.removeChild(link); - } catch (error) { - console.error('Error downloading file:', error); - throw error; - } - } - - async uploadFileToGoogleDrive( - data:Blob|string='a,b,c,1,2,3\nd,e,f,4,5,6\n', - fileName=`${new Date().toISOString()}.csv`, - mimeType='application/vnd.google-apps.spreadsheet', - directory=this.directory, - onProgress:((this: XMLHttpRequest, ev: ProgressEvent) => any) | null - ) { - - if (typeof data === 'string') { - const type = fileName.endsWith('.csv') ? 'text/csv' : 'text/plain'; - data = new Blob([data], { type }); - } - - const metadata = { - 'name': fileName, - 'mimeType': mimeType, - 'parents': [directory], // upload to the current directory - }; - - const form = new FormData(); - form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' })); - form.append('file', data); - - const xhr = new XMLHttpRequest(); - xhr.open('POST', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'); - - const token = this.gapi.auth.getToken().access_token; - xhr.setRequestHeader('Authorization', 'Bearer ' + token); - - xhr.upload.onprogress = onProgress; - - return new Promise((resolve, reject) => { - xhr.onload = () => { - if (xhr.status === 200) { - resolve(JSON.parse(xhr.responseText)); - } else { - reject(xhr.responseText); - } - }; - xhr.onerror = () => reject(xhr.statusText); - xhr.send(form); - }); - } - - // Add this method to your GDrive class - async uploadFiles( - files:{name:string,mimeType:string,data:Blob|string}[], - directory=this.directory, - uploadProgress:HTMLProgressElement|string, - defaultBrowser=false - ) { - if(typeof uploadProgress === 'string') uploadProgress = document.getElementById('upload-progress') as HTMLProgressElement; - if(uploadProgress) uploadProgress.style.display = 'block'; - - for (let i = 0; i < files.length; i++) { - const file = files[i]; - try { - await this.uploadFileToGoogleDrive( - file.data, - file.name, - file.mimeType, - directory, - (progressEvent) => { - const progress = (progressEvent.loaded / progressEvent.total) * 100; - (uploadProgress as HTMLProgressElement).value = progress; - } - ); - if(uploadProgress) uploadProgress.value = 0; // Reset the progress bar after each file is uploaded - } catch (error) { - console.error('Error uploading file:', (file as any).name, error); - } - } - - if(uploadProgress) uploadProgress.style.display = 'none'; // Hide the progress bar after all files are uploaded - if(defaultBrowser) this.updateFileList(directory, this.nextPageToken, undefined, this.container); // Refresh the file list to show the newly uploaded files - } - - - async listDriveFiles( - folderId = this.directory, - pageSize = 100, - onload?:(files)=>{}, - pageToken = null, - parentFolder?:string - ) { - - if(this.isLoggedIn) { - try { - const response = await this.gapi.client.drive.files.list({ - q: `'${folderId}' ${parentFolder ? `and '${parentFolder}' ` : ``}in parents and trashed=false`, - pageSize, - fields: 'nextPageToken, files(id, name, mimeType)', - pageToken, - }); - - if (response.result?.files && response.result.files.length > 0) { - if(onload) onload(response.result.files); - } - - return { - files: response.result.files, - nextPageToken: response.result.nextPageToken, - }; - - } catch (error) { - console.error('Error listing Drive files:', error); - throw error; - } - - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - return await this.listDriveFiles( - folderId, - pageSize, - onload, //rerun - pageToken, - parentFolder - ) - } - }); - } - } - - createFileBrowser( - container, - folderId=this.directory, - nextPageToken=this.nextPageToken, - parentFolder - ) { - if (typeof container === 'string') { - container = document.getElementById(container); - } - - if (!container) { - console.error('Container element not found'); - return; - } - this.container = container; - container.innerHTML = `
-
- - -
-
Drop files here to upload
- -
-
- - -
`; - - this.updateFileList(folderId, nextPageToken, parentFolder, container); // Initially load the root directory - this.setupDragAndDrop(folderId, nextPageToken, parentFolder, container); - this.setupUploadButton(folderId, nextPageToken, parentFolder, container); - this.setupPaginationButtons(folderId, parentFolder, container); - } - - setupUploadButton(folderId, nextPageToken, parentFolder, container) { - const uploadButton = container.querySelector('#upload-button') as HTMLButtonElement; - const fileInput = container.querySelector('#file-input') as HTMLInputElement; - - if (!uploadButton || !fileInput) { - console.error('Upload button or file input not found'); - return; - } - - uploadButton.addEventListener('click', () => { - fileInput.click(); - }); - - fileInput.addEventListener('change', async () => { - const files = fileInput.files as any; - if (files.length > 0) { - const uploadFiles = Array.from(files).map((file:any) => ({ - name: file.name, - mimeType: file.type, - data: file, - })); - - const uploadProgress = container.querySelector('#upload-progress') as HTMLProgressElement; - await this.uploadFiles(uploadFiles, this.directory, uploadProgress); - this.updateFileList(folderId, nextPageToken, parentFolder, container); - fileInput.value = ''; // Clear the file input - } - }); - } - - setupDragAndDrop(currentFolderId:string, nextPageToken, parentFolder, container:HTMLElement) { - const dropZone = container.querySelector('#drop-zone'); - if (!dropZone) { - console.error('Drop zone element not found'); - return; - } - - dropZone.addEventListener('dragover', (e) => { - e.preventDefault(); - e.stopPropagation(); - dropZone.classList.add('highlight'); - }); - - dropZone.addEventListener('dragleave', (e) => { - e.preventDefault(); - e.stopPropagation(); - dropZone.classList.remove('highlight'); - }); - - dropZone.addEventListener('drop', async (e:any) => { - e.preventDefault(); - e.stopPropagation(); - dropZone.classList.remove('highlight'); - - const files = e.dataTransfer.files; - if (files.length > 0) { - const uploadFiles = Array.from(files).map((file:any) => ({ - name: file.name, - mimeType: file.type, - data: file, - })); - - const uploadProgress = container.querySelector('#upload-progress') as HTMLProgressElement; - await this.uploadFiles(uploadFiles, this.directory, uploadProgress); - this.updateFileList(currentFolderId, nextPageToken, parentFolder, container); - } - }); - } - - async updateFileList(currentFolderId = this.directory, pageToken = null, parentFolder, container:HTMLElement) { - try { - const { files, nextPageToken } = await this.listDriveFiles(currentFolderId, 100, undefined, pageToken, parentFolder) as any; - this.renderFileList(files, currentFolderId, parentFolder, container); - - // Update the previous page token when navigating forward. - if (pageToken !== null) { - this.previousPageToken = pageToken; - } - // Update the next page token. - this.nextPageToken = nextPageToken; - // Update the visibility of the pagination buttons. - (container.querySelector('#previous-page') as any).style.display = this.previousPageToken ? 'block' : 'none'; - (container.querySelector('#next-page') as any).style.display = this.nextPageToken ? 'block' : 'none'; - } catch (error) { - console.error('Error updating file list:', error); - } - } - - - renderFileList(files, currentFolderId = this.directory, parentFolder, container:HTMLElement) { - const fileListContainer = container.querySelector('#file-list'); - const folderPathContainer = container.querySelector('#folder-path'); - - if (!fileListContainer || !folderPathContainer) { - console.error('File browser elements not found'); - return; - } - - let html = ''; - files.forEach(file => { - html += `
- ${file.name} -
`; - }); - fileListContainer.innerHTML = html; - - this.setupFileItemClick(parentFolder, container); - - if (currentFolderId !== this.directory) { - folderPathContainer.innerHTML = ``; - (container.querySelector('#parent-folder') as any).addEventListener('click', () => { - this.goBackToParentFolder(container); - }); - } else { - folderPathContainer.innerHTML = ''; - } - } - - async goBackToParentFolder(container) { - try { - const currentFolderMetadata = await this.getFileMetadata(this.currentFolderId); - if (currentFolderMetadata && currentFolderMetadata.parents && currentFolderMetadata.parents.length > 0) { - const parentFolderId = currentFolderMetadata.parents[0]; - this.updateFileList(parentFolderId, null, 'parents', container); - this.currentFolderId = parentFolderId; // Update currentFolderId - } else { - console.error('This folder does not have a parent.'); - } - } catch (error) { - console.error('Error going back to parent folder:', error); - } - } - - setupFileItemClick(parentFolder, container) { - const fileItems = container.querySelectorAll('.file-item'); - fileItems.forEach(item => { - item.addEventListener('click', async () => { - const fileId = item.getAttribute('data-id'); - const mimeType = item.getAttribute('data-mime-type'); - const fileName = item.getAttribute('data-name'); - - if (mimeType === 'application/vnd.google-apps.folder') { - this.updateFileList(fileId, null, parentFolder, container); // Updated to navigate into the folder - this.currentFolderId = fileId; // Update currentFolderId - } else { - const downloadedFile = await this.downloadFile(fileId, mimeType); - console.log('Downloaded file:', fileName, downloadedFile); - } - }); - }); - } - - - setupPaginationButtons(folderId, parentFolder, container) { - (container.querySelector('#previous-page') as any).addEventListener('click', () => { - if (this.previousPageToken !== null) { - this.updateFileList(folderId, this.previousPageToken, parentFolder, container); - // Clear the previous page token since we've navigated back. - this.previousPageToken = null; - } - }); - - (container.querySelector('#next-page') as any).addEventListener('click', () => { - if (this.nextPageToken) { - this.updateFileList(folderId, this.nextPageToken, parentFolder, container); - } - }); - } - - - //backup BFS file to drive by name (requires gapi authorization) - backupBFSToDrive = ( - bfsPath:string, - bfsDir='data', - mimeType='application/vnd.google-apps.spreadsheet' - ) => { - return new Promise(async (res,rej) => { - if(!fsInited) await initFS(['data']); - if(this.isLoggedIn){ - fs.readFile(bfsDir+'/'+bfsPath, (e,output)=>{ - if(e) throw e; if(!output) return; - let file = new Blob([output.toString()],{type:'text/csv'}); - this.checkFolder(this.directory, (result)=>{ - console.log(result); - let metadata = { - 'name':bfsPath, - 'mimeType':mimeType, - 'parents':[result.files[0].id] - } - let token = this.gapi.auth.getToken().access_token; - var form = new FormData(); - form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'})); - form.append('file', file); - - var xhr = new XMLHttpRequest(); - xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id'); - xhr.setRequestHeader('Authorization', 'Bearer ' + token); - xhr.responseType = 'json'; - xhr.onload = () => { - console.log("Uploaded file id: ",xhr.response.id); // Retrieve uploaded file ID. - //this.listDriveFiles(); - res(true); - }; - xhr.send(form); - }); - }); - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - res(await this.backupBFSToDrive(bfsPath)); //rerun - } - }); - - } - }); - - } - - - //pass a queried drive folder (i.e. from listDriveFiles) - driveToBFS = ( - file:{id:string, name:string, [key:string]:any}, //you need the file id from gdrive - bfsDir='data', - ondownload=(body)=>{}, - mimeType='text/csv' - ) => { - return new Promise((res,rej) => { - if(this.isLoggedIn) { - var request = this.gapi.client.drive.files.export({'fileId': file.id, 'mimeType':mimeType}); - request.then(async (resp) => { - let filename = file.name; - if(!fsInited) await initFS(['data']); - fs.appendFile( - '/'+bfsDir+'/'+filename, - resp.body, - (e)=>{ - if(e) throw e; - ondownload(resp.body); - res(resp.body); - }); - }); - } else { - console.error("Sign in with Google first!"); - this.handleUserSignIn().then(async () => { - if(this.isLoggedIn) { - res(await this.driveToBFS( - file, - bfsDir, //rerun - ondownload - )) - } - }); - } - }); - } - - -} - - -export const GDriveRoutes = new GDrive(); //need to call init(apiKey,clientId); \ No newline at end of file diff --git a/src/extras/storage/gdrivetest/.gitignore b/src/extras/storage/gdrivetest/.gitignore deleted file mode 100644 index ac756779..00000000 --- a/src/extras/storage/gdrivetest/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ - -dist -**/node_modules/** -**/*.pem -**/*.pfxs -**/*.key -**/*.lock -**/package-lock.json -**/*.key -**/*.log diff --git a/src/extras/storage/gdrivetest/index.css b/src/extras/storage/gdrivetest/index.css deleted file mode 100644 index d5ea5431..00000000 --- a/src/extras/storage/gdrivetest/index.css +++ /dev/null @@ -1,9 +0,0 @@ -#floatingDiv { - position: absolute; - width: 100px; - height: 100px; - background-color: red; - text-align: center; - vertical-align: middle; - line-height: 100px; /* The same as your div height */ -} \ No newline at end of file diff --git a/src/extras/storage/gdrivetest/index.html b/src/extras/storage/gdrivetest/index.html deleted file mode 100644 index a5aa66e1..00000000 --- a/src/extras/storage/gdrivetest/index.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - Google Drive File Browser - - - - -

Google Drive File Browser

-
Sign in with Google
-
- - - - - \ No newline at end of file diff --git a/src/extras/storage/gdrivetest/index.js b/src/extras/storage/gdrivetest/index.js deleted file mode 100644 index 47635f08..00000000 --- a/src/extras/storage/gdrivetest/index.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - esbuild + nodejs development server. - Begin your javascript application here. This file serves as a simplified entry point to your app, - all other scripts you want to build can stem from here if you don't want to define more entryPoints - and an outdir in the bundler settings. - - Just ctrl-A + delete all this to get started on your app. - -*/ - -import { GDrive } from '../BFS_GDrive'; - -const apiKey = 'YOUR_GOOGLE_API_KEY'; -const clientId = 'YOUR_GOOGLE_CLIENT_ID'; - -const gdrive = new GDrive(apiKey, clientId); - -const authButton = document.getElementById('auth-button'); -authButton.addEventListener('click', async () => { - try { - await gdrive.handleUserSignIn(); - authButton.style.display = 'none'; - gdrive.createFileBrowser('file-browser-container'); - } catch (error) { - console.error('Error signing in:', error); - } -}); - diff --git a/src/extras/storage/gdrivetest/package.json b/src/extras/storage/gdrivetest/package.json deleted file mode 100644 index 271c951d..00000000 --- a/src/extras/storage/gdrivetest/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "tinybuildapp7431", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \"npm run python\" \"npm start\"", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \"node tinybuild.js\" -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "", - "dependencies": { - "browserfs": "^1.4.3" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/src/extras/storage/gdrivetest/tinybuild.config.js b/src/extras/storage/gdrivetest/tinybuild.config.js deleted file mode 100644 index cf06d3b8..00000000 --- a/src/extras/storage/gdrivetest/tinybuild.config.js +++ /dev/null @@ -1,58 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.js" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:'dist' //exit point folder, define for multiple entryPoints - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files // { platform:'node' } //etc you can also supply an object here to add more specific esbuild settings - bundleTypes: false, //create .d.ts files, //you need a .tsconfig for this to work - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - //bundleIIFE:false, //create an iife build, this is compiled temporarily to create the types files and only saved with bundleIIFE:true - //bundleCommonJS:false, //cjs format outputted as .cjs - minify: true, - sourcemap: false, - //plugins:{} //custom esbuild plugins? e.g. esbuild-sass-plugin for scss support - //includeDefaultPlugins:true //true by default, includes the presets for the streaming imports, worker bundling, and auto npm install - //blobWorkers:true, //package workers as blobs or files? blobs are faster but inflate the main package size - //workerBundler:{minifyWhitespace:true} //bundler settings specific to the worker. e.g. apply platform:'node' when bundling node workers, - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } - // outputs:{ //overwrites main config settings for specific use cases - // node:{ //e.g. for bundleNode - // // external:[] //externals for node environment builds - // }, - // //commonjs:{} //bundleCommonJS - // //browser:{} - // //esm:{} - // iife:{ - // // external:[] //we only use the iife for types so it doesn't really matter if it bundles node, just note otherwise if you need iife for some obscure reason - // } - // }, - - //refer to esbuild docs for more settings - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - //redirect: 'http://localhost:8082' //instead of serving the default content, redirect ot another url e.g. another server - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - reloadscripts: false, //hot swap scripts, can break things if script handles initializations, otherwise css, link, srcs all hot swap without page reloading fairly intelligently - //delay: 50, //millisecond delay on the watch command for hot reloading - //pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - //watch: ['../'], //watch additional directories other than the current working directory - python: false,//7000, //quart server port (configured via the python server script file still) - python_node:7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: 'node_modules/tinybuild/tinybuild/node_server/other/404.html', //default error page, etc. - certpath:'node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem',//if using https, this is required. See cert.pfx.md for instructions - keypath:'node_modules/tinybuild/tinybuild/node_server/ssl/key.pem'//if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/src/extras/storage/sheets_rest.ts b/src/extras/storage/sheets_rest.ts deleted file mode 100644 index 54408e72..00000000 --- a/src/extras/storage/sheets_rest.ts +++ /dev/null @@ -1,210 +0,0 @@ - -function getOrCreateSheet(spreadsheetOptions) { - let { spreadsheetId, sheetName, accessToken } = spreadsheetOptions; - - return fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}?fields=sheets.properties`, { - headers: { - 'Authorization': `Bearer ${accessToken}` - } - }) - .then(response => { - const body = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - const sheets = body.sheets || []; - const sheet = sheets.find(s => s.properties.title === sheetName); - - if (sheet) { - return sheet.properties; - } else { - return createSheet({ spreadsheetId, sheetName, accessToken }); - } - }); -} - -function createSheet(spreadsheetOptions: { - spreadsheetId?: string; - sheetName: string; - accessToken: string; -}) { - - let { spreadsheetId, sheetName, accessToken } = spreadsheetOptions; - - const data = { - requests: [{ - addSheet: { - properties: { - title: sheetName - } - } - }] - }; - - return fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}:batchUpdate`, { - method: 'POST', - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(data) - }) - .then(response => { - const body = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - const sheet = body.replies[0].addSheet.properties; - return sheet; - }); - -} - -async function init(spreadsheetOptions: { - accessToken: string; - spreadsheetName?: string; //either - spreadsheetId?: string; //or - sheetName?: string; -}) { - if (!spreadsheetOptions.spreadsheetId) { - if (!spreadsheetOptions.spreadsheetName) { - throw new Error('Either spreadsheetId or spreadsheetName must be provided'); - } - - // Query Google Drive API to get the spreadsheet ID by name - const driveApiUrl = `https://www.googleapis.com/drive/v3/files?q=name='${spreadsheetOptions.spreadsheetName}'&mimeType='application/vnd.google-apps.spreadsheet'&fields=files(id,name)`; - const driveResponse = await fetch(driveApiUrl, { - headers: { - 'Authorization': `Bearer ${spreadsheetOptions.accessToken}` - } - }); - const driveResponseBody = typeof driveResponse.body === 'string' ? JSON.parse(driveResponse.body) : driveResponse.body; - const file = driveResponseBody.files[0]; - - if (file) { - spreadsheetOptions.spreadsheetId = file.id; - } else { - // If spreadsheet not found, create a new one - const createResponse = await fetch('https://www.googleapis.com/drive/v3/files', { - method: 'POST', - headers: { - 'Authorization': `Bearer ${spreadsheetOptions.accessToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - mimeType: 'application/vnd.google-apps.spreadsheet', - name: spreadsheetOptions.spreadsheetName, - }) - }); - let createData = await createResponse.json(); - createData = typeof createData === 'string' ? JSON.parse(createData) : createData; - spreadsheetOptions.spreadsheetId = createData.id; - } - } - - // Fetch spreadsheet to get sheets info - const sheetsResponse = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetOptions.spreadsheetId}?fields=sheets.properties`, { - headers: { - 'Authorization': `Bearer ${spreadsheetOptions.accessToken}` - } - }); - let sheetsData = await sheetsResponse.json(); - sheetsData = typeof sheetsData === 'string' ? JSON.parse(sheetsData) : sheetsData; - - if (!spreadsheetOptions.sheetName) { - if (sheetsData.sheets && sheetsData.sheets.length > 0) { - spreadsheetOptions.sheetName = sheetsData.sheets[0].properties.title; - } else { - throw new Error('No sheets found in the spreadsheet'); - } - } - - const sheetProperties = await getOrCreateSheet({ spreadsheetId: spreadsheetOptions.spreadsheetId, sheetName: spreadsheetOptions.sheetName, accessToken: spreadsheetOptions.accessToken }); - const sheetIndex = sheetProperties.sheetId; - console.log('Sheet exists or was created:', sheetProperties.title, 'with Sheet Index:', sheetIndex); -} - -async function readRange(spreadsheetOptions: { - spreadsheetId: string; - sheetName: string; - range?: string; - accessToken: string; - }): Promise { - const { spreadsheetId, sheetName, range, accessToken } = spreadsheetOptions; - - // If range is provided, use it; otherwise, default to the entire sheet - const fullRange = range ? `${sheetName}!${range}` : sheetName; - const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${fullRange}`; - const response = await fetch(url, { - headers: { - 'Authorization': `Bearer ${accessToken}` - } - }); - - if (!response.ok) { - throw new Error('Network response was not ok: ' + response.statusText); - } - - const responseBody = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - return responseBody.values || []; -} - -async function writeRange(spreadsheetOptions: { - spreadsheetId: string; - range: string; - values: any[][]; - accessToken: string; -}): Promise { - const { spreadsheetId, range, values, accessToken } = spreadsheetOptions; - - const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}:batchUpdate`; - const response = await fetch(url, { - method: 'POST', - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - valueInputOption: 'USER_ENTERED', - data: [ - { - range: range, - values: values - } - ] - }) - }); - - const responseBody = typeof response.body === 'string' ? JSON.parse(response.body) : response.body; - if (!response.ok) { - throw new Error('Network response was not ok ' + (responseBody.error?.message || response.statusText)); - } - return responseBody; -} - - -async function demo( - accessToken='YOUR_ACCESS_TOKEN', - spreadsheetName='MySpreadsheet', - sheetName='Sheet1' -) { - const spreadsheetOptions = { - accessToken, - spreadsheetName, // Either provide this... - //spreadsheetId: 'your-spreadsheet-id', // Or provide this - sheetName - } as any; - - // Initialize the spreadsheet - await init(spreadsheetOptions); - console.log('Spreadsheet initialized.'); - - // Read data from the spreadsheet - const readOptions = { ...spreadsheetOptions, range: 'A1:B2' }; - const data = await readRange(readOptions); - console.log('Data read from the spreadsheet:', data, readOptions); - - // Write data to the spreadsheet - const writeOptions = { ...spreadsheetOptions, range: 'A3', values: [['Hello', 'World'], ['How', 'are you?']] }; - await writeRange(writeOptions); - console.log('Data written to the spreadsheet.', writeOptions); -} - -// // Run the demo -// demo() -// .then(() => console.log('Demo completed successfully')) -// .catch(error => console.error('Demo failed with error:', error)); \ No newline at end of file diff --git a/src/extras/struct/datastructures/bson.cjs b/src/extras/struct/datastructures/bson.cjs deleted file mode 100644 index fb846640..00000000 --- a/src/extras/struct/datastructures/bson.cjs +++ /dev/null @@ -1,4095 +0,0 @@ -'use strict'; - -const BSON_MAJOR_VERSION = 5; -const BSON_INT32_MAX = 0x7fffffff; -const BSON_INT32_MIN = -0x80000000; -const BSON_INT64_MAX = Math.pow(2, 63) - 1; -const BSON_INT64_MIN = -Math.pow(2, 63); -const JS_INT_MAX = Math.pow(2, 53); -const JS_INT_MIN = -Math.pow(2, 53); -const BSON_DATA_NUMBER = 1; -const BSON_DATA_STRING = 2; -const BSON_DATA_OBJECT = 3; -const BSON_DATA_ARRAY = 4; -const BSON_DATA_BINARY = 5; -const BSON_DATA_UNDEFINED = 6; -const BSON_DATA_OID = 7; -const BSON_DATA_BOOLEAN = 8; -const BSON_DATA_DATE = 9; -const BSON_DATA_NULL = 10; -const BSON_DATA_REGEXP = 11; -const BSON_DATA_DBPOINTER = 12; -const BSON_DATA_CODE = 13; -const BSON_DATA_SYMBOL = 14; -const BSON_DATA_CODE_W_SCOPE = 15; -const BSON_DATA_INT = 16; -const BSON_DATA_TIMESTAMP = 17; -const BSON_DATA_LONG = 18; -const BSON_DATA_DECIMAL128 = 19; -const BSON_DATA_MIN_KEY = 0xff; -const BSON_DATA_MAX_KEY = 0x7f; -const BSON_BINARY_SUBTYPE_DEFAULT = 0; -const BSON_BINARY_SUBTYPE_UUID_NEW = 4; -const BSONType = Object.freeze({ - double: 1, - string: 2, - object: 3, - array: 4, - binData: 5, - undefined: 6, - objectId: 7, - bool: 8, - date: 9, - null: 10, - regex: 11, - dbPointer: 12, - javascript: 13, - symbol: 14, - javascriptWithScope: 15, - int: 16, - timestamp: 17, - long: 18, - decimal: 19, - minKey: -1, - maxKey: 127 -}); - -class BSONError extends Error { - get bsonError() { - return true; - } - get name() { - return 'BSONError'; - } - constructor(message) { - super(message); - } - static isBSONError(value) { - return (value != null && - typeof value === 'object' && - 'bsonError' in value && - value.bsonError === true && - 'name' in value && - 'message' in value && - 'stack' in value); - } -} -class BSONVersionError extends BSONError { - get name() { - return 'BSONVersionError'; - } - constructor() { - super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); - } -} -class BSONRuntimeError extends BSONError { - get name() { - return 'BSONRuntimeError'; - } - constructor(message) { - super(message); - } -} - -function nodejsMathRandomBytes(byteLength) { - return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); -} -const nodejsRandomBytes = (() => { - try { - return require('crypto').randomBytes; - } - catch { - return nodejsMathRandomBytes; - } -})(); -const nodeJsByteUtils = { - toLocalBufferType(potentialBuffer) { - if (Buffer.isBuffer(potentialBuffer)) { - return potentialBuffer; - } - if (ArrayBuffer.isView(potentialBuffer)) { - return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); - if (stringTag === 'ArrayBuffer' || - stringTag === 'SharedArrayBuffer' || - stringTag === '[object ArrayBuffer]' || - stringTag === '[object SharedArrayBuffer]') { - return Buffer.from(potentialBuffer); - } - throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); - }, - allocate(size) { - return Buffer.alloc(size); - }, - equals(a, b) { - return nodeJsByteUtils.toLocalBufferType(a).equals(b); - }, - fromNumberArray(array) { - return Buffer.from(array); - }, - fromBase64(base64) { - return Buffer.from(base64, 'base64'); - }, - toBase64(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); - }, - fromISO88591(codePoints) { - return Buffer.from(codePoints, 'binary'); - }, - toISO88591(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); - }, - fromHex(hex) { - return Buffer.from(hex, 'hex'); - }, - toHex(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); - }, - fromUTF8(text) { - return Buffer.from(text, 'utf8'); - }, - toUTF8(buffer) { - return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); - }, - utf8ByteLength(input) { - return Buffer.byteLength(input, 'utf8'); - }, - encodeUTF8Into(buffer, source, byteOffset) { - return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); - }, - randomBytes: nodejsRandomBytes -}; - -function isReactNative() { - const { navigator } = globalThis; - return typeof navigator === 'object' && navigator.product === 'ReactNative'; -} -function webMathRandomBytes(byteLength) { - if (byteLength < 0) { - throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); - } - return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); -} -const webRandomBytes = (() => { - const { crypto } = globalThis; - if (crypto != null && typeof crypto.getRandomValues === 'function') { - return (byteLength) => { - return crypto.getRandomValues(webByteUtils.allocate(byteLength)); - }; - } - else { - if (isReactNative()) { - const { console } = globalThis; - console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); - } - return webMathRandomBytes; - } -})(); -const HEX_DIGIT = /(\d|[a-f])/i; -const webByteUtils = { - toLocalBufferType(potentialUint8array) { - const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? - Object.prototype.toString.call(potentialUint8array); - if (stringTag === 'Uint8Array') { - return potentialUint8array; - } - if (ArrayBuffer.isView(potentialUint8array)) { - return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); - } - if (stringTag === 'ArrayBuffer' || - stringTag === 'SharedArrayBuffer' || - stringTag === '[object ArrayBuffer]' || - stringTag === '[object SharedArrayBuffer]') { - return new Uint8Array(potentialUint8array); - } - throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); - }, - allocate(size) { - if (typeof size !== 'number') { - throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); - } - return new Uint8Array(size); - }, - equals(a, b) { - if (a.byteLength !== b.byteLength) { - return false; - } - for (let i = 0; i < a.byteLength; i++) { - if (a[i] !== b[i]) { - return false; - } - } - return true; - }, - fromNumberArray(array) { - return Uint8Array.from(array); - }, - fromBase64(base64) { - return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); - }, - toBase64(uint8array) { - return btoa(webByteUtils.toISO88591(uint8array)); - }, - fromISO88591(codePoints) { - return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); - }, - toISO88591(uint8array) { - return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); - }, - fromHex(hex) { - const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); - const buffer = []; - for (let i = 0; i < evenLengthHex.length; i += 2) { - const firstDigit = evenLengthHex[i]; - const secondDigit = evenLengthHex[i + 1]; - if (!HEX_DIGIT.test(firstDigit)) { - break; - } - if (!HEX_DIGIT.test(secondDigit)) { - break; - } - const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); - buffer.push(hexDigit); - } - return Uint8Array.from(buffer); - }, - toHex(uint8array) { - return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); - }, - fromUTF8(text) { - return new TextEncoder().encode(text); - }, - toUTF8(uint8array) { - return new TextDecoder('utf8', { fatal: false }).decode(uint8array); - }, - utf8ByteLength(input) { - return webByteUtils.fromUTF8(input).byteLength; - }, - encodeUTF8Into(buffer, source, byteOffset) { - const bytes = webByteUtils.fromUTF8(source); - buffer.set(bytes, byteOffset); - return bytes.byteLength; - }, - randomBytes: webRandomBytes -}; - -const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; -const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; -class BSONDataView extends DataView { - static fromUint8Array(input) { - return new DataView(input.buffer, input.byteOffset, input.byteLength); - } -} - -const VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i; -const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); -const uuidHexStringToBuffer = (hexString) => { - if (!uuidValidateString(hexString)) { - throw new BSONError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'); - } - const sanitizedHexString = hexString.replace(/-/g, ''); - return ByteUtils.fromHex(sanitizedHexString); -}; -function bufferToUuidHexString(buffer, includeDashes = true) { - if (includeDashes) { - return [ - ByteUtils.toHex(buffer.subarray(0, 4)), - ByteUtils.toHex(buffer.subarray(4, 6)), - ByteUtils.toHex(buffer.subarray(6, 8)), - ByteUtils.toHex(buffer.subarray(8, 10)), - ByteUtils.toHex(buffer.subarray(10, 16)) - ].join('-'); - } - return ByteUtils.toHex(buffer); -} - -function isAnyArrayBuffer(value) { - return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); -} -function isUint8Array(value) { - return Object.prototype.toString.call(value) === '[object Uint8Array]'; -} -function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} -function isMap(d) { - return Object.prototype.toString.call(d) === '[object Map]'; -} -function isDate(d) { - return Object.prototype.toString.call(d) === '[object Date]'; -} - -class BSONValue { - get [Symbol.for('@@mdb.bson.version')]() { - return BSON_MAJOR_VERSION; - } -} - -class Binary extends BSONValue { - get _bsontype() { - return 'Binary'; - } - constructor(buffer, subType) { - super(); - if (!(buffer == null) && - !(typeof buffer === 'string') && - !ArrayBuffer.isView(buffer) && - !(buffer instanceof ArrayBuffer) && - !Array.isArray(buffer)) { - throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); - } - this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer == null) { - this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); - this.position = 0; - } - else { - if (typeof buffer === 'string') { - this.buffer = ByteUtils.fromISO88591(buffer); - } - else if (Array.isArray(buffer)) { - this.buffer = ByteUtils.fromNumberArray(buffer); - } - else { - this.buffer = ByteUtils.toLocalBufferType(buffer); - } - this.position = this.buffer.byteLength; - } - } - put(byteValue) { - if (typeof byteValue === 'string' && byteValue.length !== 1) { - throw new BSONError('only accepts single character String'); - } - else if (typeof byteValue !== 'number' && byteValue.length !== 1) - throw new BSONError('only accepts single character Uint8Array or Array'); - let decodedByte; - if (typeof byteValue === 'string') { - decodedByte = byteValue.charCodeAt(0); - } - else if (typeof byteValue === 'number') { - decodedByte = byteValue; - } - else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONError('only accepts number in a valid unsigned byte range 0-255'); - } - if (this.buffer.byteLength > this.position) { - this.buffer[this.position++] = decodedByte; - } - else { - const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); - newSpace.set(this.buffer, 0); - this.buffer = newSpace; - this.buffer[this.position++] = decodedByte; - } - } - write(sequence, offset) { - offset = typeof offset === 'number' ? offset : this.position; - if (this.buffer.byteLength < offset + sequence.length) { - const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); - newSpace.set(this.buffer, 0); - this.buffer = newSpace; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); - this.position = - offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } - else if (typeof sequence === 'string') { - const bytes = ByteUtils.fromISO88591(sequence); - this.buffer.set(bytes, offset); - this.position = - offset + sequence.length > this.position ? offset + sequence.length : this.position; - } - } - read(position, length) { - length = length && length > 0 ? length : this.position; - return this.buffer.slice(position, position + length); - } - value(asRaw) { - asRaw = !!asRaw; - if (asRaw && this.buffer.length === this.position) { - return this.buffer; - } - if (asRaw) { - return this.buffer.slice(0, this.position); - } - return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); - } - length() { - return this.position; - } - toJSON() { - return ByteUtils.toBase64(this.buffer); - } - toString(encoding) { - if (encoding === 'hex') - return ByteUtils.toHex(this.buffer); - if (encoding === 'base64') - return ByteUtils.toBase64(this.buffer); - if (encoding === 'utf8' || encoding === 'utf-8') - return ByteUtils.toUTF8(this.buffer); - return ByteUtils.toUTF8(this.buffer); - } - toExtendedJSON(options) { - options = options || {}; - const base64String = ByteUtils.toBase64(this.buffer); - const subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? '0' + subType : subType - }; - } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? '0' + subType : subType - } - }; - } - toUUID() { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID(this.buffer.slice(0, this.position)); - } - throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); - } - static fromExtendedJSON(doc, options) { - options = options || {}; - let data; - let type; - if ('$binary' in doc) { - if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) { - type = doc.$type ? parseInt(doc.$type, 16) : 0; - data = ByteUtils.fromBase64(doc.$binary); - } - else { - if (typeof doc.$binary !== 'string') { - type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; - data = ByteUtils.fromBase64(doc.$binary.base64); - } - } - } - else if ('$uuid' in doc) { - type = 4; - data = uuidHexStringToBuffer(doc.$uuid); - } - if (!data) { - throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); - } - return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; - } -} -Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; -Binary.BUFFER_SIZE = 256; -Binary.SUBTYPE_DEFAULT = 0; -Binary.SUBTYPE_FUNCTION = 1; -Binary.SUBTYPE_BYTE_ARRAY = 2; -Binary.SUBTYPE_UUID_OLD = 3; -Binary.SUBTYPE_UUID = 4; -Binary.SUBTYPE_MD5 = 5; -Binary.SUBTYPE_ENCRYPTED = 6; -Binary.SUBTYPE_COLUMN = 7; -Binary.SUBTYPE_USER_DEFINED = 128; -const UUID_BYTE_LENGTH = 16; -class UUID extends Binary { - constructor(input) { - let bytes; - let hexStr; - if (input == null) { - bytes = UUID.generate(); - } - else if (input instanceof UUID) { - bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); - hexStr = input.__id; - } - else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { - bytes = ByteUtils.toLocalBufferType(input); - } - else if (typeof input === 'string') { - bytes = uuidHexStringToBuffer(input); - } - else { - throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'); - } - super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); - this.__id = hexStr; - } - get id() { - return this.buffer; - } - set id(value) { - this.buffer = value; - if (UUID.cacheHexString) { - this.__id = bufferToUuidHexString(value); - } - } - toHexString(includeDashes = true) { - if (UUID.cacheHexString && this.__id) { - return this.__id; - } - const uuidHexString = bufferToUuidHexString(this.id, includeDashes); - if (UUID.cacheHexString) { - this.__id = uuidHexString; - } - return uuidHexString; - } - toString(encoding) { - if (encoding === 'hex') - return ByteUtils.toHex(this.id); - if (encoding === 'base64') - return ByteUtils.toBase64(this.id); - return this.toHexString(); - } - toJSON() { - return this.toHexString(); - } - equals(otherId) { - if (!otherId) { - return false; - } - if (otherId instanceof UUID) { - return ByteUtils.equals(otherId.id, this.id); - } - try { - return ByteUtils.equals(new UUID(otherId).id, this.id); - } - catch { - return false; - } - } - toBinary() { - return new Binary(this.id, Binary.SUBTYPE_UUID); - } - static generate() { - const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - return bytes; - } - static isValid(input) { - if (!input) { - return false; - } - if (input instanceof UUID) { - return true; - } - if (typeof input === 'string') { - return uuidValidateString(input); - } - if (isUint8Array(input)) { - if (input.byteLength !== UUID_BYTE_LENGTH) { - return false; - } - return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; - } - return false; - } - static createFromHexString(hexString) { - const buffer = uuidHexStringToBuffer(hexString); - return new UUID(buffer); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new UUID("${this.toHexString()}")`; - } -} - -class Code extends BSONValue { - get _bsontype() { - return 'Code'; - } - constructor(code, scope) { - super(); - this.code = code.toString(); - this.scope = scope ?? null; - } - toJSON() { - if (this.scope != null) { - return { code: this.code, scope: this.scope }; - } - return { code: this.code }; - } - toExtendedJSON() { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - } - static fromExtendedJSON(doc) { - return new Code(doc.$code, doc.$scope); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - const codeJson = this.toJSON(); - return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; - } -} - -function isDBRefLike(value) { - return (value != null && - typeof value === 'object' && - '$id' in value && - value.$id != null && - '$ref' in value && - typeof value.$ref === 'string' && - (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); -} -class DBRef extends BSONValue { - get _bsontype() { - return 'DBRef'; - } - constructor(collection, oid, db, fields) { - super(); - const parts = collection.split('.'); - if (parts.length === 2) { - db = parts.shift(); - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; - } - get namespace() { - return this.collection; - } - set namespace(value) { - this.collection = value; - } - toJSON() { - const o = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o.$db = this.db; - return o; - } - toExtendedJSON(options) { - options = options || {}; - let o = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o; - } - if (this.db) - o.$db = this.db; - o = Object.assign(o, this.fields); - return o; - } - static fromExtendedJSON(doc) { - const copy = Object.assign({}, doc); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc.$ref, doc.$id, doc.$db, copy); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString(); - return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ''})`; - } -} - -let wasm = undefined; -try { - wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; -} -catch { -} -const TWO_PWR_16_DBL = 1 << 16; -const TWO_PWR_24_DBL = 1 << 24; -const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; -const INT_CACHE = {}; -const UINT_CACHE = {}; -const MAX_INT64_STRING_LENGTH = 20; -const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; -class Long extends BSONValue { - get _bsontype() { - return 'Long'; - } - get __isLong__() { - return true; - } - constructor(low = 0, high, unsigned) { - super(); - if (typeof low === 'bigint') { - Object.assign(this, Long.fromBigInt(low, !!high)); - } - else if (typeof low === 'string') { - Object.assign(this, Long.fromString(low, !!high)); - } - else { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - } - static fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } - static fromInt(value, unsigned) { - let obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } - else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - } - static fromNumber(value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } - else { - if (value <= -TWO_PWR_63_DBL) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; - } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - } - static fromBigInt(value, unsigned) { - return Long.fromString(value.toString(), unsigned); - } - static fromString(str, unsigned, radix) { - if (str.length === 0) - throw new BSONError('empty string'); - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') - return Long.ZERO; - if (typeof unsigned === 'number') { - (radix = unsigned), (unsigned = false); - } - else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw new BSONError('radix'); - let p; - if ((p = str.indexOf('-')) > 0) - throw new BSONError('interior hyphen'); - else if (p === 0) { - return Long.fromString(str.substring(1), unsigned, radix).neg(); - } - const radixToPower = Long.fromNumber(Math.pow(radix, 8)); - let result = Long.ZERO; - for (let i = 0; i < str.length; i += 8) { - const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - const power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } - else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - static fromBytes(bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - } - static fromBytesLE(bytes, unsigned) { - return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned); - } - static fromBytesBE(bytes, unsigned) { - return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned); - } - static isLong(value) { - return (value != null && - typeof value === 'object' && - '__isLong__' in value && - value.__isLong__ === true); - } - static fromValue(val, unsigned) { - if (typeof val === 'number') - return Long.fromNumber(val, unsigned); - if (typeof val === 'string') - return Long.fromString(val, unsigned); - return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); - } - add(addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - const a48 = this.high >>> 16; - const a32 = this.high & 0xffff; - const a16 = this.low >>> 16; - const a00 = this.low & 0xffff; - const b48 = addend.high >>> 16; - const b32 = addend.high & 0xffff; - const b16 = addend.low >>> 16; - const b00 = addend.low & 0xffff; - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - } - and(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); - } - compare(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - const thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - } - comp(other) { - return this.compare(other); - } - divide(divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw new BSONError('division by zero'); - if (wasm) { - if (!this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1) { - return this; - } - const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - let approx, rem, res; - if (!this.unsigned) { - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - const halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } - else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } - else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } - else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } - else { - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - return Long.UONE; - res = Long.UZERO; - } - rem = this; - while (rem.gte(divisor)) { - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - const log2 = Math.ceil(Math.log(approx) / Math.LN2); - const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - let approxRes = Long.fromNumber(approx); - let approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - } - div(divisor) { - return this.divide(divisor); - } - equals(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - } - eq(other) { - return this.equals(other); - } - getHighBits() { - return this.high; - } - getHighBitsUnsigned() { - return this.high >>> 0; - } - getLowBits() { - return this.low; - } - getLowBitsUnsigned() { - return this.low >>> 0; - } - getNumBitsAbs() { - if (this.isNegative()) { - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - } - const val = this.high !== 0 ? this.high : this.low; - let bit; - for (bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - } - greaterThan(other) { - return this.comp(other) > 0; - } - gt(other) { - return this.greaterThan(other); - } - greaterThanOrEqual(other) { - return this.comp(other) >= 0; - } - gte(other) { - return this.greaterThanOrEqual(other); - } - ge(other) { - return this.greaterThanOrEqual(other); - } - isEven() { - return (this.low & 1) === 0; - } - isNegative() { - return !this.unsigned && this.high < 0; - } - isOdd() { - return (this.low & 1) === 1; - } - isPositive() { - return this.unsigned || this.high >= 0; - } - isZero() { - return this.high === 0 && this.low === 0; - } - lessThan(other) { - return this.comp(other) < 0; - } - lt(other) { - return this.lessThan(other); - } - lessThanOrEqual(other) { - return this.comp(other) <= 0; - } - lte(other) { - return this.lessThanOrEqual(other); - } - modulo(divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (wasm) { - const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - } - mod(divisor) { - return this.modulo(divisor); - } - rem(divisor) { - return this.modulo(divisor); - } - multiply(multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - if (wasm) { - const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } - else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - const a48 = this.high >>> 16; - const a32 = this.high & 0xffff; - const a16 = this.low >>> 16; - const a00 = this.low & 0xffff; - const b48 = multiplier.high >>> 16; - const b32 = multiplier.high & 0xffff; - const b16 = multiplier.low >>> 16; - const b00 = multiplier.low & 0xffff; - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - } - mul(multiplier) { - return this.multiply(multiplier); - } - negate() { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); - } - neg() { - return this.negate(); - } - not() { - return Long.fromBits(~this.low, ~this.high, this.unsigned); - } - notEquals(other) { - return !this.equals(other); - } - neq(other) { - return this.notEquals(other); - } - ne(other) { - return this.notEquals(other); - } - or(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); - } - shiftLeft(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return Long.fromBits(0, this.low << (numBits - 32), this.unsigned); - } - shl(numBits) { - return this.shiftLeft(numBits); - } - shiftRight(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - } - shr(numBits) { - return this.shiftRight(numBits); - } - shiftRightUnsigned(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - const high = this.high; - if (numBits < 32) { - const low = this.low; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } - else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - } - shr_u(numBits) { - return this.shiftRightUnsigned(numBits); - } - shru(numBits) { - return this.shiftRightUnsigned(numBits); - } - subtract(subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); - } - sub(subtrahend) { - return this.subtract(subtrahend); - } - toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - } - toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - } - toBigInt() { - return BigInt(this.toString()); - } - toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - } - toBytesLE() { - const hi = this.high, lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24 - ]; - } - toBytesBE() { - const hi = this.high, lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - } - toSigned() { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); - } - toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw new BSONError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { - if (this.eq(Long.MIN_VALUE)) { - const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } - else - return '-' + this.neg().toString(radix); - } - const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - let rem = this; - let result = ''; - while (true) { - const remDiv = rem.div(radixToPower); - const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - let digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - } - toUnsigned() { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - } - xor(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - } - eqz() { - return this.isZero(); - } - le(other) { - return this.lessThanOrEqual(other); - } - toExtendedJSON(options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; - } - static fromExtendedJSON(doc, options) { - const { useBigInt64 = false, relaxed = true } = { ...options }; - if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { - throw new BSONError('$numberLong string is too long'); - } - if (!DECIMAL_REG_EX.test(doc.$numberLong)) { - throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); - } - if (useBigInt64) { - const bigIntResult = BigInt(doc.$numberLong); - return BigInt.asIntN(64, bigIntResult); - } - const longResult = Long.fromString(doc.$numberLong); - if (relaxed) { - return longResult.toNumber(); - } - return longResult; - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; - } -} -Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); -Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); -Long.ZERO = Long.fromInt(0); -Long.UZERO = Long.fromInt(0, true); -Long.ONE = Long.fromInt(1); -Long.UONE = Long.fromInt(1, true); -Long.NEG_ONE = Long.fromInt(-1); -Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); - -const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; -const EXPONENT_MAX = 6111; -const EXPONENT_MIN = -6176; -const EXPONENT_BIAS = 6176; -const MAX_DIGITS = 34; -const NAN_BUFFER = ByteUtils.fromNumberArray([ - 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse()); -const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ - 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse()); -const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ - 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -].reverse()); -const EXPONENT_REGEX = /^([-+])?(\d+)?$/; -const COMBINATION_MASK = 0x1f; -const EXPONENT_MASK = 0x3fff; -const COMBINATION_INFINITY = 30; -const COMBINATION_NAN = 31; -function isDigit(value) { - return !isNaN(parseInt(value, 10)); -} -function divideu128(value) { - const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - let _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (let i = 0; i <= 3; i++) { - _rem = _rem.shiftLeft(32); - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); - } - return { quotient: value, rem: _rem }; -} -function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - const leftHigh = left.shiftRightUnsigned(32); - const leftLow = new Long(left.getLowBits(), 0); - const rightHigh = right.shiftRightUnsigned(32); - const rightLow = new Long(right.getLowBits(), 0); - let productHigh = leftHigh.multiply(rightHigh); - let productMid = leftHigh.multiply(rightLow); - const productMid2 = leftLow.multiply(rightHigh); - let productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - return { high: productHigh, low: productLow }; -} -function lessThan(left, right) { - const uhleft = left.high >>> 0; - const uhright = right.high >>> 0; - if (uhleft < uhright) { - return true; - } - else if (uhleft === uhright) { - const ulleft = left.low >>> 0; - const ulright = right.low >>> 0; - if (ulleft < ulright) - return true; - } - return false; -} -function invalidErr(string, message) { - throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); -} -class Decimal128 extends BSONValue { - get _bsontype() { - return 'Decimal128'; - } - constructor(bytes) { - super(); - if (typeof bytes === 'string') { - this.bytes = Decimal128.fromString(bytes).bytes; - } - else if (isUint8Array(bytes)) { - if (bytes.byteLength !== 16) { - throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); - } - this.bytes = bytes; - } - else { - throw new BSONError('Decimal128 must take a Buffer or string'); - } - } - static fromString(representation) { - let isNegative = false; - let sawRadix = false; - let foundNonZero = false; - let significantDigits = 0; - let nDigitsRead = 0; - let nDigits = 0; - let radixPosition = 0; - let firstNonZero = 0; - const digits = [0]; - let nDigitsStored = 0; - let digitsInsert = 0; - let firstDigit = 0; - let lastDigit = 0; - let exponent = 0; - let i = 0; - let significandHigh = new Long(0, 0); - let significandLow = new Long(0, 0); - let biasedExponent = 0; - let index = 0; - if (representation.length >= 7000) { - throw new BSONError('' + representation + ' not a valid Decimal128 string'); - } - const stringMatch = representation.match(PARSE_STRING_REGEXP); - const infMatch = representation.match(PARSE_INF_REGEXP); - const nanMatch = representation.match(PARSE_NAN_REGEXP); - if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { - throw new BSONError('' + representation + ' not a valid Decimal128 string'); - } - if (stringMatch) { - const unsignedNumber = stringMatch[2]; - const e = stringMatch[4]; - const expSign = stringMatch[5]; - const expNumber = stringMatch[6]; - if (e && expNumber === undefined) - invalidErr(representation, 'missing exponent power'); - if (e && unsignedNumber === undefined) - invalidErr(representation, 'missing exponent base'); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, 'missing e before exponent'); - } - } - if (representation[index] === '+' || representation[index] === '-') { - isNegative = representation[index++] === '-'; - } - if (!isDigit(representation[index]) && representation[index] !== '.') { - if (representation[index] === 'i' || representation[index] === 'I') { - return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); - } - else if (representation[index] === 'N') { - return new Decimal128(NAN_BUFFER); - } - } - while (isDigit(representation[index]) || representation[index] === '.') { - if (representation[index] === '.') { - if (sawRadix) - invalidErr(representation, 'contains multiple periods'); - sawRadix = true; - index = index + 1; - continue; - } - if (nDigitsStored < 34) { - if (representation[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - digits[digitsInsert++] = parseInt(representation[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONError('' + representation + ' not a valid Decimal128 string'); - if (representation[index] === 'e' || representation[index] === 'E') { - const match = representation.substr(++index).match(EXPONENT_REGEX); - if (!match || !match[2]) - return new Decimal128(NAN_BUFFER); - exponent = parseInt(match[0], 10); - index = index + match[0].length; - } - if (representation[index]) - return new Decimal128(NAN_BUFFER); - firstDigit = 0; - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } - else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (digits[firstNonZero + significantDigits - 1] === 0) { - significantDigits = significantDigits - 1; - } - } - } - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } - else { - exponent = exponent - radixPosition; - } - while (exponent > EXPONENT_MAX) { - lastDigit = lastDigit + 1; - if (lastDigit - firstDigit > MAX_DIGITS) { - const digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - exponent = exponent - 1; - } - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - nDigits = nDigits - 1; - } - else { - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } - else { - const digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, 'overflow'); - } - } - if (lastDigit - firstDigit + 1 < significantDigits) { - let endOfString = nDigitsRead; - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - if (isNegative) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - let roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(representation[i], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - let dIdx = lastDigit; - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } - else { - return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); - } - } - } - } - } - } - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } - else if (lastDigit - firstDigit < 17) { - let dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - else { - let dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - biasedExponent = exponent + EXPONENT_BIAS; - const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } - else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - dec.low = significand.low; - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - const buffer = ByteUtils.allocate(16); - index = 0; - buffer[index++] = dec.low.low & 0xff; - buffer[index++] = (dec.low.low >> 8) & 0xff; - buffer[index++] = (dec.low.low >> 16) & 0xff; - buffer[index++] = (dec.low.low >> 24) & 0xff; - buffer[index++] = dec.low.high & 0xff; - buffer[index++] = (dec.low.high >> 8) & 0xff; - buffer[index++] = (dec.low.high >> 16) & 0xff; - buffer[index++] = (dec.low.high >> 24) & 0xff; - buffer[index++] = dec.high.low & 0xff; - buffer[index++] = (dec.high.low >> 8) & 0xff; - buffer[index++] = (dec.high.low >> 16) & 0xff; - buffer[index++] = (dec.high.low >> 24) & 0xff; - buffer[index++] = dec.high.high & 0xff; - buffer[index++] = (dec.high.high >> 8) & 0xff; - buffer[index++] = (dec.high.high >> 16) & 0xff; - buffer[index++] = (dec.high.high >> 24) & 0xff; - return new Decimal128(buffer); - } - toString() { - let biased_exponent; - let significand_digits = 0; - const significand = new Array(36); - for (let i = 0; i < significand.length; i++) - significand[i] = 0; - let index = 0; - let is_zero = false; - let significand_msb; - let significand128 = { parts: [0, 0, 0, 0] }; - let j, k; - const string = []; - index = 0; - const buffer = this.bytes; - const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - index = 0; - const dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - const combination = (high >> 26) & COMBINATION_MASK; - if (combination >> 3 === 3) { - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } - else if (combination === COMBINATION_NAN) { - return 'NaN'; - } - else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } - else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - const exponent = biased_exponent - EXPONENT_BIAS; - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0) { - is_zero = true; - } - else { - for (k = 3; k >= 0; k--) { - let least_digits = 0; - const result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - if (!least_digits) - continue; - for (j = 8; j >= 0; j--) { - significand[k * 9 + j] = least_digits % 10; - least_digits = Math.floor(least_digits / 10); - } - } - } - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } - else { - significand_digits = 36; - while (!significand[index]) { - significand_digits = significand_digits - 1; - index = index + 1; - } - } - const scientific_exponent = significand_digits - 1 + exponent; - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - if (significand_digits > 34) { - string.push(`${0}`); - if (exponent > 0) - string.push(`E+${exponent}`); - else if (exponent < 0) - string.push(`E${exponent}`); - return string.join(''); - } - string.push(`${significand[index++]}`); - significand_digits = significand_digits - 1; - if (significand_digits) { - string.push('.'); - } - for (let i = 0; i < significand_digits; i++) { - string.push(`${significand[index++]}`); - } - string.push('E'); - if (scientific_exponent > 0) { - string.push(`+${scientific_exponent}`); - } - else { - string.push(`${scientific_exponent}`); - } - } - else { - if (exponent >= 0) { - for (let i = 0; i < significand_digits; i++) { - string.push(`${significand[index++]}`); - } - } - else { - let radix_position = significand_digits + exponent; - if (radix_position > 0) { - for (let i = 0; i < radix_position; i++) { - string.push(`${significand[index++]}`); - } - } - else { - string.push('0'); - } - string.push('.'); - while (radix_position++ < 0) { - string.push('0'); - } - for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(`${significand[index++]}`); - } - } - } - return string.join(''); - } - toJSON() { - return { $numberDecimal: this.toString() }; - } - toExtendedJSON() { - return { $numberDecimal: this.toString() }; - } - static fromExtendedJSON(doc) { - return Decimal128.fromString(doc.$numberDecimal); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Decimal128("${this.toString()}")`; - } -} - -class Double extends BSONValue { - get _bsontype() { - return 'Double'; - } - constructor(value) { - super(); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; - } - valueOf() { - return this.value; - } - toJSON() { - return this.value; - } - toString(radix) { - return this.value.toString(radix); - } - toExtendedJSON(options) { - if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { - return this.value; - } - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: '-0.0' }; - } - return { - $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() - }; - } - static fromExtendedJSON(doc, options) { - const doubleValue = parseFloat(doc.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - const eJSON = this.toExtendedJSON(); - return `new Double(${eJSON.$numberDouble})`; - } -} - -class Int32 extends BSONValue { - get _bsontype() { - return 'Int32'; - } - constructor(value) { - super(); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value | 0; - } - valueOf() { - return this.value; - } - toString(radix) { - return this.value.toString(radix); - } - toJSON() { - return this.value; - } - toExtendedJSON(options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; - } - static fromExtendedJSON(doc, options) { - return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Int32(${this.valueOf()})`; - } -} - -class MaxKey extends BSONValue { - get _bsontype() { - return 'MaxKey'; - } - toExtendedJSON() { - return { $maxKey: 1 }; - } - static fromExtendedJSON() { - return new MaxKey(); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return 'new MaxKey()'; - } -} - -class MinKey extends BSONValue { - get _bsontype() { - return 'MinKey'; - } - toExtendedJSON() { - return { $minKey: 1 }; - } - static fromExtendedJSON() { - return new MinKey(); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return 'new MinKey()'; - } -} - -const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); -let PROCESS_UNIQUE = null; -const kId = Symbol('id'); -class ObjectId extends BSONValue { - get _bsontype() { - return 'ObjectId'; - } - constructor(inputId) { - super(); - let workingId; - if (typeof inputId === 'object' && inputId && 'id' in inputId) { - if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { - throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); - } - if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { - workingId = ByteUtils.fromHex(inputId.toHexString()); - } - else { - workingId = inputId.id; - } - } - else { - workingId = inputId; - } - if (workingId == null || typeof workingId === 'number') { - this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); - } - else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this[kId] = ByteUtils.toLocalBufferType(workingId); - } - else if (typeof workingId === 'string') { - if (workingId.length === 12) { - const bytes = ByteUtils.fromUTF8(workingId); - if (bytes.byteLength === 12) { - this[kId] = bytes; - } - else { - throw new BSONError('Argument passed in must be a string of 12 bytes'); - } - } - else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { - this[kId] = ByteUtils.fromHex(workingId); - } - else { - throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); - } - } - else { - throw new BSONError('Argument passed in does not match the accepted types'); - } - if (ObjectId.cacheHexString) { - this.__id = ByteUtils.toHex(this.id); - } - } - get id() { - return this[kId]; - } - set id(value) { - this[kId] = value; - if (ObjectId.cacheHexString) { - this.__id = ByteUtils.toHex(value); - } - } - toHexString() { - if (ObjectId.cacheHexString && this.__id) { - return this.__id; - } - const hexString = ByteUtils.toHex(this.id); - if (ObjectId.cacheHexString && !this.__id) { - this.__id = hexString; - } - return hexString; - } - static getInc() { - return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); - } - static generate(time) { - if ('number' !== typeof time) { - time = Math.floor(Date.now() / 1000); - } - const inc = ObjectId.getInc(); - const buffer = ByteUtils.allocate(12); - BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = ByteUtils.randomBytes(5); - } - buffer[4] = PROCESS_UNIQUE[0]; - buffer[5] = PROCESS_UNIQUE[1]; - buffer[6] = PROCESS_UNIQUE[2]; - buffer[7] = PROCESS_UNIQUE[3]; - buffer[8] = PROCESS_UNIQUE[4]; - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - return buffer; - } - toString(encoding) { - if (encoding === 'base64') - return ByteUtils.toBase64(this.id); - if (encoding === 'hex') - return this.toHexString(); - return this.toHexString(); - } - toJSON() { - return this.toHexString(); - } - equals(otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (otherId instanceof ObjectId) { - return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); - } - if (typeof otherId === 'string' && - ObjectId.isValid(otherId) && - otherId.length === 12 && - isUint8Array(this.id)) { - return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) { - return ByteUtils.equals(ByteUtils.fromUTF8(otherId), this.id); - } - if (typeof otherId === 'object' && - 'toHexString' in otherId && - typeof otherId.toHexString === 'function') { - const otherIdString = otherId.toHexString(); - const thisIdString = this.toHexString().toLowerCase(); - return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString; - } - return false; - } - getTimestamp() { - const timestamp = new Date(); - const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - } - static createPk() { - return new ObjectId(); - } - static createFromTime(time) { - const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); - return new ObjectId(buffer); - } - static createFromHexString(hexString) { - if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { - throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - return new ObjectId(ByteUtils.fromHex(hexString)); - } - static isValid(id) { - if (id == null) - return false; - try { - new ObjectId(id); - return true; - } - catch { - return false; - } - } - toExtendedJSON() { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString('hex') }; - } - static fromExtendedJSON(doc) { - return new ObjectId(doc.$oid); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new ObjectId("${this.toHexString()}")`; - } -} -ObjectId.index = Math.floor(Math.random() * 0xffffff); - -function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { - let totalLength = 4 + 1; - if (Array.isArray(object)) { - for (let i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } - else { - if (typeof object?.toBSON === 'function') { - object = object.toBSON(); - } - for (const key of Object.keys(object)) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - return totalLength; -} -function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - switch (typeof value) { - case 'string': - return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; - case 'number': - if (Math.floor(value) === value && - value >= JS_INT_MIN && - value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); - } - else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - } - else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); - case 'object': - if (value != null && - typeof value._bsontype === 'string' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; - } - else if (value._bsontype === 'ObjectId') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); - } - else if (value instanceof Date || isDate(value)) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - else if (ArrayBuffer.isView(value) || - value instanceof ArrayBuffer || - isAnyArrayBuffer(value)) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); - } - else if (value._bsontype === 'Long' || - value._bsontype === 'Double' || - value._bsontype === 'Timestamp') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - else if (value._bsontype === 'Decimal128') { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); - } - else if (value._bsontype === 'Code') { - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - 4 + - 4 + - ByteUtils.utf8ByteLength(value.code.toString()) + - 1 + - internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); - } - else { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - 4 + - ByteUtils.utf8ByteLength(value.code.toString()) + - 1); - } - } - else if (value._bsontype === 'Binary') { - const binary = value; - if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - (binary.position + 1 + 4 + 1 + 4)); - } - else { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); - } - } - else if (value._bsontype === 'Symbol') { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - ByteUtils.utf8ByteLength(value.value) + - 4 + - 1 + - 1); - } - else if (value._bsontype === 'DBRef') { - const ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - if (value.db != null) { - ordered_values['$db'] = value.db; - } - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); - } - else if (value instanceof RegExp || isRegExp(value)) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - ByteUtils.utf8ByteLength(value.source) + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1); - } - else if (value._bsontype === 'BSONRegExp') { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - ByteUtils.utf8ByteLength(value.pattern) + - 1 + - ByteUtils.utf8ByteLength(value.options) + - 1); - } - else { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1); - } - case 'function': - if (serializeFunctions) { - return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + - 1 + - 4 + - ByteUtils.utf8ByteLength(value.toString()) + - 1); - } - } - return 0; -} - -function alphabetize(str) { - return str.split('').sort().join(''); -} -class BSONRegExp extends BSONValue { - get _bsontype() { - return 'BSONRegExp'; - } - constructor(pattern, options) { - super(); - this.pattern = pattern; - this.options = alphabetize(options ?? ''); - if (this.pattern.indexOf('\x00') !== -1) { - throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); - } - if (this.options.indexOf('\x00') !== -1) { - throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); - } - for (let i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u')) { - throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`); - } - } - } - static parseOptions(options) { - return options ? options.split('').sort().join('') : ''; - } - toExtendedJSON(options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; - } - static fromExtendedJSON(doc) { - if ('$regex' in doc) { - if (typeof doc.$regex !== 'string') { - if (doc.$regex._bsontype === 'BSONRegExp') { - return doc; - } - } - else { - return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); - } - } - if ('$regularExpression' in doc) { - return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); - } - throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; - } -} - -class BSONSymbol extends BSONValue { - get _bsontype() { - return 'BSONSymbol'; - } - constructor(value) { - super(); - this.value = value; - } - valueOf() { - return this.value; - } - toString() { - return this.value; - } - inspect() { - return `new BSONSymbol("${this.value}")`; - } - toJSON() { - return this.value; - } - toExtendedJSON() { - return { $symbol: this.value }; - } - static fromExtendedJSON(doc) { - return new BSONSymbol(doc.$symbol); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } -} - -const LongWithoutOverridesClass = Long; -class Timestamp extends LongWithoutOverridesClass { - get _bsontype() { - return 'Timestamp'; - } - constructor(low) { - if (low == null) { - super(0, 0, true); - } - else if (typeof low === 'bigint') { - super(low, true); - } - else if (Long.isLong(low)) { - super(low.low, low.high, true); - } - else if (typeof low === 'object' && 't' in low && 'i' in low) { - if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { - throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); - } - if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { - throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); - } - if (low.t < 0) { - throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); - } - if (low.i < 0) { - throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); - } - if (low.t > 4294967295) { - throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); - } - if (low.i > 4294967295) { - throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); - } - super(low.i.valueOf(), low.t.valueOf(), true); - } - else { - throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); - } - } - toJSON() { - return { - $timestamp: this.toString() - }; - } - static fromInt(value) { - return new Timestamp(Long.fromInt(value, true)); - } - static fromNumber(value) { - return new Timestamp(Long.fromNumber(value, true)); - } - static fromBits(lowBits, highBits) { - return new Timestamp({ i: lowBits, t: highBits }); - } - static fromString(str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); - } - toExtendedJSON() { - return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; - } - static fromExtendedJSON(doc) { - const i = Long.isLong(doc.$timestamp.i) - ? doc.$timestamp.i.getLowBitsUnsigned() - : doc.$timestamp.i; - const t = Long.isLong(doc.$timestamp.t) - ? doc.$timestamp.t.getLowBitsUnsigned() - : doc.$timestamp.t; - return new Timestamp({ t, i }); - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return this.inspect(); - } - inspect() { - return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; - } -} -Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - -const FIRST_BIT = 0x80; -const FIRST_TWO_BITS = 0xc0; -const FIRST_THREE_BITS = 0xe0; -const FIRST_FOUR_BITS = 0xf0; -const FIRST_FIVE_BITS = 0xf8; -const TWO_BIT_CHAR = 0xc0; -const THREE_BIT_CHAR = 0xe0; -const FOUR_BIT_CHAR = 0xf0; -const CONTINUING_CHAR = 0x80; -function validateUtf8(bytes, start, end) { - let continuation = 0; - for (let i = start; i < end; i += 1) { - const byte = bytes[i]; - if (continuation) { - if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) { - return false; - } - continuation -= 1; - } - else if (byte & FIRST_BIT) { - if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) { - continuation = 1; - } - else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) { - continuation = 2; - } - else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) { - continuation = 3; - } - else { - return false; - } - } - } - return !continuation; -} - -const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); -const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); -function internalDeserialize(buffer, options, isArray) { - options = options == null ? {} : options; - const index = options && options.index ? options.index : 0; - const size = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (size < 5) { - throw new BSONError(`bson size must be >= 5, is ${size}`); - } - if (options.allowObjectSmallerThanBufferSize && buffer.length < size) { - throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`); - } - if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) { - throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`); - } - if (size + index > buffer.byteLength) { - throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`); - } - if (buffer[index + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - return deserializeObject(buffer, index, options, isArray); -} -const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; -function deserializeObject(buffer, index, options, isArray = false) { - const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - const raw = options['raw'] == null ? false : options['raw']; - const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - const promoteBuffers = options.promoteBuffers ?? false; - const promoteLongs = options.promoteLongs ?? true; - const promoteValues = options.promoteValues ?? true; - const useBigInt64 = options.useBigInt64 ?? false; - if (useBigInt64 && !promoteValues) { - throw new BSONError('Must either request bigint or Long for int64 deserialization'); - } - if (useBigInt64 && !promoteLongs) { - throw new BSONError('Must either request bigint or Long for int64 deserialization'); - } - const validation = options.validation == null ? { utf8: true } : options.validation; - let globalUTFValidation = true; - let validationSetting; - const utf8KeysSet = new Set(); - const utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === 'boolean') { - validationSetting = utf8ValidatedKeys; - } - else { - globalUTFValidation = false; - const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError('UTF-8 validation setting cannot be empty'); - } - if (typeof utf8ValidationValues[0] !== 'boolean') { - throw new BSONError('Invalid UTF-8 validation option, must specify boolean values'); - } - validationSetting = utf8ValidationValues[0]; - if (!utf8ValidationValues.every(item => item === validationSetting)) { - throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); - } - } - if (!globalUTFValidation) { - for (const key of Object.keys(utf8ValidatedKeys)) { - utf8KeysSet.add(key); - } - } - const startIndex = index; - if (buffer.length < 5) - throw new BSONError('corrupt bson message < 5 bytes long'); - const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - if (size < 5 || size > buffer.length) - throw new BSONError('corrupt bson message'); - const object = isArray ? [] : {}; - let arrayIndex = 0; - const done = false; - let isPossibleDBRef = isArray ? false : null; - const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); - while (!done) { - const elementType = buffer[index++]; - if (elementType === 0) - break; - let i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.byteLength) - throw new BSONError('Bad BSON Document: illegal CString'); - const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); - let shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet.has(name)) { - shouldValidateKey = validationSetting; - } - else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === '$') { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - let value; - index = i + 1; - if (elementType === BSON_DATA_STRING) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - } - else if (elementType === BSON_DATA_OID) { - const oid = ByteUtils.allocate(12); - oid.set(buffer.subarray(index, index + 12)); - value = new ObjectId(oid); - index = index + 12; - } - else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); - } - else if (elementType === BSON_DATA_INT) { - value = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } - else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { - value = new Double(dataview.getFloat64(index, true)); - index = index + 8; - } - else if (elementType === BSON_DATA_NUMBER) { - value = dataview.getFloat64(index, true); - index = index + 8; - } - else if (elementType === BSON_DATA_DATE) { - const lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - value = new Date(new Long(lowBits, highBits).toNumber()); - } - else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) - throw new BSONError('illegal boolean type value'); - value = buffer[index++] === 1; - } - else if (elementType === BSON_DATA_OBJECT) { - const _index = index; - const objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new BSONError('bad embedded document length in bson'); - if (raw) { - value = buffer.slice(index, index + objectSize); - } - else { - let objectOptions = options; - if (!globalUTFValidation) { - objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer, _index, objectOptions, false); - } - index = index + objectSize; - } - else if (elementType === BSON_DATA_ARRAY) { - const _index = index; - const objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - let arrayOptions = options; - const stopIndex = index + objectSize; - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = { ...options, raw: true }; - } - if (!globalUTFValidation) { - arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - if (buffer[index - 1] !== 0) - throw new BSONError('invalid array terminator byte'); - if (index !== stopIndex) - throw new BSONError('corrupted array bson'); - } - else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } - else if (elementType === BSON_DATA_NULL) { - value = null; - } - else if (elementType === BSON_DATA_LONG) { - const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); - const lowBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const highBits = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const long = new Long(lowBits, highBits); - if (useBigInt64) { - value = dataview.getBigInt64(0, true); - } - else if (promoteLongs && promoteValues === true) { - value = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } - else { - value = long; - } - } - else if (elementType === BSON_DATA_DECIMAL128) { - const bytes = ByteUtils.allocate(16); - bytes.set(buffer.subarray(index, index + 16), 0); - index = index + 16; - value = new Decimal128(bytes); - } - else if (elementType === BSON_DATA_BINARY) { - let binarySize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - const totalBinarySize = binarySize; - const subType = buffer[index++]; - if (binarySize < 0) - throw new BSONError('Negative binary type element size found'); - if (binarySize > buffer.byteLength) - throw new BSONError('Binary type size larger than document size'); - if (buffer['slice'] != null) { - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - if (promoteBuffers && promoteValues) { - value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { - value = value.toUUID(); - } - } - } - else { - const _buffer = ByteUtils.allocate(binarySize); - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new BSONError('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too long binary size'); - if (binarySize < totalBinarySize - 4) - throw new BSONError('Binary type with subtype 0x02 contains too short binary size'); - } - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - if (promoteBuffers && promoteValues) { - value = _buffer; - } - else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { - value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); - } - else { - value = new Binary(buffer.slice(index, index + binarySize), subType); - } - } - index = index + binarySize; - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const source = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - const optionsArray = new Array(regExpOptions.length); - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - value = new RegExp(source, optionsArray.join('')); - } - else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const source = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - i = index; - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - if (i >= buffer.length) - throw new BSONError('Bad BSON Document: illegal CString'); - const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); - index = i + 1; - value = new BSONRegExp(source, regExpOptions); - } - else if (elementType === BSON_DATA_SYMBOL) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol : new BSONSymbol(symbol); - index = index + stringSize; - } - else if (elementType === BSON_DATA_TIMESTAMP) { - const i = buffer[index++] + - buffer[index++] * (1 << 8) + - buffer[index++] * (1 << 16) + - buffer[index++] * (1 << 24); - const t = buffer[index++] + - buffer[index++] * (1 << 8) + - buffer[index++] * (1 << 16) + - buffer[index++] * (1 << 24); - value = new Timestamp({ i, t }); - } - else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey(); - } - else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey(); - } - else if (elementType === BSON_DATA_CODE) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - value = new Code(functionString); - index = index + stringSize; - } - else if (elementType === BSON_DATA_CODE_W_SCOPE) { - const totalSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError('code_w_scope total size shorter minimum expected length'); - } - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) { - throw new BSONError('bad string length in bson'); - } - const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey); - index = index + stringSize; - const _index = index; - const objectSize = buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - const scopeObject = deserializeObject(buffer, _index, options, false); - index = index + objectSize; - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too short, truncating scope'); - } - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError('code_w_scope total size is too long, clips outer document'); - } - value = new Code(functionString, scopeObject); - } - else if (elementType === BSON_DATA_DBPOINTER) { - const stringSize = buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0) - throw new BSONError('bad string length in bson'); - if (validation != null && validation.utf8) { - if (!validateUtf8(buffer, index, index + stringSize - 1)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - } - const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); - index = index + stringSize; - const oidBuffer = ByteUtils.allocate(12); - oidBuffer.set(buffer.subarray(index, index + 12), 0); - const oid = new ObjectId(oidBuffer); - index = index + 12; - value = new DBRef(namespace, oid); - } - else { - throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); - } - if (name === '__proto__') { - Object.defineProperty(object, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - object[name] = value; - } - } - if (size !== index - startIndex) { - if (isArray) - throw new BSONError('corrupt array bson'); - throw new BSONError('corrupt object bson'); - } - if (!isPossibleDBRef) - return object; - if (isDBRefLike(object)) { - const copy = Object.assign({}, object); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object.$ref, object.$id, object.$db, copy); - } - return object; -} -function getValidatedString(buffer, start, end, shouldValidateUtf8) { - const value = ByteUtils.toUTF8(buffer.subarray(start, end)); - if (shouldValidateUtf8) { - for (let i = 0; i < value.length; i++) { - if (value.charCodeAt(i) === 0xfffd) { - if (!validateUtf8(buffer, start, end)) { - throw new BSONError('Invalid UTF-8 string in BSON document'); - } - break; - } - } - } - return value; -} - -const regexp = /\x00/; -const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); -function serializeString(buffer, key, value, index) { - buffer[index++] = BSON_DATA_STRING; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - index = index + 4 + size; - buffer[index++] = 0; - return index; -} -const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); -const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); -const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); -function serializeNumber(buffer, key, value, index) { - const isNegativeZero = Object.is(value, -0); - const type = !isNegativeZero && - Number.isSafeInteger(value) && - value <= BSON_INT32_MAX && - value >= BSON_INT32_MIN - ? BSON_DATA_INT - : BSON_DATA_NUMBER; - if (type === BSON_DATA_INT) { - NUMBER_SPACE.setInt32(0, value, true); - } - else { - NUMBER_SPACE.setFloat64(0, value, true); - } - const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; - buffer[index++] = type; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0x00; - buffer.set(bytes, index); - index += bytes.byteLength; - return index; -} -function serializeBigInt(buffer, key, value, index) { - buffer[index++] = BSON_DATA_LONG; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index += numberOfWrittenBytes; - buffer[index++] = 0; - NUMBER_SPACE.setBigInt64(0, value, true); - buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); - index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; - return index; -} -function serializeNull(buffer, key, _, index) { - buffer[index++] = BSON_DATA_NULL; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeBoolean(buffer, key, value, index) { - buffer[index++] = BSON_DATA_BOOLEAN; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - buffer[index++] = value ? 1 : 0; - return index; -} -function serializeDate(buffer, key, value, index) { - buffer[index++] = BSON_DATA_DATE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const dateInMilis = Long.fromNumber(value.getTime()); - const lowBits = dateInMilis.getLowBits(); - const highBits = dateInMilis.getHighBits(); - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeRegExp(buffer, key, value, index) { - buffer[index++] = BSON_DATA_REGEXP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw new BSONError('value ' + value.source + ' must not contain null bytes'); - } - index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); - buffer[index++] = 0x00; - if (value.ignoreCase) - buffer[index++] = 0x69; - if (value.global) - buffer[index++] = 0x73; - if (value.multiline) - buffer[index++] = 0x6d; - buffer[index++] = 0x00; - return index; -} -function serializeBSONRegExp(buffer, key, value, index) { - buffer[index++] = BSON_DATA_REGEXP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.pattern.match(regexp) != null) { - throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); - } - index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); - buffer[index++] = 0x00; - const sortedOptions = value.options.split('').sort().join(''); - index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); - buffer[index++] = 0x00; - return index; -} -function serializeMinMax(buffer, key, value, index) { - if (value === null) { - buffer[index++] = BSON_DATA_NULL; - } - else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON_DATA_MIN_KEY; - } - else { - buffer[index++] = BSON_DATA_MAX_KEY; - } - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} -function serializeObjectId(buffer, key, value, index) { - buffer[index++] = BSON_DATA_OID; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (isUint8Array(value.id)) { - buffer.set(value.id.subarray(0, 12), index); - } - else { - throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - return index + 12; -} -function serializeBuffer(buffer, key, value, index) { - buffer[index++] = BSON_DATA_BINARY; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const size = value.length; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; - buffer.set(value, index); - index = index + size; - return index; -} -function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { - if (path.has(value)) { - throw new BSONError('Cannot convert circular structure to BSON'); - } - path.add(value); - buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - path.delete(value); - return endIndex; -} -function serializeDecimal128(buffer, key, value, index) { - buffer[index++] = BSON_DATA_DECIMAL128; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - buffer.set(value.bytes.subarray(0, 16), index); - return index + 16; -} -function serializeLong(buffer, key, value, index) { - buffer[index++] = - value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const lowBits = value.getLowBits(); - const highBits = value.getHighBits(); - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} -function serializeInt32(buffer, key, value, index) { - value = value.valueOf(); - buffer[index++] = BSON_DATA_INT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -} -function serializeDouble(buffer, key, value, index) { - buffer[index++] = BSON_DATA_NUMBER; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - NUMBER_SPACE.setFloat64(0, value.value, true); - buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); - index = index + 8; - return index; -} -function serializeFunction(buffer, key, value, index) { - buffer[index++] = BSON_DATA_CODE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const functionString = value.toString(); - const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - index = index + 4 + size - 1; - buffer[index++] = 0; - return index; -} -function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { - if (value.scope && typeof value.scope === 'object') { - buffer[index++] = BSON_DATA_CODE_W_SCOPE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - let startIndex = index; - const functionString = value.code; - index = index + 4; - const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - buffer[index + 4 + codeSize - 1] = 0; - index = index + codeSize + 4; - const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - index = endIndex - 1; - const totalSize = endIndex - startIndex; - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - buffer[index++] = 0; - } - else { - buffer[index++] = BSON_DATA_CODE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const functionString = value.code.toString(); - const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - index = index + 4 + size - 1; - buffer[index++] = 0; - } - return index; -} -function serializeBinary(buffer, key, value, index) { - buffer[index++] = BSON_DATA_BINARY; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const data = value.buffer; - let size = value.position; - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - buffer[index++] = value.sub_type; - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - buffer.set(data, index); - index = index + value.position; - return index; -} -function serializeSymbol(buffer, key, value, index) { - buffer[index++] = BSON_DATA_SYMBOL; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - index = index + 4 + size - 1; - buffer[index++] = 0x00; - return index; -} -function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { - buffer[index++] = BSON_DATA_OBJECT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - let startIndex = index; - let output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; - } - output = Object.assign(output, value.fields); - const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path); - const size = endIndex - startIndex; - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - return endIndex; -} -function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - if (path == null) { - if (object == null) { - buffer[0] = 0x05; - buffer[1] = 0x00; - buffer[2] = 0x00; - buffer[3] = 0x00; - buffer[4] = 0x00; - return 5; - } - if (Array.isArray(object)) { - throw new BSONError('serialize does not support an array as the root input'); - } - if (typeof object !== 'object') { - throw new BSONError('serialize does not support non-object as the root input'); - } - else if ('_bsontype' in object && typeof object._bsontype === 'string') { - throw new BSONError(`BSON types cannot be serialized as a document`); - } - else if (isDate(object) || - isRegExp(object) || - isUint8Array(object) || - isAnyArrayBuffer(object)) { - throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); - } - path = new Set(); - } - path.add(object); - let index = startingIndex + 4; - if (Array.isArray(object)) { - for (let i = 0; i < object.length; i++) { - const key = `${i}`; - let value = object[i]; - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - if (typeof value === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (typeof value === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (typeof value === 'bigint') { - index = serializeBigInt(buffer, key, value, index); - } - else if (typeof value === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (typeof value === 'object' && value._bsontype == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'object' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value._bsontype === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } - else if (value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value._bsontype === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index); - } - else if (value._bsontype === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (value._bsontype === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value._bsontype === 'BSONSymbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value._bsontype === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); - } - else if (value._bsontype === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value._bsontype === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value._bsontype !== 'undefined') { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } - } - else if (object instanceof Map || isMap(object)) { - const iterator = object.entries(); - let done = false; - while (!done) { - const entry = iterator.next(); - done = !!entry.done; - if (done) - continue; - const key = entry.value[0]; - let value = entry.value[1]; - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - const type = typeof value; - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - throw new BSONError('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw new BSONError('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw new BSONError('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - index = serializeBigInt(buffer, key, value, index); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'object' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value._bsontype === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value._bsontype === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value._bsontype === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index); - } - else if (value._bsontype === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value._bsontype === 'BSONSymbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value._bsontype === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); - } - else if (value._bsontype === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value._bsontype === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value._bsontype !== 'undefined') { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } - } - else { - if (typeof object?.toBSON === 'function') { - object = object.toBSON(); - if (object != null && typeof object !== 'object') { - throw new BSONError('toBSON function did not return an object'); - } - } - for (const key of Object.keys(object)) { - let value = object[key]; - if (typeof value?.toBSON === 'function') { - value = value.toBSON(); - } - const type = typeof value; - if (typeof key === 'string' && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - throw new BSONError('key ' + key + ' must not contain null bytes'); - } - if (checkKeys) { - if ('$' === key[0]) { - throw new BSONError('key ' + key + " must not start with '$'"); - } - else if (~key.indexOf('.')) { - throw new BSONError('key ' + key + " must not contain '.'"); - } - } - } - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } - else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } - else if (type === 'bigint') { - index = serializeBigInt(buffer, key, value, index); - } - else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } - else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } - else if (value === undefined) { - if (ignoreUndefined === false) - index = serializeNull(buffer, key, value, index); - } - else if (value === null) { - index = serializeNull(buffer, key, value, index); - } - else if (isUint8Array(value)) { - index = serializeBuffer(buffer, key, value, index); - } - else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'object' && - value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (value._bsontype === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } - else if (type === 'object' && value._bsontype === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } - else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } - else if (value._bsontype === 'Double') { - index = serializeDouble(buffer, key, value, index); - } - else if (value._bsontype === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); - } - else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index); - } - else if (value._bsontype === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } - else if (value._bsontype === 'BSONSymbol') { - index = serializeSymbol(buffer, key, value, index); - } - else if (value._bsontype === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); - } - else if (value._bsontype === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } - else if (value._bsontype === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } - else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - else if (typeof value._bsontype !== 'undefined') { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } - } - path.delete(object); - buffer[index++] = 0x00; - const size = index - startingIndex; - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -function isBSONType(value) { - return (value != null && - typeof value === 'object' && - '_bsontype' in value && - typeof value._bsontype === 'string'); -} -const keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp -}; -function deserializeValue(value, options = {}) { - if (typeof value === 'number') { - const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; - const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; - if (options.relaxed || options.legacy) { - return value; - } - if (Number.isInteger(value) && !Object.is(value, -0)) { - if (in32BitRange) { - return new Int32(value); - } - if (in64BitRange) { - if (options.useBigInt64) { - return BigInt(value); - } - return Long.fromNumber(value); - } - } - return new Double(value); - } - if (value == null || typeof value !== 'object') - return value; - if (value.$undefined) - return null; - const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); - for (let i = 0; i < keys.length; i++) { - const c = keysToCodecs[keys[i]]; - if (c) - return c.fromExtendedJSON(value, options); - } - if (value.$date != null) { - const d = value.$date; - const date = new Date(); - if (options.legacy) { - if (typeof d === 'number') - date.setTime(d); - else if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (typeof d === 'bigint') - date.setTime(Number(d)); - else - throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); - } - else { - if (typeof d === 'string') - date.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date.setTime(d.toNumber()); - else if (typeof d === 'number' && options.relaxed) - date.setTime(d); - else if (typeof d === 'bigint') - date.setTime(Number(d)); - else - throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); - } - return date; - } - if (value.$code != null) { - const copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); - } - if (isDBRefLike(value) || value.$dbPointer) { - const v = value.$ref ? value : value.$dbPointer; - if (v instanceof DBRef) - return v; - const dollarKeys = Object.keys(v).filter(k => k.startsWith('$')); - let valid = true; - dollarKeys.forEach(k => { - if (['$ref', '$id', '$db'].indexOf(k) === -1) - valid = false; - }); - if (valid) - return DBRef.fromExtendedJSON(v); - } - return value; -} -function serializeArray(array, options) { - return array.map((v, index) => { - options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); - try { - return serializeValue(v, options); - } - finally { - options.seenObjects.pop(); - } - }); -} -function getISOString(date) { - const isoStr = date.toISOString(); - return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; -} -function serializeValue(value, options) { - if (value instanceof Map || isMap(value)) { - const obj = Object.create(null); - for (const [k, v] of value) { - if (typeof k !== 'string') { - throw new BSONError('Can only serialize maps with string keys'); - } - obj[k] = v; - } - return serializeValue(obj, options); - } - if ((typeof value === 'object' || typeof value === 'function') && value !== null) { - const index = options.seenObjects.findIndex(entry => entry.obj === value); - if (index !== -1) { - const props = options.seenObjects.map(entry => entry.propertyName); - const leadingPart = props - .slice(0, index) - .map(prop => `${prop} -> `) - .join(''); - const alreadySeen = props[index]; - const circularPart = ' -> ' + - props - .slice(index + 1, props.length - 1) - .map(prop => `${prop} -> `) - .join(''); - const current = props[props.length - 1]; - const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2); - const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONError('Converting circular structure to EJSON:\n' + - ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` + - ` ${leadingSpace}\\${dashes}/`); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; - } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange - ? { $date: value.getTime() } - : { $date: getISOString(value) }; - } - return options.relaxed && inRange - ? { $date: getISOString(value) } - : { $date: { $numberLong: value.getTime().toString() } }; - } - if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { - if (Number.isInteger(value) && !Object.is(value, -0)) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - return { $numberInt: value.toString() }; - } - if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { - return { $numberLong: value.toString() }; - } - } - return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; - } - if (typeof value === 'bigint') { - if (!options.relaxed) { - return { $numberLong: BigInt.asIntN(64, value).toString() }; - } - return Number(BigInt.asIntN(64, value)); - } - if (value instanceof RegExp || isRegExp(value)) { - let flags = value.flags; - if (flags === undefined) { - const match = value.toString().match(/[gimuy]*$/); - if (match) { - flags = match[0]; - } - } - const rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); - } - if (value != null && typeof value === 'object') - return serializeDocument(value, options); - return value; -} -const BSON_TYPE_MAPPINGS = { - Binary: (o) => new Binary(o.value(), o.sub_type), - Code: (o) => new Code(o.code, o.scope), - DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), - Decimal128: (o) => new Decimal128(o.bytes), - Double: (o) => new Double(o.value), - Int32: (o) => new Int32(o.value), - Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_), - MaxKey: () => new MaxKey(), - MinKey: () => new MinKey(), - ObjectId: (o) => new ObjectId(o), - BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), - BSONSymbol: (o) => new BSONSymbol(o.value), - Timestamp: (o) => Timestamp.fromBits(o.low, o.high) -}; -function serializeDocument(doc, options) { - if (doc == null || typeof doc !== 'object') - throw new BSONError('not an object instance'); - const bsontype = doc._bsontype; - if (typeof bsontype === 'undefined') { - const _doc = {}; - for (const name of Object.keys(doc)) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - const value = serializeValue(doc[name], options); - if (name === '__proto__') { - Object.defineProperty(_doc, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } - else { - _doc[name] = value; - } - } - finally { - options.seenObjects.pop(); - } - } - return _doc; - } - else if (doc != null && - typeof doc === 'object' && - typeof doc._bsontype === 'string' && - doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError(); - } - else if (isBSONType(doc)) { - let outDoc = doc; - if (typeof outDoc.toExtendedJSON !== 'function') { - const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; - if (!mapper) { - throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); - } - outDoc = mapper(outDoc); - } - if (bsontype === 'Code' && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } - else if (bsontype === 'DBRef' && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); - } - return outDoc.toExtendedJSON(options); - } - else { - throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype); - } -} -function parse(text, options) { - const ejsonOptions = { - useBigInt64: options?.useBigInt64 ?? false, - relaxed: options?.relaxed ?? true, - legacy: options?.legacy ?? false - }; - return JSON.parse(text, (key, value) => { - if (key.indexOf('\x00') !== -1) { - throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); - } - return deserializeValue(value, ejsonOptions); - }); -} -function stringify(value, replacer, space, options) { - if (space != null && typeof space === 'object') { - options = space; - space = 0; - } - if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; - } - const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: '(root)', obj: null }] - }); - const doc = serializeValue(value, serializeOptions); - return JSON.stringify(doc, replacer, space); -} -function EJSONserialize(value, options) { - options = options || {}; - return JSON.parse(stringify(value, options)); -} -function EJSONdeserialize(ejson, options) { - options = options || {}; - return parse(JSON.stringify(ejson), options); -} -const EJSON = Object.create(null); -EJSON.parse = parse; -EJSON.stringify = stringify; -EJSON.serialize = EJSONserialize; -EJSON.deserialize = EJSONdeserialize; -Object.freeze(EJSON); - -const MAXSIZE = 1024 * 1024 * 17; -let buffer = ByteUtils.allocate(MAXSIZE); -function setInternalBufferSize(size) { - if (buffer.length < size) { - buffer = ByteUtils.allocate(size); - } -} -function serialize(object, options = {}) { - const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - if (buffer.length < minInternalBufferSize) { - buffer = ByteUtils.allocate(minInternalBufferSize); - } - const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); - const finishedBuffer = ByteUtils.allocate(serializationIndex); - finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); - return finishedBuffer; -} -function serializeWithBufferAndIndex(object, finalBuffer, options = {}) { - const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - const startIndex = typeof options.index === 'number' ? options.index : 0; - const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); - finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); - return startIndex + serializationIndex - 1; -} -function deserialize(buffer, options = {}) { - return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); -} -function calculateObjectSize(object, options = {}) { - options = options || {}; - const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined); -} -function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - const bufferData = ByteUtils.toLocalBufferType(data); - let index = startIndex; - for (let i = 0; i < numberOfDocuments; i++) { - const size = bufferData[index] | - (bufferData[index + 1] << 8) | - (bufferData[index + 2] << 16) | - (bufferData[index + 3] << 24); - internalOptions.index = index; - documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); - index = index + size; - } - return index; -} - -var bson = /*#__PURE__*/Object.freeze({ - __proto__: null, - Code: Code, - BSONSymbol: BSONSymbol, - DBRef: DBRef, - Binary: Binary, - ObjectId: ObjectId, - UUID: UUID, - Long: Long, - Timestamp: Timestamp, - Double: Double, - Int32: Int32, - MinKey: MinKey, - MaxKey: MaxKey, - BSONRegExp: BSONRegExp, - Decimal128: Decimal128, - setInternalBufferSize: setInternalBufferSize, - serialize: serialize, - serializeWithBufferAndIndex: serializeWithBufferAndIndex, - deserialize: deserialize, - calculateObjectSize: calculateObjectSize, - deserializeStream: deserializeStream, - BSONValue: BSONValue, - BSONError: BSONError, - BSONVersionError: BSONVersionError, - BSONRuntimeError: BSONRuntimeError, - BSONType: BSONType, - EJSON: EJSON -}); - -exports.BSON = bson; -exports.BSONError = BSONError; -exports.BSONRegExp = BSONRegExp; -exports.BSONRuntimeError = BSONRuntimeError; -exports.BSONSymbol = BSONSymbol; -exports.BSONType = BSONType; -exports.BSONValue = BSONValue; -exports.BSONVersionError = BSONVersionError; -exports.Binary = Binary; -exports.Code = Code; -exports.DBRef = DBRef; -exports.Decimal128 = Decimal128; -exports.Double = Double; -exports.EJSON = EJSON; -exports.Int32 = Int32; -exports.Long = Long; -exports.MaxKey = MaxKey; -exports.MinKey = MinKey; -exports.ObjectId = ObjectId; -exports.Timestamp = Timestamp; -exports.UUID = UUID; -exports.calculateObjectSize = calculateObjectSize; -exports.deserialize = deserialize; -exports.deserializeStream = deserializeStream; -exports.serialize = serialize; -exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; -exports.setInternalBufferSize = setInternalBufferSize; -//# sourceMappingURL=bson.cjs.map diff --git a/src/extras/struct/genTimestamps.ts b/src/extras/struct/genTimestamps.ts deleted file mode 100644 index 38c74670..00000000 --- a/src/extras/struct/genTimestamps.ts +++ /dev/null @@ -1,110 +0,0 @@ - -//thanks gpt -export type TimeUnit = - | 'second' - | 'minute' - | 'hour' - | 'day' - | 'week' - | 'month' - | 'year' - | 'decade' - | 'century' - | 'millennium' - | 'microsecond' - | 'nanosecond'; - -type Plural = `${T}s`; - -export type TimeSpecifier = `now` | `last ${string} ${Plural}` | `last ${TimeUnit}`; - -export let defaultSpecifiers = [ - 'now', - 'minute', - '5 minutes', - '30 minutes', - 'hour', - '6 hours', - '12 hours', - 'day', - '3 days', - 'week', - '2 weeks', - 'month', - '6 months', - 'year', - '5 years', - 'decade', -] as ('now'|TimeUnit)[]; - -export function genTimeSpecifiers( - specifiers = defaultSpecifiers as ('now'|TimeUnit)[] -) { - let result = ['now']; - specifiers.forEach((s) => { - if(s !== 'now') - result.push(`last ${s}`); - else result.push(s); - }); - - return result; -} - -export function genTimestampFromString(specifier: TimeSpecifier): number { - const now = new Date(); - - if(specifier === 'now') {} - else if (specifier === 'last minute') { - now.setMinutes(now.getMinutes() - 1); - } else if (specifier === 'last hour') { - now.setHours(now.getHours() - 1); - } else if (specifier === 'last day') { - now.setDate(now.getDate() - 1); - } else if (specifier === 'last week') { - now.setDate(now.getDate() - 7); - } else if (specifier === 'last month') { - now.setMonth(now.getMonth() - 1); - } else if (specifier === 'last year') { - now.setFullYear(now.getFullYear() - 1); - } else if (specifier === 'last decade') { - now.setFullYear(now.getFullYear() - 1 * 10); - } else if (specifier === 'last century') { - now.setFullYear(now.getFullYear() - 1 * 100); - } else if (specifier === 'last millennium') { - now.setFullYear(now.getFullYear() - 1 * 1000); - } else if (specifier === 'last microsecond') { - now.setMilliseconds(now.getMilliseconds() - 1); - } else if (specifier === 'last nanosecond') { - now.setMilliseconds(now.getMilliseconds() - 1 * 0.001); - } else if (specifier.startsWith('last')) { - const [, count, unit] = specifier.match(/last (\d+) (\w+)/) || []; - if (count && unit) { - const num = parseInt(count, 10); - if (unit.includes('minute')) { - now.setMinutes(now.getMinutes() - num); - } else if (unit.includes('hour')) { - now.setHours(now.getHours() - num); - } else if (unit.includes('day')) { - now.setDate(now.getDate() - num); - } else if (unit.includes('week')) { - now.setDate(now.getDate() - num * 7); - } else if (unit.includes('month')) { - now.setMonth(now.getMonth() - num); - } else if (unit.includes('year')) { - now.setFullYear(now.getFullYear() - num); - } else if (unit.includes('decade')) { - now.setFullYear(now.getFullYear() - num * 10); - } else if (unit.includes('century')) { - now.setFullYear(now.getFullYear() - num * 100); - } else if (unit.includes('millennium')) { - now.setFullYear(now.getFullYear() - num * 1000); - } else if (unit.includes('microsecond')) { - now.setMilliseconds(now.getMilliseconds() - num); - } else if (unit.includes('nanosecond')) { - now.setMilliseconds(now.getMilliseconds() - num * 0.001); - } - } - } - - return now.getTime(); - } \ No newline at end of file diff --git a/src/extras/todo.md b/src/extras/todo.md deleted file mode 100644 index df0255f6..00000000 --- a/src/extras/todo.md +++ /dev/null @@ -1 +0,0 @@ -Really need to fix the dist splitting types up \ No newline at end of file diff --git a/src/loaders/html/html.loader.ts b/src/loaders/html/html.loader.ts deleted file mode 100644 index 9cc7fb3a..00000000 --- a/src/loaders/html/html.loader.ts +++ /dev/null @@ -1,143 +0,0 @@ - -import {GraphNode, GraphNodeProperties,Graph} from '../../core/Graph' - -export type HTMLNodeProperties = GraphNodeProperties & { - __props?:HTMLElement, - __onresize?:(elm:HTMLElement) => void, - __onremove?:(elm:HTMLElement) => void, - __onrender?:(elm:HTMLElement) => void, - tagName?:string, //can provide this instead of an element or html template string - parentNode?:string|HTMLElement, //can define a specific parentNode, else a parent graph node with an HTMLElement as __props will be selected, else graph.parentNode if defined, else document.body - style?:Partial, //supply an object with style properties for this element's inline styles - //applies to custom webcomponent only (wchtmlloader): - __template?:string|((...args:any[]) => string), - __renderonchanged?:(elm:HTMLElement) => void, - useShadow?:boolean, - __css?:string, //stylesheet template string for use with web components (just prepends a `; delete node.__css; - } - - - const registerElement = (node, tagNameOverride?:string) => { - if (isNativeClass(node)) node = new node(); - else if (typeof node === 'function' && !node.__node) node = node(); - - class CustomElement extends DOMElement { - props = node.props; - styles = node.__css; - useShadow = node.useShadow; - template = node.__template as any; - oncreate = node.__onrender; - onresize = node.__onresize; - ondelete = node.__onremove; - renderonchanged = node.__renderonchanged as any; - } - - if (tagNameOverride?.includes('-')) node.tagName = tagNameOverride - else if(node.__element) node.tagName = node.__element; - - if(!node.tagName) node.tagName = `element${Math.floor(Math.random()*1000000000000000)}-`; - - CustomElement.addElement(node.tagName); - } - - - if ('__components' in node) { - if (Array.isArray(node.__components)) node.__components.forEach(c => registerElement(c)) - else Object.entries(node.__components).forEach(([k, c]) => registerElement(c, k.includes('-') ? k : undefined)) - } - - if ('__template' in node) { - - if(typeof node.__renderonchanged === 'function') { - let renderonchanged = node.__renderonchanged; - node.__renderonchanged = (element:DOMElement) => { - renderonchanged.call((element as any).node, element); - } - } - - registerElement(node); - node.__props = document.createElement(node.tagName); - - let cpy = Object.assign({},node); - let keys = Object.getOwnPropertyNames(cpy); - for(const k of keys) { - if(k === 'style' && typeof node[k] === 'object') {Object.assign(node.__props.style,cpy[k]);} - else if (k === 'className') node.__props.setAttribute('class', cpy[k]); - else if (!k.includes('outer')) node.__props[k] = cpy[k]; - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(k === 'style' && typeof node.__attributes[k] === 'object') {Object.assign(node.__props.style,node.__attributes[k]);} - else if (k === 'className') node.__props.setAttribute('class', node.__attributes[k]); - else if (!k.includes('outer')) node.__props[k] = node.__attributes[k]; - } - } - node.__proxyObject(node.__props); - - //fix for event listeners - for(const k of keys) { - if(typeof cpy[k] === 'function') { - let fn = cpy[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - } - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(typeof cpy[k] === 'function') { - let fn = node.__attributes[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - } - } - } - /// - - } else if(node.__props instanceof HTMLElement) { - let cpy = Object.assign({},node); - let keys = Object.getOwnPropertyNames(cpy); - - for(const k of keys) { - if(k === 'style' && typeof node[k] === 'object') {Object.assign(node.__props.style,cpy[k]);} - else if (k === 'className') node.__props.setAttribute('class', cpy[k]); - else if (!k.includes('outer')) node.__props[k] = cpy[k]; - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(k === 'style' && typeof node.__attributes[k] === 'object') {Object.assign(node.__props.style,node.__attributes[k]);} - else if (k === 'className') node.__props.setAttribute('class', cpy[k]); - else if (!k.includes('outer')) node.__props[k] = node.__attributes[k]; - } - } - - node.__proxyObject(node.__props); - - //fix for event listeners - for(const k of keys) { - if(typeof cpy[k] === 'function') { - let fn = cpy[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - node[k] = node.__props[k]; - } - } - - if(node.__attributes) { - for(const k in node.__attributes) { - if(typeof cpy[k] === 'function') { - let fn = node.__attributes[k]; - node.__props[k] = (...inp) => { let res = fn(...inp); node.__node.state.triggerEvent(node.__node.unique+'.'+k, res); }; - node[k] = node.__props[k]; - } - } - } - /// - - if(node.__onresize) - window.addEventListener('resize', node.__onresize as EventListener); - - } - - if(node.__props instanceof HTMLElement) { - node.__props.id = key; - (node.__props as any).node = node; - - node.__addOnconnected((n) => { - if(!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement) && n.__props.parentNode) (n.__props as HTMLElement).remove(); - if(properties.parentNode) { - if(typeof properties.parentNode === 'string' && document.getElementById(properties.parentNode)) - document.getElementById(properties.parentNode)?.appendChild(n.__props); - else if (properties.parentNode instanceof HTMLElement) properties.parentNode.appendChild(n.__props); - } else if(parent?.__props instanceof HTMLElement) { - parent.__props.appendChild(node.__props); - } else if (typeof graph.parentNode === 'string' && document.getElementById(properties.parentNode)) { - document.getElementById(properties.parentNode)?.appendChild(graph.__props); - } else if(graph.parentNode instanceof HTMLElement) { - graph.parentNode.appendChild(node.__props); - } else if(!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement)) - document.body.appendChild(node.__props); - - //add slight delay for sizing etc to kick in correctly - if(node.__onrender && !(node.__props instanceof DOMElement) && !node.__template) setTimeout(()=>{node.__onrender(node.__props)},0.01); - - }); - - node.__addOndisconnected((n) => { - (n.__props as HTMLElement).remove(); - - if(typeof n.__onremove === 'function') { - n.__onremove(n.__props) - } - - if(n.__onresize) { - window.removeEventListener('resize', n.__onresize); - } - }); - } - - -} \ No newline at end of file diff --git a/src/loaders/methodstrings.ts b/src/loaders/methodstrings.ts deleted file mode 100644 index f96e7677..00000000 --- a/src/loaders/methodstrings.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {parseFunctionFromText} from '../services/utils' - -export function methodstrings (node) { - if(typeof node.__methods === 'object') { - for(const key in node.__methods) { - let fstr = node.__methods[key]; - let fn = typeof fstr === 'function' ? fstr : parseFunctionFromText(fstr); - if(key === '__operator') { - node.__setOperator(fn as any); - } - else { - node[key] = fn.bind(node); - } - } - } -} \ No newline at end of file diff --git a/src/services/http/HTTP.node.ts b/src/services/http/HTTP.node.ts deleted file mode 100644 index 210e579f..00000000 --- a/src/services/http/HTTP.node.ts +++ /dev/null @@ -1,1268 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; -import * as http from 'http' -import * as https from 'https' -import * as fs from 'fs' -import * as path from 'path' -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -import { defaultManifest, defaultServiceWorker } from "./boilerplate/index"; - -export * from './boilerplate/index' - -export type ServerProps = { - host:string, - port:number, - certpath?:string, - keypath?:string, - passphrase?:string, - startpage?: string, - errpage?:string, - pages?:{ - [key:'all'|string]:string|{ //objects get loaded as nodes which you can modify props on - headers?:{[key:string]:any}, //page specific headers to assign on page response - template?:string, - onrequest?:GraphNode|string|((self:HTTPbackend, node:GraphNode, request:http.IncomingMessage, response:http.ServerResponse)=>void), //run a function or node? the template, request and response are passed as arguments, you can write custom node logic within this function to customize inputs etc. - redirect?:string, // can redirect the url to call a different route instead, e.g. '/':{redirect:'home'} sets the route passed to the receiver as 'home' - inject?:{[key:string]:any}|any[]|string| ((...args:any)=>any) //append html - } & GraphNodeProperties - }, - protocol?:'http'|'https', - type?:'httpserver'|string, - keepState?:boolean, //setState whenever a route is run? State will be available at the address (same key of the object storing it here) - onopen?:(served:ServerInfo)=>void, //onopen callback - onerror?:(er:Error,served:ServerInfo)=>void, - onclose?:(served:ServerInfo)=>void, //server close callback - onupgrade?:(request, socket, head, served:ServerInfo)=>void, - timeout?:number, //request timeout, default is 1 second - _id?:string, - debug?:boolean, - [key:string]:any -} - -export type ServerInfo = { - server:https.Server|http.Server, - address:string, - terminate:()=>void, - graph:HTTPbackend, - _id:string -} & ServerProps - -export type ReqOptions = { - protocol:'http'|'https'|string - host:string, - port:number, - method:string, - path?:string, - headers?:{ - [key:string]:any, - 'Content-Type'?:string, //e.g... - 'Content-Length'?:number - } -} - -//http/s server -export class HTTPbackend extends Service { - - name='http'; - - server:any - - debug:boolean=false - - servers:{ - [key:string]:ServerInfo - }={} - - mimeTypes:{[key:string]:string} = { - '.html': 'text/html', '.htm': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.txt':'text/plain', - '.png': 'image/png', '.jpg': 'image/jpg', '.jpeg': 'image/jpg','.gif': 'image/gif', '.svg': 'image/svg+xml', '.xhtml':'application/xhtml+xml', '.bmp':'image/bmp', - '.wav': 'audio/wav', '.mp3':'audio/mpeg', '.mp4': 'video/mp4', '.xml':'application/xml', '.webm':'video/webm', '.webp':'image/webp', '.weba':'audio/webm', - '.woff': 'font/woff', 'woff2':'font/woff2', '.ttf': 'application/font-ttf', '.eot': 'application/vnd.ms-fontobject', '.otf': 'application/font-otf', - '.wasm': 'application/wasm', '.zip':'application/zip','.xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.tif':'image/tiff', - '.sh':'application/x-sh', '.csh':'application/x-csh', '.rar':'application/vnd.rar','.ppt':'application/vnd.ms-powerpoint', '.pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation', - '.odt':'application/vnd.oasis.opendocument.text','.ods':'application/vnd.oasis.opendocument.spreadsheet','.odp':'application/vnd.oasis.opendocument.presentation', - '.mpeg':'video/mpeg','.mjs':'text/javascript','.cjs':'text/javascript','.jsonld':'application/ld+json', '.jar':'application/java-archive', '.ico':'image/vnd.microsoft.icon', - '.gz':'application/gzip', 'epub':'application/epub+zip', '.doc':'application/msword', '.docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - '.csv':'text/csv', '.avi':'video/x-msvideo', '.aac':'audio/aac', '.mpkg':'application/vnd.apple.installer+xml','.oga':'audio/ogg','.ogv':'video/ogg','ogx':'application/ogg', - '.php':'application/x-httpd-php', '.rtf':'application/rtf', '.swf':'application/x-shockwave-flash', '.7z':'application/x-7z-compressed', '.3gp':'video/3gpp' - }; - - constructor( - options?:ServiceOptions, - settings?:ServerProps - ) { - super(options); - this.load(this); - - //console.log(settings); - if(settings) { - this.setupServer(settings); - } - - } - - //on server started - onStarted = (protocol:'http'|'https'|string,host:string,port:number) => { - console.log(`🐱 Node server running at - ${protocol}://${host}:${port}/` - ); - } - - setupServer = ( - options:ServerProps={ - protocol:'http', - host:'localhost', - port:8080, - startpage:'index.html' - }, - requestListener?:http.RequestListener, - onStarted?:()=>void - )=>{ - //console.log(options); - if(options.pages) { - for(const key in options.pages) { - if (typeof options.pages[key] === 'string') { - this.addPage(`${options.port}/${key}`, options.pages[key] as string) - } else if (typeof options.pages[key] === 'object' || typeof options.pages[key] === 'function') { - if((options.pages[key] as any).template) { - (options.pages[key] as any).get = (options.pages[key] as any).template; - } - let rt = `${options.port}/${key}`; - if(key !== '_all') this.load({[rt]:options.pages[key]}); - } - } - } - - //create http or https server - this.setupHTTPserver(options, requestListener, onStarted); - } - - open = this.setupServer; - - //Define the server via http or https - setupHTTPserver = ( - options:(ServerProps & { - certpath?:string, - keypath?:string, - passphrase?:string - })={ - host:'localhost' as string, - port:8080 as number, - startpage:'index.html', - errpage:undefined - }, - requestListener?:http.RequestListener, - onStarted:()=>void = ()=>{this.onStarted('http',options.host,options.port)} - ) => { - - const host = options.host ? options.host : 'localhost'; - const port = options.port ? options.port : 8000; - - if(!host || !port) return; - - const address = `${host}:${port}`; - - if(this.servers[address]) this.terminate(this.servers[address]); - - if(!('keepState' in options)) options.keepState = true; //default true - - const served = { - server:undefined as any, - type:'httpserver', - address, - ...options - } as ServerInfo - - //default requestListener propagates to graphscript - if(!requestListener) - requestListener = ( - request:http.IncomingMessage, - response:http.ServerResponse - ) => { - - let received:any = { - args:{request, response}, - method:request.method, - served - } - - let url = (request as any).url.slice(1); - if(!url) url = '/'; - //console.log(options) - - if(options.debug) { - let time = getHoursAndMinutes(new Date()); - console.log( - time, ' | ', - 'From: ', request.socket?.remoteAddress, - 'For: ', request.url, ' | ', request.method - ); - } - - if(options.pages) { - getPageOptions.call(this, url, received, options.pages, request, response, options.port); - } else received.route = url; - - this.receive(received); - } //default requestListener - - //var http = require('http'); - let server:http.Server|https.Server = undefined as any; - if(options.protocol === 'http') - server = http.createServer( - requestListener - ); - else { - let opts; - if(options.keypath && options.certpath) { - opts = { - key: fs.readFileSync(options.keypath), - cert: fs.readFileSync(options.certpath), - passphrase:options.passphrase - } - server = https.createServer( - opts, - requestListener - ) - } else - console.error('Error, key and/or cert .pem SSL files not provided. See OpenSSL certbot for more info on how to create free SSL certifications, or create your own self-signed one for local development.') - - - } - - if(!server) { - console.error("Server not successfully created."); - return undefined; - } - - served.server = server; - served.terminate = () => { - this.terminate(served); - } - served.service = this; - - // server.on('upgrade', (request, socket, head) => { - // this.onUpgrade(request, socket, head); - // }); - - this.servers[address] = served; - served._id = options._id ? options._id : address; - - - - //SITE AVAILABLE ON PORT: - return new Promise((resolve,reject) => { - let resolved; - // server.on('connection',(socket) => { - // //DDOS protection? - // //Rate limiting? - // }); - server.on('error',(err)=>{ - if(served.onerror) served.onerror(err, served); - else console.error('Server error:', err.toString()); - if(!resolved) reject(err); - }); - server.on('clientError',(err, socket:http.IncomingMessage["socket"]) =>{ - if(served.onerror) served.onerror(err, served); - else console.error(getHoursAndMinutes(new Date()), ' | Server clientError:', err.toString(), ' | From: ', socket.remoteAddress); - if(socket) socket.destroy(); - }); - server.on('tlsClientError',(err, socket:http.IncomingMessage["socket"]) =>{ - if(served.onerror) served.onerror(err, served); - else console.error(getHoursAndMinutes(new Date()), ' | Server tlsClientError: ', err.toString(), ' | From: ', socket.remoteAddress); - if(socket) socket.destroy(); - }); - server.on('upgrade',(request, socket, head) => { - if(served.onupgrade) served.onupgrade(request,socket,head,served); - }); - server.listen( - port, host, - ()=>{ - onStarted(); - if(served.onopen) served.onopen(served); - resolved = true; - resolve(served); - } - ); - }) as Promise ; - } - - transmit = ( //generalized http request. The default will try to post back to the first server in the list - message:any | ServiceMessage, - options:string|{ - protocol:'http'|'https'|string - host:string, - port:number, - method:string, - path?:string, - headers?:{ - [key:string]:any, - 'Content-Type'?:string, - 'Content-Length'?:number - } - }, - ondata?:(chunk:any)=>void, - onend?:()=>void - - ) => { - let input = message; - if(typeof input === 'object' && !input.byteLength) input = JSON.stringify(input); - - if(typeof options === 'string' && message) return this.POST(options,message); - else if(typeof options === 'string') return this.GET(options); - - if(!options) { //fill a generic post request for the first server if none provided - let server = this.servers[Object.keys(this.servers)[0]]; - options = { - protocol:server.protocol as any, - host:server.host, - port:server.port, - method:'POST', - path:message.route, - headers:{ - 'Content-Type':'application/json', - 'Content-Length':input.length - } - }; - } //get first server and use its settings for a generic post request - else if (!options.headers) { - options.headers = { - 'Content-Type':'application/json', - 'Content-Length':input.length - } - } - - return this.request(options,input,ondata,onend); - } - - withResult = ( - response:http.ServerResponse, - result:any, - message:{ - route:string, - args:{request:http.IncomingMessage,response:http.ServerResponse}, //data will be an object containing request, response - method?:string, - served?:ServerInfo //server deets - } - ) => { - if(result && !response.writableEnded && !response.destroyed) { - - let mimeType = 'text/plain'; - - let head = {} as any; - - if(typeof result === 'string') { - let extname = path.extname(result); - - if(extname && fs.existsSync(path.join(process.cwd(),result))) { //load file paths if returned - mimeType = this.mimeTypes[extname] || 'application/octet-stream'; - - result = fs.readFileSync(path.join(process.cwd(),result)); - if(mimeType === 'text/html' && (message.served?.pages?._all || message.served?.pages?.[message.route])) { - let { templateString, headers } = this.injectPageCode(result.toString(),message.route,message.served as any) as any; - result = templateString; - Object.assign(head, headers); - } - } - else if(typeof result === 'string' && result.includes('<') && result.includes('>') && (result.indexOf('<') < result.indexOf('>'))) //probably an html template - { - head['Content-Type'] = 'text/html'; - if(message?.served?.pages?._all || message?.served?.pages?.[message.route]) { - let { templateString, headers } = this.injectPageCode(result,message.route,message.served) as any; - result = templateString; - Object.assign(head, headers); - } - response.writeHead(200,head); - response.end(result,'utf-8'); - return; - } - } else if(typeof result === 'object') { - result = JSON.stringify(result); - mimeType = 'application/json' - } - head['Content-Type'] = mimeType; - response.writeHead(200,head); - response.end(result,'utf-8'); - } else { - try {response.destroy();} catch {} - } - } - - injectPageCode = ( - templateString:string, - url:string, - served:ServerInfo - ):{templateString:string,headers:{[key:string]:any}} => { - if ((served?.pages?.[url] as any)?.inject) { //inject per url - if(typeof (served as any).pages[url].inject === 'object') - templateString = this.buildPage((served as any).pages[url].inject as any, templateString); - else if (typeof (served as any).pages[url].inject === 'function') - templateString += ((served as any).pages[url].inject as any)(); - else if (typeof (served as any).pages[url].inject === 'string' || typeof (served as any).pages[url].inject === 'number') - templateString += (served as any).pages[url].inject; - } - if((served?.pages?._all as any)?.inject) { //any per server - if(typeof (served.pages as any)._all.inject === 'object') - templateString = this.buildPage((served as any).pages._all.inject, templateString); - else if (typeof (served as any).pages._all.inject === 'function') - templateString += (served as any).pages._all.inject(); - else if (typeof (served as any).pages._all.inject === 'string' || typeof (served as any).pages._all.inject === 'number') - templateString += (served as any).pages._all.inject; - } - - let headers = {}; - if((served as any).pages._all.headers) - Object.assign(headers,(served as any).pages._all.headers); - - if((served as any).pages[url].headers) - Object.assign(headers,(served as any).pages[url].headers); - - - return {templateString, headers}; - } - - receive = ( //our fancy request response handler - message:{ - route:string, - args:{request:http.IncomingMessage,response:http.ServerResponse}, //data will be an object containing request, response - method?:string, - node?:string, // alt for route - served?:ServerInfo, //server deets - redirect?:string //if we redirected the route according to page options - } - ) => { - if(this.debug) console.log(message.args.request.method, message.args.request.url); - //console.log(request); //debug - - let result = new Promise((resolve,reject) => { - this.responsePromiseHandler(resolve, reject, message, message.args.request, message.args.response, message.method as string, message.served as ServerInfo); - }).catch((er)=>{ console.error("Request Error:", er); }); - - return result; - } - - //internal - responseOnErrorPromiseHandler = (response:http.ServerResponse, reject, err) => { - if(!response.writableEnded || !response.destroyed ) { - response.statusCode = 400; - response.end(undefined,undefined as any); - reject(err); - } else { - try {response.destroy();} catch {} - reject(err); - } - } - - //internal - getFailedPromiseHandler = (resolve, reject, requestURL, message, response:http.ServerResponse, served) => { - if(response.writableEnded || response.destroyed) reject(requestURL); - if(requestURL == './' || requestURL == served?.startpage) { - let template = `

Brains@Play Server

`; //start page dummy - if(served?.pages?._all || served?.pages?.error) { - let {templateString, headers} = this.injectPageCode(template,message.route,served) as any; - template = templateString; - } - response.writeHead(200, { 'Content-Type': 'text/html' }); - response.end(template,'utf-8'); //write some boilerplate server page, we should make this an interactive debug page - resolve(template); - if(served?.keepState) this.setState({[served.address]:template}); - return; - } - else if(this.debug) console.log(`File ${requestURL} does not exist on path!`); - - response.writeHead(500); //set response headers - response.end(undefined,undefined as any); - reject(requestURL); - - //return; - } - - //internal - handleBufferedPostBodyPromiseHandler = (resolve, body, message, response:http.ServerResponse, served) => { - - body = Buffer.concat(body).toString(); //now it's a string - - if(typeof body === 'string') { - let substr = body.substring(0,8); - if(substr.includes('{') || substr.includes('[')) { - if(substr.includes('\\')) body = body.replace(/\\/g,""); - if(body[0] === '"') { body = body.substring(1,body.length-1)}; - body = JSON.parse(body); //parse stringified args, this is safer in a step - } - } - - let route,method,args; - - if(body?.route){ //if arguments were posted - route = body.route; - method = body.method; - args = body.args; - if(!route) { - if(typeof body.route === 'string') if(body.route.includes('/') && body.route.length > 1) body.route = body.route.split('/').pop(); - route = body.route; - } - } - if(!route) { //body post did not provide argument so use the request route - if (message?.route) { - let route = message.route; - method = message.method; - args = message.args; - if(!route) { - if(typeof message.route === 'string') - if(message.route.includes('/') && message.route.length > 1) - message.route = message.route.split('/').pop() as string; - - route = message.route; - } - } - } - let res:any = body; - if(route) { - - if(this.restrict?.[route]) { - try {response.destroy();} catch {} - resolve(res); - } else { - if(body.method) { - res = this.handleMethod(route, method, args); - } - else if (body.node) { - res = this.handleGraphNodeCall(body.node, body.args); - } - else res = this.handleServiceMessage({route, args:args, method:method}); - - if(res instanceof Promise) { - res.then((r) => { - this.withResult(response,r,message); - if(served?.keepState) this.setState({[served.address]:res}); - resolve(res); - }); - } else { - this.withResult(response,res,message); - if(served?.keepState) this.setState({[served.address]:res}); - resolve(res); - } - } - } - else if(!response.writableEnded || !response.destroyed) { - response.statusCode = 200; - response.end(undefined,undefined as any); //posts etc. shouldn't return anything but a 200 usually - resolve(res); - } else { - try {response.destroy();} catch {} - resolve(res); //get requests resolve first and return otherwise this will resolve - } - - } - - //internal - onRequestFileReadPromiseHandler = (error, content, resolve, reject, requestURL, response:http.ServerResponse, message, served:ServerInfo) => { - if (error) { - if(error.code == 'ENOENT') { //page not found: 404 - if(served?.errpage) { - fs.readFile(served.errpage, (er, content) => { - response.writeHead(404, { 'Content-Type': 'text/html' }); //set response headers - - - //add hot reload if specified - // if(process.env.HOTRELOAD && requestURL.endsWith('.html') && cfg.hotreload) { - // content = addHotReloadClient(content,`${cfg.socket_protocol}://${cfg.host}:${cfg.port}/hotreload`); - // } - - if(served.pages?._all || served.pages?.error) { - let {templateString, headers} = this.injectPageCode(content.toString(),message.route,served) as any; - content = templateString; - } - - response.end(content, 'utf-8'); //set response content - reject(content); - //console.log(content); //debug - }); - } - else { - response.writeHead(404, { 'Content-Type': 'text/html' }); - let content = `

Error: ${error.code}

` - if(served?.pages?._all || served?.pages?.[message.route]) { - let {templateString, headers} = this.injectPageCode(content.toString(),message.route,served as any) as any; - content = templateString; - } - response.end(content,'utf-8'); - reject(error.code); - //return; - } - } - else { //other error - response.writeHead(500); //set response headers - response.end('Something went wrong: '+error.code+' ..\n','utf-8'); //set response content - reject(error.code); - //return; - - } - } - else { //file read successfully, serve the content back - - //set content type based on file path extension for the browser to read it properly - var extname = String(path.extname(requestURL)).toLowerCase(); - - var contentType = this.mimeTypes[extname] || 'application/octet-stream'; - - let head = { 'Content-Type': contentType }; - - if(contentType === 'text/html' && (served?.pages?._all || served?.pages?.[message.route])) { - let {templateString, headers} = this.injectPageCode(content.toString(),message.route, served as any) as any; - Object.assign(head, headers); - content = templateString; - } - - response.writeHead(200, head); //set response headers - response.end(content, 'utf-8'); //set response content - resolve(content); - - //console.log(content); //debug - //return; - } - } - - //internal - responsePromiseHandler = (resolve, reject, message, request:http.IncomingMessage, response:http.ServerResponse, method:string, served:ServerInfo) => { - - response.on('error', (err) => { - if(served.debug) { - let time = getHoursAndMinutes(new Date()); - console.error(time,'| Response Error: ', err, ' From: ', request.socket?.remoteAddress, ' For: ', request.url, ' | ', request.method); - } - this.responseOnErrorPromiseHandler(response, reject, err); - request.destroy(); - request.socket?.destroy(); - }); - - if(method === 'GET' || method === 'get') { - //process the request, in this case simply reading a file based on the request url - var requestURL = '.' + request.url; - if(request.url && this.restrict?.[request.url]) reject(request.url); - - if (requestURL == './' && served?.startpage) { //root should point to start page - requestURL = served.startpage; //point to the start page - } - - //lets remove ? mark url extensions for now - if(requestURL.includes('?')) requestURL = requestURL.substring(0,requestURL.indexOf('?')); - - if((request.url !== '/' || served?.startpage) && fs.existsSync(path.join(process.cwd(),requestURL))) { - if(response.writableEnded || response.destroyed) reject(requestURL); - else { - //read the file on the server - fs.readFile(path.join(process.cwd(),requestURL), (error, content) => { - this.onRequestFileReadPromiseHandler(error, content, resolve, reject, requestURL, response, message, served); - }); - } - } else if (message.route) { - let route; - if(served) { - let rt = `${served.port}/${message.route}`; - if(this.__node.nodes.get(rt)) route = rt - } - if(!route && this.__node.nodes.get(message.route)) route = message.route; - - if(route) { - let res:any; - if(message.method) { - res = this.handleMethod(route, message.method, undefined); //these methods are being passed request/response in the data here, post methods will parse the command objects instead while this can be used to get html templates or play with req/res custom callbakcs - } - else if (message.node) { - res = this.handleGraphNodeCall(message.node, undefined); - } - else res = this.handleServiceMessage({route,args:undefined,method:message.method}); - - if(res instanceof Promise) res.then((r) => { - if(served?.keepState) this.setState({[served.address]:res}); - this.withResult(response,r,message); - resolve(res); - - //return; - }) - else if(res) { - if(served?.keepState) this.setState({[served.address]:res}); - this.withResult(response,res,message); - resolve(res); - // return; - } //else we can move on to check the get post - } - else if (message.redirect) { - response.writeHead(301, {'Location':message.redirect}); - response.end(); - resolve(true); - } - else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served); - } else this.getFailedPromiseHandler(resolve,reject,requestURL,message,response,served); - } else { - //get post/put/etc body if any - let requestBody; - let timedOut = true; - let timeout; - - request.on('data',(chunk)=>{ //https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ - if(!requestBody) requestBody = [] as any[]; - requestBody.push(chunk); - if(timedOut) { - timedOut = false; - if(timeout) clearTimeout(timeout); - } - }).on('end',() => { - this.handleBufferedPostBodyPromiseHandler(resolve,requestBody,message,response,served); - }); - - //timeout posts/puts/etc if no body - timeout = setTimeout(() => { - if(timedOut) { - let errMessage = new Error(`Request timed out from | ${request.socket?.remoteAddress} | For: ${request.url} | ${request.method}`); - request.destroy(errMessage); - served.server.emit('clientError', errMessage, request.socket); - if(served.debug) { - console.error(errMessage); - } - reject(errMessage); - } - }, served.timeout ? served.timeout : 1000); //most likely an unhandled method - - } - - - } - - request = ( - options:ReqOptions|any, - send?:any, - ondata?:(chunk:any)=>void, - onend?:()=>void - ) => { - - let client = http; - - if ((options.protocol as string)?.includes('https')) { - client = https as any; - } - - delete options.protocol; - - const req = client.request(options,(res)=>{ - if(ondata) res.on('data',ondata) - if(onend) res.on('end',onend); - }); - - if(options.headers) { - for(const head in options.headers) { - req.setHeader(head,options.headers[head]) - } - } - - if(send) req.write(send); - req.end(); - - return req; - } - - POST = ( - url:string|URL, - data:any, - headers?:{ - 'Content-Type'?:string, - 'Content-Length'?:number, - [key:string]:any - } - ) => { - - let urlstring = url; - if(urlstring instanceof URL) urlstring = url.toString(); - let protocol = urlstring.startsWith('https') ? 'https' : 'http'; - let host, port,path; - let split = urlstring.split('/'); - split.forEach((s) => { - if(s.includes(':')) { - let ss = s.split(':'); - host = ss[0]; port = ss[1]; - } - }); - - if(split.length > 3) { - path = split.slice(3).join('/'); - } - - let req = this.request( - { - protocol, - host, - port, - path, - method:'POST', - headers - }, - data - ); - - return req; - } - - GET = (url:string|URL|http.RequestOptions) => { - return new Promise((resolve, reject) => { - - let client = http; - - let urlstring = url; - if(url instanceof URL) urlstring = url.toString(); - - if ((urlstring as string).includes('https')) { - client = https as any; - } - - client.get(url, (resp) => { - let chunks:any[] = []; - - // A chunk of data has been recieved. - resp.on('data', (chunk) => { - chunks.push(chunk); - }); - - // The whole response has been received. Print out the result. - resp.on('end', () => { - resolve(Buffer.concat(chunks)); - }); - - }).on("error", (err) => { - reject(err); - }); - }); - } - - terminate = (served:string|ServerInfo) => { - if(typeof served === 'string') served = this.servers[served]; - - if(typeof served === 'object') { - served.server.close(); - if(served.onclose) served.onclose(served); - } - } - - getRequestBody(req:http.IncomingMessage) { - let chunks:any[] = []; - return new Promise((resolve,reject) => { - req.on('data',(chunk) => { - chunks.push(chunk); - }).on('end',() => { - resolve(Buffer.concat(chunks)); - }).on('error',(er)=>{ - let errMessage = new Error(`Request timed out from | ${req.socket?.remoteAddress} | For: ${req.url} | ${req.method}`); - req.destroy(errMessage); - reject(errMessage); - }) - }); - } - - //??? just need a way to pass a fake request/response in - // spoofRequest = (url:string, body:any, type:string='json', server:http.Server|https.Server) => { - // return this.receive({ - // route:url, - // args:{request:{ - // url, - // } as http.IncomingMessage, response:{} as http.ServerResponse}, - // method:'GET' - // }) - // } - - addPage = (path:string, template:string) => { //add an html page template as a get - if(typeof template === 'string') { - if(!template.includes(''; //add a root - } - if(typeof this.__node.roots?.[path] === 'object') { - (this.__node.roots[path] as any).get = template; - this.__node.nodes.get(path).get = template; - } - else this.load({ - [path]: { - get:template - } - }); - } - - addHTML = (path:string, template:string) => { //add an html component template e.g. route: component/button then set up logic to chain - if(typeof template === 'string') { - if(!template.includes('<') || (!template.includes('>'))) template = '
'+template+'
'; - } - if(typeof this.__node.roots?.[path] === 'object') { - (this.__node.roots[path] as any).get = template; - this.__node.nodes.get(path).get = template; - } - else this.load({ - [path]: { - get:template - } - }); - } - - buildPage = (pageStructure:{[key:string]:{}|null|any} | string[] | string | ((...args:any)=>any), baseTemplate:string) => { //construct a page from available components, child component templates will be inserted before the last '<' symbol or at end of the previous string depending - let result = ``; if(baseTemplate) result += baseTemplate; - let appendTemplate = (obj:{[key:string]:{}|null|any}|string[],r:string|any, res:string) => { - if(!Array.isArray(obj[r]) && typeof obj[r] === 'object') { - for(const key in obj) { - appendTemplate(obj, key, res); //recursive append - } - } else if(this.__node.nodes.get(r)?.get) { - let toAdd = this.__node.nodes.get(r)?.get; - if(typeof toAdd === 'function') { - if(Array.isArray(obj[r])) { - toAdd = toAdd(...obj[r]); - } - else toAdd = toAdd(obj[r]); - } - if(typeof toAdd === 'string') { - let lastDiv = res.lastIndexOf('<'); - if(lastDiv > 0) { - let end = res.substring(lastDiv) - res = res.substring(0,lastDiv) + toAdd + end; - } else res += toAdd; - } - - } else if (this.__node.nodes.get(r)?.__operator) { - let routeresult; - if(this.__node.nodes.get(r)?.__operator) routeresult = this.__node.nodes.get(r).__operator(obj[r]); - if(typeof routeresult === 'string') { - let lastDiv = res.lastIndexOf('<'); - if(lastDiv > 0) { - let end = res.substring(lastDiv) - res = res.substring(0,lastDiv) + routeresult + end; - } - else res += routeresult; - //console.log(lastDiv, res, routeresult) - } - } else if (typeof this.__node.nodes.get(r) === 'string') res += this.__node.nodes.get(r); - return res; - } - - if(Array.isArray(pageStructure)) { - pageStructure.forEach((r)=>{ - result = appendTemplate(pageStructure, r, result); - }) - } else if (typeof pageStructure === 'object') { - for(const r in pageStructure) { - result = appendTemplate(pageStructure, r, result); - } - } else if (typeof pageStructure === 'string') result += pageStructure; - else if (typeof pageStructure === 'function') result += pageStructure(); - return result; - } - - hotreload = (socketURL:string|URL=`http://localhost:8080/wss`, esbuild_cssFileName?:string) => { - if(socketURL instanceof URL) socketURL = socketURL.toString(); - - - const HotReloadClient = (socketUrl, esbuild_cssFileName) => { - //hot reload code injected from backend - //const socketUrl = `ws://${cfg.host}:${cfg.hotreload}`; - let socket = new WebSocket(socketUrl); - - - function reloadLink(file?) { - - let split = file.includes('/') ? file.split('/') : file.split('\\'); - let fname = split[split.length-1]; - - var links = document.getElementsByTagName("link") as any as HTMLLinkElement; - for (var cl in links) - { - var link = links[cl]; - - if(!file || link.href?.includes(fname)) { - let href = link.getAttribute('href') - .split('?')[0]; - - let newHref = href += ""; - - link.setAttribute('href', newHref); - - } - } - } - - - function reloadAsset(file, reloadscripts?, isJs?) { //reloads src tag elements - let split = file.includes('/') ? file.split('/') : file.split('\\'); - let fname = split[split.length-1]; - let elements = document.querySelectorAll('[src]') as any as HTMLScriptElement[]; - let found = false; - for(const s of elements) { - if(s.src.includes(fname)) { //esbuild compiles entire file so just reload app - if(s.tagName === 'SCRIPT' && !reloadscripts) {//&& s.tagName === 'SCRIPT' - window.location.reload(); - return; - } else { - let placeholder = document.createElement('object'); - s.insertAdjacentElement('afterend', placeholder); - s.remove(); - let elm = s.cloneNode(true) as HTMLElement; - placeholder.insertAdjacentElement('beforebegin',elm); - placeholder.remove(); - found = true; - } - } - } - if(!found) window.location.reload(); - } - - - socket.addEventListener('message',(ev) => { - let message = ev.data; - - if(typeof message === 'string' && message.startsWith('{')) { - message = JSON.parse(message); - } - if(message.file) { - let f = message.file; - let rs = message.reloadscripts; - if(f.endsWith('html') || f.endsWith('xml') || f.endsWith('wasm')) { //could add other formats - window.location.reload(); - } else if(f.endsWith('css')) { - if(!esbuild_cssFileName.endsWith('css')) esbuild_cssFileName += '.css'; - reloadLink(esbuild_cssFileName); //reload all css since esbuild typically bundles one file same name as the dist file - } else if (f.endsWith('js') || f.endsWith('ts') || f.endsWith('jsx') || f.endsWith('tsx') || f.endsWith('vue')) { //IDK what other third party formats would be nice to haves - reloadAsset(f, rs); - } else { - //could be an href or src - reloadLink(f); - reloadAsset(f); - } - } - }); - - - socket.addEventListener('close',()=>{ - // Then the server has been turned off, - // either due to file-change-triggered reboot, - // or to truly being turned off. - - // Attempt to re-establish a connection until it works, - // failing after a few seconds (at that point things are likely - // turned off/permanantly broken instead of rebooting) - const interAttemptTimeoutMilliseconds = 100; - const maxDisconnectedTimeMilliseconds = 3000; - const maxAttempts = Math.round(maxDisconnectedTimeMilliseconds/interAttemptTimeoutMilliseconds); - let attempts = 0; - const reloadIfCanConnect = ()=>{ - attempts ++ ; - if(attempts > maxAttempts){ - console.error("Could not reconnect to dev server."); - return; - } - socket = new WebSocket(socketUrl); - socket.onerror = (er) => { - console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`); - } - socket.addEventListener('error',()=>{ - setTimeout(reloadIfCanConnect,interAttemptTimeoutMilliseconds); - }); - socket.addEventListener('open',()=>{ - location.reload(); - }); - }; - reloadIfCanConnect(); - }); - } - - return ` - - `; - } - - pwa = (pwaName = "PWA", cacheExpirationDays=4/24, serviceWorkerUrl="service-worker.js") => { - - //check for serviceWorkerUrl, if none install the default template - if(!fs.existsSync(serviceWorkerUrl)) { - fs.writeFileSync(path.join(process.cwd(),serviceWorkerUrl), defaultServiceWorker(cacheExpirationDays)); - } - if(!fs.existsSync('manifest.webmanifest')) { - fs.writeFileSync(path.join(process.cwd(),'/manifest.webmanifest'), defaultManifest(pwaName)); - } - - function ServiceWorkerInstaller(serviceWorkerUrl) { - // Check that service workers are supported - - if(!Array.from(document.head.querySelectorAll('link')).find((elm:HTMLLinkElement) => { - if(elm.href.includes('manifest')) return true; - })) { - document.head.insertAdjacentHTML('beforeend',``) - } - - const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) - ); - - function registerSW() { - navigator.serviceWorker - .register(serviceWorkerUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated pre-cached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all tabs for this page are closed.' - ); - - } else { - // At this point, everything has been pre-cached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); - } - - if ("serviceWorker" in navigator) addEventListener('load', () => { - if(isLocalhost) { - // Add some additional logging to localhost, pointing developers to the - - // Check if the service worker can be found. If it can't reload the page. - fetch(serviceWorkerUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerSW(); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); - - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log('This web app is being served cache-first by a service worker.'); - }); - } - else { - registerSW(); - } - }); - } - - return ` - - `; - } - -} - - - -function getPageOptions(url, received, pages, request, response, port) { - let pageOptions = pages[url]; - let key = url; - //check alternative page definition keys - if(!pageOptions) { - let url2 = '/'+url; // e.g. '/home' - pageOptions = pages[url2]; - key = url2; - if(!pageOptions && !path.extname(url)) { - let split = url.split('/'); - key = split[0]+'/*'; - if(pages[key]) { // e.g. /* or home/* - pageOptions = pages[key]; - received.route = key; - request.url = key; - } else { - // e.g. /home with /* specified, or /home/* etc. - let spl = url2.split('/'); //split the modified string so the beginning is a blank string - spl[spl.length-1] = ''; //replace with empty string e.g. /home -> ['',''] - key = spl.join('/')+'*'; //now merge url - if(pages[key]) { - pageOptions = pages[key]; - received.route = key; - request.url = key; - } - } - } else { - received.route = url2; - request.url = url2; - - } - } else { - received.route = url; - request.url = url; - } - if(typeof pageOptions === 'object') { - if((pageOptions as any).redirect) { - url = (pageOptions as any).redirect; - received.redirect = url; - received.route = url; - } - if((pageOptions as any).onrequest) { - if(typeof (pageOptions as any).onrequest === 'string') { - (pageOptions as any).onrequest = this.__node.nodes.get((pageOptions as any).onrequest); - } - if(typeof (pageOptions as any).onrequest === 'object') { - if((pageOptions as any).onrequest.__operator) { - ((pageOptions as any).onrequest as GraphNode).__operator(pageOptions, request, response); - } - } else if(typeof (pageOptions as any).onrequest === 'function') { - (pageOptions as any).onrequest( - this, - this.__node.nodes.get(`${port}/${key}`), - request, - response - ); - } - } - } - - return pageOptions; -} - - - - -function getHoursAndMinutes(date) { - let hours = date.getHours(); - let minutes = date.getMinutes(); - - // Convert the hours and minutes to two digits - hours = hours < 10 ? '0' + hours : hours; - minutes = minutes < 10 ? '0' + minutes : minutes; - - return `${hours}:${minutes}`; -} diff --git a/src/services/http/boilerplate/index.ts b/src/services/http/boilerplate/index.ts deleted file mode 100644 index 40fd5c34..00000000 --- a/src/services/http/boilerplate/index.ts +++ /dev/null @@ -1,133 +0,0 @@ - -export function htmlBodyBoilerPlate(html:string|string[]) { - let template = `` - if(Array.isArray(html)) { - html.forEach((src) => { - template += src; - }) - } else { - template += html; - } - template += `` - return template; -} - -export function scriptBoilerPlate(scripts:string|string[]) { - let template = `` - if(Array.isArray(scripts)) { - scripts.forEach((src) => { - template += ``; - }) - } else { - template += ``; - } - template += `` - return template; -} - - - -export const defaultServiceWorker = function (cacheExpirationDays=4/24) { //service-worker.js template for PWA - return `//https://github.com/ibrahima92/pwa-with-vanilla-js - -//https://github.com/ibrahima92/pwa-with-vanilla-js -let cacheName = 'pwa-assets'; -const assets = [ - "/", - "/index.html", - "/dist/index.css", //alt default paths - "/dist/index.js", - '/favicon.ico' -]; - -let cacheExpiration = 1000 * 60 * //seconds - 60 * //minutes - 24 * //hours - ${cacheExpirationDays}; //days - -let isValid = function (response) { - if (!response) return false; - var fetched = response.headers.get('sw-fetched-on'); - if (fetched && (!navigator.onLine || (parseFloat(fetched) + (cacheExpiration)) > new Date().getTime())) - return true; - return false; -}; - -self.addEventListener("install", installEvent => { - installEvent.waitUntil( - caches.open(cacheName).then(cache => { - cache.addAll(assets); - }) - ); -}); - -self.addEventListener("fetch", fetchEvent => { //https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/ - fetchEvent.respondWith( - caches.match(fetchEvent.request).then(function (response) { - - // If there's a cached API and it's still valid, use it - if (isValid(response)) { - return response; - } - - // Otherwise, make a fresh API call - if(response && !assets.includes(fetchEvent.request.url)) return response; - // Otherwise, make a fresh API call - else return fetch(fetchEvent.request).then(function (response) { - - // Cache for offline access - if(assets.includes(fetchEvent.request.url)){ - var copy = response.clone(); - fetchEvent.waitUntil(caches.open(cacheName).then(function (cache) { - var headers = new Headers(copy.headers); - headers.append('sw-fetched-on', new Date().getTime()); - return copy.blob().then(function (body) { - return cache.put(fetchEvent.request, new Response(body, { - status: copy.status ? copy.status : 200, - statusText: copy.statusText, - headers: headers - })); - }); - })); - } - - // Return the requested file - return response; - - }) - // .catch(function (error) { - // return caches.match(request).then(function (response) { //fallback to offline cache - // return response || caches.match('/offline.json'); //todo: figure out what is supposed to go in offline.json (https://gomakethings.com/how-to-set-an-expiration-date-for-items-in-a-service-worker-cache/) - // }); - // }); - })); -}); - -`; -} - -//todo: make this even more customizable, just being lazy for now -export const defaultManifest = (pwaName = "PWA") => { - return `{ - "short_name": "${pwaName}", - "name": "${pwaName}", - "start_url": "/", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "description": "${pwaName} Test", - "lang": "en-US", - "permissions": [ - "storage" - ], - "icons":[{ - "src": "./assets/logo196.png", - "sizes": "196x196" - }, - { - "src": "./assets/logo512.png", - "sizes": "512x512" - }] -}` //images are REQUIRED for PWA to work -} - diff --git a/src/services/http/boilerplate/pwa/README.md b/src/services/http/boilerplate/pwa/README.md deleted file mode 100644 index febdc916..00000000 --- a/src/services/http/boilerplate/pwa/README.md +++ /dev/null @@ -1,26 +0,0 @@ -## [Instructions](https://dev.to/digitalplayer1125/custom-service-worker-in-any-app-with-esbuild-3020) - - -### Compile & inject: - -Copy manifest.webmanifest to main folder of your app and customize. - -Code to paste or inject into html pages (our server does this if you specify the service-worker path in the server_settings.js file): -```html - - - - - - - -``` \ No newline at end of file diff --git a/src/services/http/boilerplate/pwa/manifest.webmanifest b/src/services/http/boilerplate/pwa/manifest.webmanifest deleted file mode 100644 index 0111fba1..00000000 --- a/src/services/http/boilerplate/pwa/manifest.webmanifest +++ /dev/null @@ -1,22 +0,0 @@ -{ - "short_name": "PWA", - "name": "PWA", - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "description": "PWA Test", - "lang": "en-US", - "permissions": [ - "storage" - ], - "icons":[{ - "src": "./assets/logo196.png", - "sizes": "196x196" - }, - { - "src": "./assets/logo512.png", - "sizes": "512x512" - } - ] - } \ No newline at end of file diff --git a/src/services/http/boilerplate/pwa/service-worker-complex.js b/src/services/http/boilerplate/pwa/service-worker-complex.js deleted file mode 100644 index 4e841407..00000000 --- a/src/services/http/boilerplate/pwa/service-worker-complex.js +++ /dev/null @@ -1,120 +0,0 @@ -// This optional code is used to register a service worker. -// register() is not called by default. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on subsequent visits to a page, after all the -// existing tabs open on the page have been closed, since previously cached -// resources are updated in the background. - -const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -export function register(config) { - if ('serviceWorker' in navigator) { - window.addEventListener('load', () => { - const swUrl = "service-worker.js"; - - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log('This web app is being served cache-first by a service worker.'); - }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } -} - -function registerValidSW(swUrl, config) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated pre-cached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all ' + - 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' - ); - - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been pre-cached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); -} - -function checkValidServiceWorker(swUrl, config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); -} - -export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); - } -} diff --git a/src/services/http/boilerplate/pwa/service-worker.js b/src/services/http/boilerplate/pwa/service-worker.js deleted file mode 100644 index 5aad496f..00000000 --- a/src/services/http/boilerplate/pwa/service-worker.js +++ /dev/null @@ -1,81 +0,0 @@ - -//https://github.com/ibrahima92/pwa-with-vanilla-js -const version = '1.0'; // Increment this version to update all caches -const cacheNamePrefix = 'pwa-assets-'; -const cacheName = `${cacheNamePrefix}${version}`; -const assets = [ - "/", - "/index.html", - "/dist/index.css", //alt default paths - "/dist/index.js", - '/favicon.ico' -]; - -let cacheExpiration = 1000 * 60 * //seconds - 60 * //minutes - 24 * //hours - (4/24); //days (4 hours in this case) - -// Function to check if a cache name represents an expired cache -let isValidCacheName = function(cacheName) { - const cacheTimestamp = parseInt(cacheName.split('-').pop()); - const currentTime = new Date().getTime(); - return currentTime < cacheTimestamp + cacheExpiration; -}; - -self.addEventListener('fetch', event => { - event.respondWith( - caches.match(event.request).then(cachedResponse => { - - // Check if online; if not, return cached response immediately - if (!navigator.onLine) { - return cachedResponse; - } - - // Serve from cache if valid, otherwise fetch from network - return caches.keys().then(cacheNames => { - const relevantCacheName = cacheNames.find(name => name.startsWith(cacheNamePrefix)); - if (relevantCacheName && isValidCacheName(relevantCacheName)) { - return cachedResponse || fetchAndUpdateCache(event.request, relevantCacheName); - } else { - return fetchAndUpdateCache(event.request, cacheName); - } - }); - }) - ); -}); - -function fetchAndUpdateCache(request, cacheName) { - return fetch(request).then(response => { - // Only cache GET requests to whitelisted assets - if (request.method === 'GET' && assets.includes(new URL(request.url).pathname)) { - const responseToCache = response.clone(); - caches.open(cacheName).then(cache => { - cache.put(request, responseToCache); - }); - } - return response; - }).catch(() => { - // Attempt to serve from cache if the network request fails - return caches.match(request); - }); -} - -self.addEventListener('activate', event => { - event.waitUntil( - caches.keys().then(cacheNames => { - return Promise.all( - cacheNames.filter(name => name.startsWith(cacheNamePrefix) && !isValidCacheName(name)) - .map(invalidCacheName => caches.delete(invalidCacheName)) - ); - }).then(() => self.clients.claim()) - ); -}); - -self.addEventListener('install', event => { - event.waitUntil( - caches.open(cacheName) - .then(cache => cache.addAll(assets)) - .then(() => self.skipWaiting()) - ); -}); diff --git a/src/services/remote/remote.routes.ts b/src/services/remote/remote.routes.ts deleted file mode 100644 index e7f98bc7..00000000 --- a/src/services/remote/remote.routes.ts +++ /dev/null @@ -1,427 +0,0 @@ -import { getFnParamNames, getFunctionHead, parseFunctionFromText, recursivelyStringifyFunctions, stringifyWithCircularRefs, stringifyWithFunctionsAndCircularRefs } from "../utils" -import { Graph, GraphNodeProperties, Listener } from "../../core/Graph" -import { methodstrings } from "../../loaders/methodstrings"; -import { recursivelyAssign } from "../Service"; - -export const nodeTemplates = {}; - -//Contains evals and other things you probably don't want wide open on an API, for running graphs over remote contexts -export const remoteGraphRoutes = { - - transferNode: ( - properties:Function|(GraphNodeProperties & { __methods?:{[key:string]:Function|string} })|string, - connection:any | Worker | WebSocket, //put any info connection template in with - name?:string - ) => { - let str; - if(typeof properties === 'object') { - if(!properties.__node) { properties.__node = {}; } - if(name) properties.__node.tag = name; - - for(const key in properties) { - if(typeof properties[key] === 'function') { - if(!properties.__methods) properties.__methods = {}; - properties.__methods[key] = properties[key].toString(); - } - } - - str = recursivelyStringifyFunctions(properties); - - } else if (typeof properties === 'function') str = properties.toString(); - else if (typeof properties === 'string') str = properties; - if(str) { - - if((connection as any).run) - return (connection as any).run('setNode',[str]); - else if ((connection as Worker).postMessage) { - (connection as Worker).postMessage({route:'setNode', args:str},undefined); - return new Promise ((r) => r(name)); - } else if ((connection as WebSocket).send) { - (connection as WebSocket).send(JSON.stringify({route:'setNode', args:str})); - return new Promise ((r) => r(name)); - } - } - - }, - - setNode:function ( - properties:string|((...args:[])=>any)|(GraphNodeProperties & { __methods?:{[key:string]:Function|string} }), name?:string - ) { - //console.log('setting node', properties); - if(typeof properties === 'object') { - if(properties.__methods) { //stringified methods - if(!this.__node.graph.__node.loaders.methodstrings) { - this.__node.graph.__node.loaders.methodstrings = methodstrings; - } - } - } - if(typeof properties === 'string') { - let f = parseFunctionFromText(properties); - if(typeof f === 'function') properties = {__operator:f, __node:{tag:name ? name : f.name}}; - else { - f = JSON.parse(properties); - if(typeof f === 'object') properties = f; - } - } - if(typeof properties === 'object' || typeof properties === 'function') { - let template = {} as GraphNodeProperties; - if(typeof properties === 'object') Object.assign(template,properties); - else template.__operator = properties; - let node = this.__node.graph.add(template); - if(node) { - nodeTemplates[node.__node.tag] = template; //can just instantiate this again later - return node.__node?.tag; - } else return false; - } else return false; - }, - - makeNodeTransferrable:function ( - properties:GraphNodeProperties, - name?:string - ) { - if(!properties.__node) { properties.__node = {}; } - if(name) properties.__node.tag = name; - - for(const key in properties) { - if(typeof properties[key] === 'function') { - if(!properties.__methods) properties.__methods = {}; - properties.__methods[key] = properties[key].toString(); - } - } - - const str = recursivelyStringifyFunctions(properties); - - return str; - }, - - - getListenerJSON: function () { //reproducible json prototype, apply as __listeners in graph.load({__listeners:{...}}) - const triggers = this.__node.state.triggers; - let result = {} as any; - for(const key in triggers) { - triggers[key].forEach((trigger) => { - let t = trigger as any as Listener; - if(!result[t.target]) result[t.target] = {}; - let l = t.source + (t.key ? '.' + t.key : ''); - result[t.target][l] = { - __callback:t.__callback - } - if(t.__args) result[t.target][l].__args = t.__args; - if(t.subInput) result[t.target][l].subInput = t.subInput; - - }) - } - return result; - }, - - makeRootTransferrable: function () { - let roots = {}; - for(const r in this.__node.graph.__node.roots) { - let properties = this.__node.graph.__node.roots[r]; - if(typeof properties === 'function') { - roots[r] = properties.toString(); - } else if (typeof properties !== 'object') { - roots[r] = properties; - } else { - roots[r] = {}; - let keys = Object.getOwnPropertyNames(properties).filter((v) => !objProps.includes(v)); - //console.log([...keys]); - let nonArrowFunctions = Object.getOwnPropertyNames(Object.getPrototypeOf(properties)).filter((v) => !objProps.includes(v)); - keys.push(...nonArrowFunctions); //this is weird but it works - for(const key of keys) { - if(typeof properties[key] === 'function') { - roots[r][key] = properties[key].toString(); - } else if(typeof properties[key] === 'object') - roots[r][key] = stringifyWithFunctionsAndCircularRefs(properties[key]); - else roots[r][key] = properties[key]; - } - } - } - - return roots; - }, - - setTemplate:function( - properties:string|((...args:[])=>any)|(GraphNodeProperties & { __methods?:{[key:string]:Function|string} }), - name?:string - ) { - if(typeof properties === 'object') { - if(properties.__methods) { //stringified methods - if(!this.__node.graph.__node.loaders.methodstrings) { - this.__node.graph.__node.loaders.methodstrings = methodstrings; - } - } - } - if(typeof properties === 'string') { - let f = parseFunctionFromText(properties); - if(typeof f === 'function') { - if(!name) name = f.name; - properties = {__operator:f, __node:{tag:name}}; - } - else { - f = JSON.parse(properties); - if(typeof f === 'object') { - properties = f; - if(!name && f.__node?.tag) name = f.__node.tag; - } - } - } - if(!name) name = `node${Math.floor(Math.random()*1000000000000000)}` - if(typeof properties === 'object' || typeof properties === 'function') { - nodeTemplates[name] = properties; - return name; - } else return false; - }, - - loadFromTemplate:function( - templateName:string, - name?:string, - properties?:{[key:string]:any} - ) { - if(nodeTemplates[templateName]) { - let cpy = recursivelyAssign({},nodeTemplates[templateName]); - if(name) { - if(!cpy.__node) cpy.__node = {}; - cpy.__node.tag = name; - } - if(properties) Object.assign(cpy,properties); - let node = this.__node.graph.add(cpy); - return node.__node.tag; - } - }, - - setMethod:function( - nodeTag:string, - fn:string|((...args:[])=>any), - methodKey?:string - ){ //set a method on a route - //console.log(fn, fnName) - if(typeof fn === 'string') { - let f = parseFunctionFromText(fn); - if(typeof f === 'function') fn = f; - } - //console.log(fn); - if(!methodKey && typeof fn === 'function') methodKey = fn.name; - if(this.__node.graph.get(nodeTag)) { - this.__node.graph.get(nodeTag)[methodKey] = fn; //overwrite method - } - else (this.__node.graph as Graph).add({__node:{tag:methodKey,[methodKey]:fn}}); - //console.log(this) - return true; - }, - - assignNode:function(nodeTag:string,source:{[key:string]:any}) { //set values on a node - //console.log(fn, fnName) - if(this.__node.graph.get(nodeTag) && typeof source === 'object') { - Object.assign(this.__node.graph.get(nodeTag),source); - } - }, - - getNodeProperties:function(nodeTag:string) { - let node = this.__node.graph.get(nodeTag); - if(node) { - let properties = Object.getOwnPropertyNames(node); - let result = {}; - for(const key of properties) { - if(typeof node[key] === 'function') { - let str = node[key].toString() as string; - let isNative = str.indexOf('[native code]') > -1; - result[key] = { type:'function', args:getFnParamNames(node[key]), native:isNative} - } - else result[key] = typeof node[key]; - } - return result; - } return undefined; - }, - - proxyRemoteNode : function ( - name:string, - connection:any, //put any info connection template in with a .run function, does not work with base workers/sockets etc as it relies on our promise system - ):Promise { - - return new Promise((res,rej) => { - connection.run('getNodeProperties',name).then((props:any)=>{ - let proxy = {}; - if(typeof props === 'object') { - for(const key in props) { - if(props[key]?.type === 'function') { - if(props[key].native || props[key].args) { - proxy[key] = (...args:any[]) => { - return new Promise((r) => { - connection.run( - name, - args, - key - ).then(r); - }); - } - } - //else if(props[key].args) { //not easy to set arguments from remote, anonymous bound functions are unparseable - // let scope = { - // connection - // } as any; - // proxy[key] = new Function( - // ...props[key].args,//...args:any[]) => { //no way to transfer args to this function? - // `return new Promise((r) => { - // this.connection.run( - // ${name}, - // [${props[key].args.join(',')}], - // ${key} - // ).then(r); - // });` - // ).bind(scope); //will show up as "bound anonymous" but the arguments are parseable - // //console.log(getFunctionHead(proxy[key].toString()).split('(')[1].split(')')[0]); - //} - else { - proxy[key] = () => { - return new Promise((r) => { - connection.run( - name, - undefined, - key - ).then(r); - }); - } - } - } else { - Object.defineProperty( - proxy, - key, - { - get:()=>{ - return new Promise((r)=>{ - connection.run( - name, - undefined, - key - ).then((r)) - }); - }, - set:(value) => { - connection.post( - name, - value, - key - ) - }, - configurable:true, - enumerable:true - } - ) - } - } - } - - res(proxy); - - }); - }); - }, - - transferClass:( - classObj:any, - connection:any | Worker | WebSocket, - className?:string - )=>{ //send a class over a remote service - if(typeof classObj === 'object') { - let str = classObj.toString();//needs to be a class prototype - let message = {route:'receiveClass',args:[str,className]}; - if((connection as any).run) - return (connection as any).run('receiveClass',[str,className]); - else if ((connection as Worker).postMessage) { - (connection as Worker).postMessage({route:'receiveClass', args:[str,className]},undefined); - return new Promise ((r) => r(name)); - } else if ((connection as WebSocket).send) { - (connection as WebSocket).send(JSON.stringify({route:'receiveClass', args:[str,className]})); - return new Promise ((r) => r(name)); - } - return message; - } - return false; - }, - - receiveClass:function(stringified:string, className?:string){ //eval a class string and set it as a key on the local graph by class name, so this.__node.graph.method exists - if(typeof stringified === 'string') { - //console.log(stringified) - if(stringified.indexOf('class') === 0) { - let cls = (0,eval)('('+stringified+')'); - let name = className; - - if(!name) - name = cls.name; //get classname - this.__node.graph[name] = cls; - - return true; - } - } - return false; - }, - - //requires unsafe service to load on other end - transferFunction: (fn:Function, connection:any | Worker | WebSocket, fnName?:string) => { - if(!fnName) fnName = fn.name; - let str = fn.toString();//needs to be a class prototype - let message = {route:'setNode',args:[str,fnName]}; - if((connection as any).run) - return (connection as any).run('setNode',[str,fnName]); - else if ((connection as Worker).postMessage) { - (connection as Worker).postMessage({route:'setNode', args:[str,fnName]},undefined); - return new Promise ((r) => r(fnName)); - } else if ((connection as WebSocket).send) { - (connection as WebSocket).send(JSON.stringify({route:'setNode', args:[str,fnName]})); - return new Promise ((r) => r(fnName)); - } - return message; - }, - - setGlobal:(key:string, value:any) => { //set a value on the globalThis scope - globalThis[key] = value; - return true; - }, - - assignGlobalObject:(target:string, source:{[key:string]:any}) => { //assign a value on an object on the globalThis scope - if(!globalThis[target]) return false; - if(typeof source === 'object') Object.assign(globalThis[target],source); - return true; - }, - - setValue:function(key:string, value:any) { //set a value on the graph scope - this.__node.graph[key] = value; - return true; - }, - - assignObject:function(target:string, source:{[key:string]:any}){ //assign a value on an object on the globalThis scope - if(!this.__node.graph[target]) return false; - if(typeof source === 'object') Object.assign( this.__node.graph[target],source); - return true; - }, - - setGlobalFunction:(fn:any, fnName?:string) => { //set a value on the globalThis scope - if(typeof fn === 'string') fn = parseFunctionFromText(fn); - //console.log(fn); - if(typeof fn === 'function') { - if(!fnName) fnName = fn.name; - globalThis[fnName] = fn; - //console.log(this) - return true; - } - return false; - }, - - setGraphFunction:function(fn:any, fnName?:string){ //set a value on the graph scope - if(typeof fn === 'string') fn = parseFunctionFromText(fn); - //console.log(fn); - if(typeof fn === 'function') { - if(!fnName) fnName = fn.name; - this.__node.graph[fnName] = fn; - //console.log(this) - return true; - } - return false; - } - -} - -let objProps = Object.getOwnPropertyNames(Object.getPrototypeOf({})); - -//console.log(objProps); \ No newline at end of file diff --git a/src/services/todo/RemoteService.ts b/src/services/todo/RemoteService.ts deleted file mode 100644 index f2995ac5..00000000 --- a/src/services/todo/RemoteService.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { isNativeClass } from '../../core/Graph' -import {Service, ServiceMessage} from '../Service' - -//trying to generalize e.g. the Socket and Worker classes - -export class RemoteService extends Service { - - endpoints:{ - [key:string]:{ - connection:any, - postCmd:Function, - class:any, - classArgs?:any - } - } - - class:any; - onmessage:string; - close:string; - onerror?:string; - onclose?:string; - onmessageTransform?:(message:any) => any; - onerrorTransform?:(er:any) => any; - post:string; - - createConnection = (instanceArgs:any[], settings?:{[key:string]:Function}) => { - - let info = { - _id: `connection${Math.floor(Math.random()*1000000000000000)}` - } as any; - - if(typeof this.class === 'function') { - if(isNativeClass(this.class)) { - info.connection = new this.class(...instanceArgs); - } else { - info.connection = this.class(...instanceArgs); - } - } else info.connection = this.class; - - - //defaults - if(this.onmessage) { - info.connection[this.onmessage] = (message:any) => { - if(this.onmessageTransform) { - message = this.onmessageTransform(message); - } - this.receive(message); - this.setState({[info._id]:message}); - } - } - - if(this.onerror) { - info.connection[this.onerror] = (er) => { - if(this.onerrorTransform) er = this.onerrorTransform(er); - } - } - - //overwrite callbacks with settings - if(settings) { - for(const key in settings) { - info.connection[key] = settings[key]; - } - } - - return info; - } - - __wrapConnection = (info:any) => { - info.send = () => {}; - info.post = () => {}; - info.run = () => {}; - info.request = () => {}; - info.subscribe = () => {}; - info.unsubscribe = () => {}; - info.start = async () => {}; - info.stop = async () => {}; - info.terminate = () => {}; - return info; - } - - transmit = (message:ServiceMessage|any, endpoint:string|any, transformer?:(message:any,endpoint:any) => any[] ) => { - - // put in transformer - // if(!transfer) { - // transfer = this.getTransferable(message); //automatically transfer arraybuffers - // } - if(typeof endpoint === 'string') { - endpoint = this.endpoints[endpoint]; - } - - if(typeof endpoint === 'object') { - if(transformer) { - let args = transformer(message,endpoint) as any[]; - endpoint.connection[endpoint.post](...args); - } else { - endpoint.connection[endpoint.post](message); - } - - return true; - } - - return false; - } - -} \ No newline at end of file diff --git a/src/services/webrtc/WebRTC.browser.ts b/src/services/webrtc/WebRTC.browser.ts deleted file mode 100644 index a53cb43a..00000000 --- a/src/services/webrtc/WebRTC.browser.ts +++ /dev/null @@ -1,813 +0,0 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; - -//how it works: -//https://hacks.mozilla.org/2013/07/webrtc-and-the-ocean-of-acronyms/ - -export type WebRTCProps = { - _id?:string, - channels?:{ - [key:string]:(true|RTCDataChannelInit|RTCDataChannel) - }, - config?:RTCConfiguration, - description?:RTCSessionDescription|string, - offer?:RTCOfferOptions, - hostcandidates?:{[key:string]:RTCIceCandidate}, - peercandidates?:{[key:string]:RTCIceCandidate}, - candidates?:{[key:string]:RTCIceCandidate}, - answer?:RTCAnswerOptions, - ontrack?:(ev:RTCTrackEvent)=>void, - removetrack?:(ev:MediaStreamTrackEvent)=>void, //when a media stream track is removed by the peer - onicecandidate?:(ev:RTCPeerConnectionIceEvent)=>void, - onicecandidateerror?:(ev:Event)=>void, - onnegotiationneeded?:(ev:Event, description:RTCSessionDescription)=>void, - ondatachannel?:(ev:RTCDataChannelEvent)=>void, - ondata?:(ev:MessageEvent, channel:RTCDataChannel, room)=>void, - onconnectionstatechange?:(ev:Event)=>void, - oniceconnectionstatechange?:(ev:Event)=>void, - onclose?:(rtc:WebRTCInfo)=>void //custom callback - caller?:string, //e.g. caller's userId from Router - remoteId?:string, //e.g. set this when passing to the opposite user's 'receiveCallInformation' so you know which connection to call in the router for renegotiating - [key:string]:any //set whatever else for reference -} - -export type WebRTCInfo = { - _id:string, - rtc:RTCPeerConnection, - senders?:(RTCRtpSender|undefined)[], - receivers?:(RTCRtpReceiver|undefined)[], - streams?:(MediaStream|undefined)[], //received mediastreams - polite?:boolean, //peer will prevent race conditions for simultaneous negotiations - videoSender?:RTCRtpSender, //audio track channel - audioSender?:RTCRtpSender, //video track channel - videoStream?:MediaStream, //audio track channel - audioStream?:MediaStream, //video track channel - send:(message:any)=>void, //these callbacks work on the first available data channel to call to other webrtc services - request:(message:any, method?:string)=>Promise, - post:(route:any, args?:any)=>void, - run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string,args?:any[],key?:string,subInput?:boolean,channelId?:string)=>Promise, - unsubscribe:(route:any, sub:number)=>Promise, - terminate:()=>boolean, - graph:WebRTCfrontend -} & WebRTCProps - -//webrtc establishes secure P2P contexts between two users directly. -// However, we need a backend as a way to list available connections. -export class WebRTCfrontend extends Service { - - name='webrtc' - - rtc:{ - [key:string]:WebRTCInfo - } = {} - - unanswered:{ - [key:string]:WebRTCProps - } = {} - - iceServers:RTCIceServer[] = [ - { urls: ['stun:stun.l.google.com:19302'] }, - { urls: ['stun:stun1.l.google.com:19302'] }, - { urls: ['stun:stun2.l.google.com:19302'] }, - { urls: ['stun:stun3.l.google.com:19302'] }, - { urls: ['stun:stun4.l.google.com:19302'] } - ]; - - connections = { //higher level reference for router - rtc:this.rtc - } - - constructor( - options?:ServiceOptions, - iceServers?:RTCIceServer[] - ) { - super(options); - - if(iceServers) this.iceServers = iceServers; - - this.load(this); - //console.log(this) - } - - openRTC = async ( - options?:WebRTCProps - ):Promise => { - if(!options) options = {}; - if(!options._id) options._id = `rtc${Math.floor(Math.random()*1000000000000000)}`; - if(!options.config) options.config = {iceServers:this.iceServers}; - - - - if(!this.rtc[options._id]) { - let rtc = new RTCPeerConnection(options.config); - - if(!options.channels) options.channels = { 'data':true }; //need one channel at least for the default service stuff to work - - let firstChannel; - for(const key in options.channels) { - firstChannel = key; - break; - } - - let send = (message:any) => { - //console.log('sent', message) - return this.transmit(message,options._id,options.channels[firstChannel] as RTCDataChannel); - } - - let post = (route:any,args?:any, method?:string) => { - //console.log('sent', message) - let message:any = { - route, - args - }; - if(method) message.method = method; - - return this.transmit(message,options._id,options.channels[firstChannel] as RTCDataChannel); - } - - let run = (route:any,args?:any, method?:string):Promise => { - return new Promise ((res,rej) => { - let callbackId = Math.random(); - let req = {route:'runRequest', args:[{route, args}, options._id, callbackId]} as any; - //console.log(req) - if(method) req.args[0].method = method; - - let sub; - let ondata = (data:any)=>{ - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { - //(options.channels[firstChannel] as RTCDataChannel).removeEventListener('message',onmessage); - this.unsubscribe(options._id,sub); - res(data.args); //resolve the request with the corresponding message - } - } - } - - sub = this.subscribe(options._id,ondata); - - //(options.channels[firstChannel] as RTCDataChannel).addEventListener('message',onmessage) - this.transmit(req, options._id,options.channels[firstChannel] as RTCDataChannel); - }); - } - - let request = (message:ServiceMessage|any, method?:string):Promise => { - return new Promise ((res,rej) => { - let callbackId = Math.random(); - let req = {route:'runRequest', args:[message,options._id,callbackId]} as any; - //console.log(req) - if(method) req.method = method; - - let sub; - let ondata = (data:any)=>{ - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { - //(options.channels[firstChannel] as RTCDataChannel).removeEventListener('message',onmessage); - this.unsubscribe(options._id,sub); - res(data.args); //resolve the request with the corresponding message - } - } - } - - sub = this.subscribe(options._id,ondata); - this.transmit(req, options._id,options.channels[firstChannel] as RTCDataChannel); - }); - } - - let subscribe = (route:any, callback?:((res:any)=>void)|string, - args?:any[],key?:string, - subInput?:boolean, - channelId?:string - ) => { - return this.subscribeToRTC(route, options._id, channelId ? channelId : firstChannel, callback, args, key, subInput); - } - - let unsubscribe = (route:any, sub:number) => { - return run('unsubscribe',[route,sub]); - } - - let terminate = () => { - return this.terminate(options._id); - } - - this.rtc[options._id] = { - rtc, - _id:options._id, - request, - run, - post, - send, - subscribe, - unsubscribe, - terminate, - graph:this, - ...options - } - - const setMessageChannelHandle = (channel:RTCDataChannel) => { - if(!this.rtc[options._id].ondata) { - this.rtc[options._id].ondata = (mev) => { - //console.log('message on data channel', mev); - this.receive(mev.data, channel, this.rtc[options._id]); - this.setState({[options._id]:mev.data}); - } - channel.addEventListener('message', (mev) => { - //console.log('message on data channel', mev); - if(this.rtc[options._id].ondata) - this.rtc[options._id].ondata(mev, channel, this.rtc[options._id]); - }); - } - else { - channel.addEventListener('message', (mev) => { - if(this.rtc[options._id].ondata) - this.rtc[options._id].ondata(mev, channel, this.rtc[options._id]); - }); - } - } - - if(this.rtc[options._id].channels) { - for(const channel in this.rtc[options._id].channels) { - if(this.rtc[options._id].channels[channel] instanceof RTCDataChannel) { - //OK - } - else if( typeof this.rtc[options._id].channels[channel] === 'object') { - this.rtc[options._id].channels[channel] = this.addDataChannel(rtc,channel,(this.rtc[options._id].channels)[channel] as any); - } else { - this.rtc[options._id].channels[channel] = this.addDataChannel(rtc,channel); - } - - setMessageChannelHandle(this.rtc[options._id].channels[channel] as RTCDataChannel); - - } - } - - - rtc.ontrack = (ev) => { - if(!this.rtc[options._id].receivers) this.rtc[options._id].receivers = []; - this.rtc[options._id].receivers.push(ev.receiver); - - if(!this.rtc[options._id].streams) this.rtc[options._id].streams = []; - this.rtc[options._id].streams.push(...ev.streams); - - let rlength = this.rtc[options._id].receivers.length; - let slength = this.rtc[options._id].streams.length; - - ev.streams.forEach((s) => { - s.addEventListener('removetrack', (ev) => { - this.rtc[options._id].receivers[rlength] = undefined; - this.rtc[options._id].streams[slength] = undefined; - if(this.rtc[options._id].removetrack) this.rtc[options._id].removetrack(ev); - }) - }) - - if(this.rtc[options._id].ontrack) this.rtc[options._id].ontrack(ev); - }; - - rtc.ondatachannel = (ev) => { - this.rtc[options._id].channels[ev.channel.label] = ev.channel; - - setMessageChannelHandle(ev.channel); - - if(this.rtc[options._id].ondatachannel) - this.rtc[options._id].ondatachannel(ev); - }; - - rtc.onicecandidate = (ev) => { if(this.rtc[options._id].onicecandidate) this.rtc[options._id].onicecandidate(ev); }; - rtc.onicecandidateerror = (ev) => { if(this.rtc[options._id].onicecandidateerror) this.rtc[options._id].onicecandidateerror(ev); }; - - let initialOffer = this.rtc[options._id].description === undefined; - - rtc.onnegotiationneeded = async (ev) => { - if(!initialOffer) { - const offer = await rtc.createOffer(this.rtc[options._id].offer); - if (rtc.signalingState != "stable") return; - await rtc.setLocalDescription(offer); - - if(this.rtc[options._id].onnegotiationneeded) this.rtc[options._id].onnegotiationneeded(ev, rtc.localDescription); - } - }; - /* - rtc.onnegotiationneeded = async () => { //you need to implement this - const offer = await rtc.createOffer(); - if (rtc.signalingState != "stable") return; - await rtc.setLocalDescription(offer); - io.send({route:'negotiateCall', args: [options._id, rtc.localDescription]}); - } - */ - rtc.oniceconnectionstatechange = (ev) => { if(this.rtc[options._id].oniceconnectionstatechange) this.rtc[options._id].oniceconnectionstatechange(ev); }; - rtc.onconnectionstatechange = (ev) => { if(this.rtc[options._id].onconnectionstatechange) this.rtc[options._id].onconnectionstatechange(ev); }; - rtc.addEventListener('connectionstatechange', (ev) => { - if(rtc.connectionState === 'closed' || rtc.connectionState === 'failed') { - if(this.rtc[options._id].onclose) { - this.rtc[options._id].onclose(this.rtc[options._id]); - } - - delete this.rtc[options._id]; - } - }); - - - if(!this.rtc[options._id].onicecandidate) this.rtc[options._id].onicecandidate = (ev:RTCPeerConnectionIceEvent) => { - if(ev.candidate) { - let icecandidate = ev.candidate; - - if(!this.rtc[options._id].candidates) this.rtc[options._id].candidates = {}; - this.rtc[options._id].candidates[`candidate${Math.floor(Math.random()*1000000000000000)}`] = icecandidate; - - } - } - - if(!options.description) return await new Promise((res,rej) => { - this.rtc[options._id].rtc.createOffer(options.offer) - .then((offer) => this.rtc[options._id].rtc.setLocalDescription(offer)) - .then(()=>{ - initialOffer = false; - res(this.rtc[options._id]); //this is to be transmitted to the user - }); - }); - - } else { - Object.assign(this.rtc[options._id],options); - } - - - if(options.description) { - this.rtc[options._id].polite = true; - await this.negotiateCall(options._id, options.description, true); - } - - if(options.candidates) { - for(const prop in options.candidates) { - const candidate = new RTCIceCandidate(options.candidates[prop]) - this.rtc[options._id].rtc.addIceCandidate(candidate).catch(console.error); - } - } - - return this.rtc[options._id]; - - } - - open = this.openRTC; //for the router - - addIceCandidate = (rtc:RTCPeerConnection|string, candidate:RTCIceCandidate) => { - if(typeof rtc === 'string') rtc = this.rtc[rtc]?.rtc; - if(typeof candidate === 'string') candidate = JSON.parse(decodeURIComponent(candidate)); - if(rtc && rtc.remoteDescription) return rtc.addIceCandidate(candidate); - } - - //receive and compile unanswered/unadded call information (e.g. peer descriptions and ice candidates) - //https://hacks.mozilla.org/2013/07/webrtc-and-the-ocean-of-acronyms/ - receiveCallInformation = async ( options:WebRTCProps ) => { - if(!options._id) options._id = `rtc${Math.floor(Math.random()*1000000000000000)}`; - if (this.rtc[options._id]) { - if(options.candidates) { - for(const key in options.candidates) - this.addIceCandidate(this.rtc[options._id].rtc, options.candidates[key]); - delete options.candidates; - } - Object.assign(this.rtc[options._id],options); - } - else if(this.unanswered[options._id]) { - this.recursivelyAssign(this.unanswered[options._id], options); // - } else this.unanswered[options._id] = options; - - return options._id; - } - - answerCall = ( options:WebRTCProps|string ) => { - if(typeof options === 'string') options = this.unanswered[options]; - delete this.unanswered[options._id]; - return this.openRTC(options); - } - - rejectCall = ( options:WebRTCProps|string ) => { - if(typeof options === 'string') options = this.unanswered[options]; - delete this.unanswered[options._id]; - return true; - } - - negotiateCall = async ( rtc:RTCPeerConnection|string, description:string|RTCSessionDescription, polite?:boolean) => { - if(typeof rtc === 'string') { - if(polite === undefined) - polite = this.rtc[rtc].description !== undefined; //only the person called should have this defined - rtc = this.rtc[rtc].rtc; - } - if(typeof description === 'string') description = new RTCSessionDescription(JSON.parse(decodeURIComponent(description))); - if((description as RTCSessionDescription).type === 'offer' && rtc.signalingState !== 'stable') { - if(!polite) return; - await Promise.all([ - rtc.setLocalDescription({type:'rollback'}), - rtc.setRemoteDescription(description as RTCSessionDescription) - ]); - return encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); //we need to run negotiateCall on the other end now with this description to update the call information - } else { - await rtc.setRemoteDescription(description as RTCSessionDescription); - } if ((description as RTCSessionDescription).type == "offer") { - await rtc.setLocalDescription(await rtc.createAnswer()); - return encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); //we need to run negotiateCall on the other end now with this description to update the call information - } - } - - createOffer(rtc:RTCPeerConnection|string, options:WebRTCProps|string) { - if(typeof rtc === 'string') rtc = this.rtc[rtc].rtc; - if(typeof options === 'string') options = this.rtc[options]; - return new Promise((res,rej) => { - if(!rtc) rej(undefined); - (rtc as RTCPeerConnection).createOffer((options as WebRTCProps).offer) - .then((offer) => (rtc as RTCPeerConnection).setLocalDescription(offer)) - .then(()=>{ - let description = encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); - res(description); //this is to be transmitted to the user - }); - }) - } - - createAnswer(rtc:RTCPeerConnection|string, options:WebRTCProps|string) { - if(typeof rtc === 'string') rtc = this.rtc[rtc]?.rtc as RTCPeerConnection; - if(typeof options === 'string') options = this.rtc[options]; - - return new Promise((res,rej) => { - if(!rtc) rej(undefined); - (rtc as RTCPeerConnection).createAnswer((options as WebRTCProps).answer) - .then((answer)=> (rtc as RTCPeerConnection).setLocalDescription(answer)) - .then(()=>{ - let description = encodeURIComponent(JSON.stringify((rtc as RTCPeerConnection).localDescription)); - res(description); - }); - }); - } - - answerPeer = (rtc:RTCPeerConnection|string, options:WebRTCProps|string) => { - if(typeof rtc === 'string') { - let cpy = Object.assign(this.rtc[rtc],options); - delete cpy.description; - delete cpy.candidates; - Object.assign(this.rtc[rtc],cpy); - - rtc = this.rtc[rtc]?.rtc; - } - if(typeof options === 'string') options = this.rtc[options]; - return new Promise((res,rej) => { - if(typeof (options as WebRTCProps).description === 'string') { - (options as WebRTCProps).description = JSON.parse(decodeURIComponent((options as WebRTCProps).description as string)); - } - const description = new RTCSessionDescription((options as WebRTCProps).description as RTCSessionDescriptionInit); - - (rtc as RTCPeerConnection).setRemoteDescription(description).then(()=>{ - if((options as WebRTCProps).candidates) { - for(const prop in (options as WebRTCProps).candidates) { - const candidate = new RTCIceCandidate((options as WebRTCProps).candidates[prop]) - if(this.rtc[(options as WebRTCProps)._id]) this.rtc[(options as WebRTCProps)._id].candidates[prop] = (options as WebRTCProps).candidates[prop]; - (rtc as RTCPeerConnection).addIceCandidate(candidate).catch(console.error); - } - } - if(description.type === 'offer') { - this.rtc[(options as WebRTCProps)._id].rtc.createAnswer((options as WebRTCProps).answer).then((a) => { - this.rtc[(options as WebRTCProps)._id].rtc.setLocalDescription(a); - }); - } - res(this.rtc[(options as WebRTCProps)._id] ? this.rtc[(options as WebRTCProps)._id] : rtc); - }).catch(rej); //we can now receive data - }); - } - - createStream = ( //use navigator.mediaDevices.getUserMedia({audio:true,video:true}) for audio/video streams - options:{ - [key:string]:{ - track:MediaStreamTrack|MediaTrackConstraints, - onended:(ev)=>void, - onmute:(ev)=>void, - onunmute:(ev)=>void - } - } - ) => { - let stream = new MediaStream(); - for(const key in options) { - let track = options[key].track; - if(!(track instanceof MediaStreamTrack) && typeof track === 'object') { - track = new MediaStreamTrack(); - track.applyConstraints(options[key].track as MediaTrackConstraints) - stream.addTrack(track); - } - - if(track instanceof MediaStreamTrack) { - stream.addTrack(track as MediaStreamTrack); - track.onmute = options[key].onmute; - track.onunmute = options[key].onunmute; - track.onended = options[key].onended; - - } - } - return stream; - } - - addUserMedia = ( - rtc:RTCPeerConnection, - options:MediaStreamConstraints={ - audio:true, - video:{ - optional:[ - {minWidth: 320 }, - {minWidth: 640 }, - {minWidth: 1024 }, - {minWidth: 1280 }, - {minWidth: 1920 }, - {minWidth: 2560 }, - ] - } as MediaTrackConstraints - }, - info?:WebRTCInfo - ) => { - - return new Promise(async (res,rej) => { - - let RTCRtpSenders:any[] = []; - - let stream = await navigator.mediaDevices.getUserMedia(options) - - if(stream) { - let tracks = stream.getTracks() - tracks.forEach((track) => { - let sender = rtc.addTrack(track,stream); - if(track.kind === 'video' && info) {info.videoSender = sender; info.videoStream = stream; } - if(track.kind === 'audio' && info) {info.audioSender = sender; info.audioStream = stream; } - RTCRtpSenders.push(sender); - }); - let str = stream; - - if(info) info.senders = - info.senders ? - [...info.senders, ...RTCRtpSenders] : - RTCRtpSenders; - - res(str); - } - }); - } - - //add media streams to the dat channel - addTrack = (rtc:RTCPeerConnection, track:MediaStreamTrack, stream:MediaStream) => { - return rtc.addTrack(track,stream); - } - - removeTrack = (rtc:RTCPeerConnection,sender:RTCRtpSender) => { - rtc.removeTrack(sender); //e.g. remove the senders removed by addUserMedia - return true; - } - - addDataChannel = ( //send arbitrary strings - rtc:RTCPeerConnection, - name:string, - options?:RTCDataChannelInit//{ negotiated: false } - ) => { - return rtc.createDataChannel(name,options); - } - - enableAudio = async (call:WebRTCInfo, audioOptions:boolean|(MediaTrackConstraints & {deviceId?:string})=true) => { - if(call.audioStream) this.disableAudio(call); - let stream = await this.addUserMedia( - call.rtc, - { - audio:audioOptions, - video:false - }, - call - ); - - if((audioOptions as any)?.deviceId) (call.audioSender as any).deviceId = (audioOptions as any).deviceId; - - return stream; - } - - enableVideo = async ( - call:WebRTCInfo, - videoOptions:(MediaTrackConstraints & {deviceId?:string, optional?:{minWidth: number}[] }) = { - //deviceId: 'abc' //or below default setting: - optional:[ - {minWidth: 320}, - {minWidth: 640}, - {minWidth: 1024}, - {minWidth: 1280}, - {minWidth: 1920}, - {minWidth: 2560}, - {minWidth: 3840}, - ] - } as MediaTrackConstraints & { deviceId?:string, optional?:{minWidth: number}[] }, - includeAudio:boolean|(MediaTrackConstraints & {deviceId?:string}) = false - ) => { //the maximum available resolution will be selected if not specified - - if(call.videoStream) this.disableVideo(call); - - let stream = await this.addUserMedia( - call.rtc, - { - audio:includeAudio, - video:videoOptions ? videoOptions : { - optional: [ - {minWidth: 320}, - {minWidth: 640}, - {minWidth: 1024}, - {minWidth: 1280}, - {minWidth: 1920}, - {minWidth: 2560}, - {minWidth: 3840}, - ] - } as MediaTrackConstraints - }, - call - ); - - if(videoOptions?.deviceId) (call.videoSender as any).deviceId = videoOptions.deviceId; - if(includeAudio) { - if((includeAudio as any)?.deviceId) - (call.audioSender as any).deviceId = (includeAudio as any).deviceId; - else if(videoOptions?.deviceId) (call.audioSender as any).deviceId = (videoOptions as any).deviceId; - } - - return stream; - } - - disableAudio(call:WebRTCInfo) { - if(call.audioSender) { - call.senders?.find((s,i) => { - if(call.audioStream?.getAudioTracks()[0].id === s.track.id) { - call.senders.splice(i,1); - return true; - } - }); - call.rtc.removeTrack(call.audioSender); - call.audioSender = undefined; - } - call.audioStream?.getTracks().forEach((track) => { - if(track.kind === 'audio') track.stop(); - }); - call.audioStream = undefined; - } - - disableVideo(call:WebRTCInfo) { - if(call.videoSender) { - call.senders?.find((s,i) => { - if(call.videoStream?.getVideoTracks()[0].id === s.track.id) { - call.senders.splice(i,1); - return true; - } - }); - call.rtc.removeTrack(call.videoSender); - call.videoSender = undefined; - } - call.videoStream?.getTracks().forEach((track) => { - if(track.kind === 'video') track.stop(); - }); - call.videoStream = undefined; - } - - //send data on a data channel - transmit = (data:ServiceMessage|any, id?:string, channel?:string|RTCDataChannel ) => { - if((typeof data === 'object' && ((data.route || data.node) || !(data as ArrayBufferLike).byteLength && typeof (data as Blob).arrayBuffer !== 'function') || typeof data === 'number')) - data = JSON.stringify(data); //we need strings - - if(!channel && id) { //select first channel - let keys = Object.keys(this.rtc[id].channels); - if(keys[0]) - channel = this.rtc[id].channels[keys[0]] as RTCDataChannel; - } - - if(typeof channel === 'string') { - if(id) { - channel = this.rtc[id].channels[channel] as RTCDataChannel; - } else { //send on all channels on all rooms - for(const id in this.rtc) { - if(this.rtc[id].channels[channel] instanceof RTCDataChannel) - (this.rtc[id].channels[channel] as RTCDataChannel).send(data); // This may be a string, a Blob, an ArrayBuffer, a TypedArray or a DataView object. - } - } - } - - if(channel instanceof RTCDataChannel) - channel.send(data); // This may be a string, a Blob, an ArrayBuffer, a TypedArray or a DataView object. - - //console.log('sending',channel,data) - - return true; - } - - //close a channel - terminate = (rtc:RTCPeerConnection|WebRTCInfo|string) => { - let tx; - if(typeof rtc === 'string') { - let room = this.rtc[rtc]; - delete this.rtc[rtc]; - if(room) { - tx = room.rtc; - } - } - else if (typeof rtc === 'object') { - tx = (rtc as WebRTCInfo).rtc; - } - - if(rtc instanceof RTCPeerConnection && rtc.signalingState !== 'closed') { - rtc.close(); - } else if(tx && tx.signalingState !== 'closed') { - if(tx) tx.close(); - } - - return true; - } - - request = (message:ServiceMessage|any, channel:RTCDataChannel, _id:string, method?:string) => { //return a promise which can resolve with a server route result through the socket - let callbackId = `${Math.random()}`; - let req:any = {route:'runRequest', args:[message,_id,callbackId]}; - if(method) req.method = method; - return new Promise((res,rej) => { - let onmessage = (ev:any) => { - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(ev.data); - if(typeof data === 'object') if(data.callbackId === callbackId) { - channel.removeEventListener('message',onmessage); - res(data.args); - } - } - - channel.addEventListener('message',onmessage); - channel.send(JSON.stringify(req)); - }); - } - - runRequest = ( - message:any, - channelOrRtcId:RTCDataChannel|string, //data channel or rtc id (which grabs the first channel) - callbackId:string|number - ) => { //send result back - let res = this.receive(message); - if(channelOrRtcId) { - if(typeof channelOrRtcId === 'string') { - for(const key in this.rtc) { - if(key === channelOrRtcId) {channelOrRtcId = this.rtc[key].channels.data ? this.rtc[key].channels.data as RTCDataChannel : this.rtc[key].channels[Object.keys(this.rtc[key].channels)[0]] as RTCDataChannel; break;} - } - } - if(res instanceof Promise) - res.then((v) => { - res = {args:v, callbackId}; - if(channelOrRtcId instanceof RTCDataChannel) channelOrRtcId.send(JSON.stringify(res)); - - return res; - }) - else { - res = {args:res, callbackId}; - if(channelOrRtcId instanceof RTCDataChannel) channelOrRtcId.send(JSON.stringify(res)); - } - } - return res; - } - - subscribeRTC = ( - route:string, - rtcId:string, - args?:any[], - key?:string, - subInput?:boolean, - channel?:string|RTCDataChannel - ) => { - if(this.restrict?.[route]) return undefined; - if(typeof channel === 'string' && this.rtc[rtcId]) { - channel = this.rtc[rtcId].channels[channel] as RTCDataChannel; - } else if (!channel) { channel = this.rtc[rtcId].channels[Object.keys(this.rtc[rtcId].channels)[0]] as RTCDataChannel } - return this.subscribe(route, (res:any) => { - //console.log('running request', message, 'for worker', worker, 'callback', callbackId) - if(res instanceof Promise) { - res.then((r) => { - (channel as RTCDataChannel).send(JSON.stringify({args:r, callbackId:route})); - }); - } else { - (channel as RTCDataChannel).send(JSON.stringify({args:res, callbackId:route})); - } - },args,key,subInput); - } - - subscribeToRTC = ( - route:string, rtcId:string, channelId:string, callback?:string|((res:any)=>void), - args?:any[], - key?:string, - subInput?:boolean - ) => { - if(typeof channelId === 'string' && this.rtc[rtcId]) { - let c = this.rtc[rtcId]; - let channel = c.channels[channelId]; - - if(channel) { - this.__node.state.subscribeEvent(rtcId, (res) => { - if(res?.callbackId === route) { - if(!callback) this.setState({[rtcId]:res.args}); //just set state - else if(typeof callback === 'string') { //run a local node - this.run(callback,res.args); - } - else callback(res.args); - } - }); - return c.request({route:'subscribeRTC', args:[route,rtcId,args,key,subInput,channelId]}); - } - } - } - -} \ No newline at end of file diff --git a/src/services/worker/canvas.worker.ts b/src/services/worker/canvas.worker.ts deleted file mode 100644 index 8078f85a..00000000 --- a/src/services/worker/canvas.worker.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { workerCanvasRoutes } from './WorkerCanvas'; -//minimal web worker for running offscreen canvases, -//no graphscript required - -declare var WorkerGlobalScope; - -if(typeof WorkerGlobalScope !== 'undefined') { - - const routes = { - ...workerCanvasRoutes - //add more compatible routes that don't require graphscript - }; - - self.onmessage = (ev) => { - if(ev.data.route) { - if(Array.isArray(ev.data.args)) { - routes[ev.data.route](...ev.data.args); - } else routes[ev.data.route](ev.data.args); - } //that's it! The functions handle worker communication internally - - } - -} - -export default self as any; \ No newline at end of file diff --git a/src/services/wss/WSS.browser.ts b/src/services/wss/WSS.browser.ts deleted file mode 100644 index 6bed648f..00000000 --- a/src/services/wss/WSS.browser.ts +++ /dev/null @@ -1,452 +0,0 @@ - -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -import { Service, ServiceMessage, ServiceOptions } from "../Service"; - -export type WSSRoute = { - socket?:WebSocketInfo - transferFunctions?:{[key:string]:Function}, - transferClasses?:{[key:string]:Function}, - parentRoute?:string, //if a child of a socket node, subscribe to a route on a parent worker? - callback?:string, //Run this route on the socket when the operator is called. If this route is a child of another node, run this node on the child worker when it receives a message. - stopped?:boolean, // Don't run the callback until we call the thread to start? E.g. for recording data periodically. - blocking?:boolean, //should the subscribed socket wait for the subscriber to resolve before sending a new result? Prevents backup and makes async processing easier - init?:string, //run a callback on the socket on socket init? - initArgs?:any[] //arguments to go with the socket init? -} & GraphNodeProperties & WebSocketProps - -export type WebSocketProps = { - host:string, - port:number, - path?:string, - debug?:boolean, - onmessage?:(data:string | ArrayBufferLike | Blob | ArrayBufferView, ws:WebSocket, wsinfo:WebSocketInfo)=>void, //will use this.receive as default - onopen?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, - onclose?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, - onerror?:(ev:any, ws:WebSocket, wsinfo:WebSocketInfo)=>void, - protocol?:'ws'|'wss', - keepState?:boolean, - type?:'socket', - _id?:string, - [key:string]:any -} & GraphNodeProperties - -export type WebSocketInfo = { - socket:WebSocket, - address:string, - send:(message:any)=>void, - request:(message:any, method?:string)=>Promise, - post:(route:any, args?:any)=>void, - run:(route:any, args?:any, method?:string)=>Promise, - subscribe:(route:any, callback?:((res:any)=>void)|string, args?: any[], key?: string, subInput?: boolean)=>any, - unsubscribe:(route:any, sub:number)=>Promise, - terminate:()=>boolean, - _id?:string, - graph:WSSfrontend -} & WebSocketProps & GraphNode - -//browser side websockets -export class WSSfrontend extends Service { - - name='wss' - - sockets:{ - [key:string]:WebSocketInfo & GraphNode - } = { } - - connections = { //higher level reference for Router - sockets:this.sockets - } - - - constructor(options?:ServiceOptions) { - super(options) - this.load(this); - } - - loadWebSocketRoute = (node: WebSocketProps & GraphNode) => { - let wsInfo = this.openWS(node); - - if (!wsInfo.__ondisconnected) { - wsInfo.__addOndisconnected(() => { - wsInfo.terminate(); - }); - } - - if (!node.__operator) { - node.__operator = (...args) => { - //console.log('operator', args) - if(node.callback) { - if(!this.__node.nodes.get(node.__node.tag)?.__children) wsInfo.post(node.callback,args); - else return wsInfo.run(node.callback,args); - } else { - if(!this.__node.nodes.get(node.__node.tag)?.__children) wsInfo.send(args); - else return wsInfo.request(args); - } - } - } - - if(!node.__ondisconnected) { - let ondelete = (rt) => { //removing the original route will trigger ondelete - rt?.terminate(); - } - node.__addOndisconnected(ondelete); - } - - // Additional setup or event handlers can be added here - // ... - - return wsInfo; - }; - - socketloader = { - 'websockets': (node: WebSocketProps & GraphNode, parent: WebSocketProps & GraphNode, graph: WSSfrontend, roots: any) => { - node._id = node.__node.tag; - let ws = this.loadWebSocketRoute(node); - Object.assign(node,ws); - if (parent && parent.type === 'socket') { - let parentWs = this.sockets[parent._id]; - - // Logic to subscribe child node to parent WebSocket - if (node.parentRoute) { - parentWs.subscribe(node.parentRoute, node.__operator); - } - } - } - } - - openWS = ( - options:WebSocketProps = { - host:'localhost', - port:7000, - path:undefined, - protocol:'ws' - } - ) => { - - let protocol = options.protocol; - if(!protocol) protocol = 'ws'; - let address = `${protocol}://${options.host}`; - - if(!('keepState' in options)) options.keepState = true; - if(options.port) address+= ':'+options.port; - if(options.path && !options.path?.startsWith('/')) address += '/'; - if(options.path) address += options.path; - - if(this.sockets[address]?.socket) - if(this.sockets[address].socket.readyState === this.sockets[address].socket.OPEN) - this.sockets[address].socket.close(); //we'll try refresh the socket - - const socket = new WebSocket(address); - - if(!options.onmessage) { - if(!options._id) { - options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { - if(data) if(typeof data === 'string') { - if(options.debug) { - console.log("Message from ",address, ": ", data); - } - let substr = data.substring(0,8); - if(substr.includes('{') || substr.includes('[')) { - if(substr.includes('\\')) data = data.replace(/\\/g,""); - if(data[0] === '"') { data = data.substring(1,data.length-1)}; - //console.log(message) - data = JSON.parse(data); //parse stringified objects - - if(data.route === 'setId') { - this.sockets[address]._id = data.args; - - options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo) => { //clear extra logic after id is set - if(options.debug) { - console.log("Message from ",address, ": ", data); - } - this.receive(data); - if(options.keepState) { - this.setState({[address as string]:data}); - } - } - } - } - } - - let res = this.receive(data); - if(options.keepState) this.setState({[address]:data}); - } //default onmessage - } - else { - options.onmessage = (data:any, ws:WebSocket, wsinfo:WebSocketInfo)=> { - if(options.debug) { - console.log("Message from ",(socket as WebSocket).url, ": ", data); - } - this.receive(data,socket,this.sockets[address]); - if(options.keepState) { - this.setState({[address]:data}); - } - }; - } - } - - if((options as any).onmessage) { - socket.addEventListener('message',(ev)=>{ - (this.sockets[address] as any).onmessage(ev.data, socket, this.sockets[address]); - }); - } - - socket.addEventListener('open',(ev)=>{ - if(this.sockets[address].onopen) (this.sockets[address] as any).onopen(ev, socket, this.sockets[address]); - }); - - socket.addEventListener('close',(ev)=>{ - let obj = this.sockets[address]; - let onclose = obj.onclose; - - delete this.sockets[address]; //delete by default onclose (memory saving) - this.remove(address); - - if(onclose) onclose(ev,socket, obj); - - }); - - socket.addEventListener('error',(ev)=>{ - if(this.sockets[address].onerror) (this.sockets[address] as any).onerror(ev,socket, this.sockets[address]); - }); - - - let send = (message:ServiceMessage|any) => { - //console.log('sent', message) - return this.transmit(message,socket); - } - - let post = (route:any,args?:any, method?:string) => { - //console.log('sent', message) - let message:any = { - route, - args - }; - if(method) message.method = method; - - return this.transmit(message,socket); - } - - let run = (route:any,args?:any,method?:string) => { - return new Promise ((res,rej) => { - let callbackId = Math.random(); - let req = { - route:'runRequest', - args:[{route, args}, this.sockets[address]._id, callbackId] - } as any; - if(method) req.args[0].method = method; - let onmessage = (ev)=>{ - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(ev.data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { - socket.removeEventListener('message',onmessage); - res(data.args); //resolve the request with the corresponding message - } - } - } - socket.addEventListener('message',onmessage) - this.transmit(req, socket); - }); - } - - let request = (message:ServiceMessage|any, method?:string) => { - return new Promise ((res,rej) => { - let callbackId = Math.random(); - let req = {route:'runRequest', args:[message, this.sockets[address]._id, callbackId]} as any; - //console.log(req) - if(method) req.method = method; - let onmessage = (ev)=>{ - let data = ev.data; - if(typeof data === 'string' && data.indexOf('{') > -1) data = JSON.parse(ev.data); - if(typeof data === 'object') { - if(data.callbackId === callbackId) { - socket.removeEventListener('message',onmessage); - res(data.args); //resolve the request with the corresponding message - } - } - } - socket.addEventListener('message',onmessage) - this.transmit(req, socket); - }); - } - - let subscribe = (route:any, callback?:((res:any)=>void)|string, args?: any[], key?: string, subInput?: boolean):Promise => { - return this.subscribeToSocket(route, this.sockets[address]._id, callback, args, key, subInput); - } - - let unsubscribe = (route:any, sub:number):Promise => { - return run('unsubscribe',[route,sub]); - } - - let terminate = () => { - return this.terminate(address); - } - - Object.assign(options, { - type:'socket', - socket, - address, - send, - post, - run, - request, - subscribe, - unsubscribe, - terminate - }); - - if(!(options instanceof GraphNode)) { - let node = this.add(options); - node.__addOndisconnected(function() { terminate(); }); - options = node as any; - } - this.sockets[address] = options as GraphNode & WebSocketInfo; - //console.log(node,this.get(address),this.sockets[address]); - - return options as WebSocketInfo; - } - - open = this.openWS; - - transmit = ( - data:string | ArrayBufferLike | Blob | ArrayBufferView | ServiceMessage, - ws:WebSocket - ) => { - if( - (typeof data === 'object' && - (((data as ServiceMessage)?.route || ((data as ServiceMessage)?.node)) || ( - typeof (data as Blob).arrayBuffer !== 'function' && - typeof (data as ArrayBufferLike).byteLength !== 'number' - ))) || typeof data === 'number' - ) data = JSON.stringify(data); - if(!ws) { - let s = this.sockets[Object.keys(this.sockets)[0]]; - if(s) ws = s.socket; - } - if(ws instanceof WebSocket && ws?.readyState === 1) ws.send(data as any); - - return true; - } - - terminate = (ws:WebSocket|string) => { - - let str; - if(!ws) { - //terminate all - let keys = Object.keys(this.sockets) - for(const key in keys) { - this.terminate(key); - } - } - else if(typeof ws === 'string') { - str = ws; - for(const k in this.sockets) { - if(k.includes(ws) || this.sockets[k]._id === k) { - ws = this.sockets[k].socket; - break; - } - } - } - - if(ws instanceof WebSocket) { - if(ws.readyState === ws.OPEN) - ws.close(); - - if(this.get(str ? str : ws.url)) this.remove(str ? str : ws.url); - } - - return true; - } - - request = ( - message:ServiceMessage|any, - ws:WebSocket, - _id:string, - method?:string - ) => { //return a promise which can resolve with a server route result through the socket - let callbackId = `${Math.random()}`; - let req:any = {route:'runRequest', args:[message,_id,callbackId]}; - if(method) req.method = method; - return new Promise((res,rej) => { - let onmessage = (ev:any) => { - let data = ev.data; - if(typeof data === 'string') if(data.includes('callbackId')) data = JSON.parse(data); - if(typeof data === 'object') if(data.callbackId === callbackId) { - ws.removeEventListener('message',onmessage); - res(data.args); - } - } - - ws.addEventListener('message',onmessage); - ws.send(JSON.stringify(req)); - }) - } - - runRequest = ( - message:any, - ws:WebSocket|string, - callbackId:string|number - ) => { //send result back - //console.log('running request', message, this.__node.nodes); - let res = this.receive(message); - if(typeof ws === 'string') { - for(const s in this.sockets) { - if(s === ws || this.sockets[s]._id === ws) {ws = this.sockets[s].socket; break;} - } - } - if(ws) { - if(res instanceof Promise) { - res.then((v) => { - res = {args:v, callbackId}; - if(ws instanceof WebSocket) ws.send(JSON.stringify(res)); - }) - } - else { - res = {args:res, callbackId}; - if(ws instanceof WebSocket) ws.send(JSON.stringify(res)); - } - } - - return res; - } - - subscribeSocket = (route:string, socket:WebSocket|string, args?:any[], key?:string, subInput?:boolean) => { - if(this.restrict?.[route]) return undefined; - if(typeof socket === 'string' && this.sockets[socket]) { - socket = this.sockets[socket].socket; - } - - if(typeof socket === 'object') { - return this.subscribe(route, (res:any) => { - //console.log('running request', message, 'for worker', worker, 'callback', callbackId) - if((socket as WebSocket).readyState === (socket as WebSocket).OPEN) { - if(res instanceof Promise) { - res.then((r) => { - (socket as WebSocket).send(JSON.stringify({args:r, callbackId:route})); - }); - } else { - (socket as WebSocket).send(JSON.stringify({args:res, callbackId:route})); - } - } - },args,key,subInput); - } - } - - subscribeToSocket = (route:string, socketId:string, callback?:((res:any)=>void)|string, args?:any[], key?:string,subInput?:boolean) => { - if(typeof socketId === 'string' && this.sockets[socketId]) { - this.__node.state.subscribeEvent(socketId, (res) => { - let msg = JSON.parse(res); - if(msg?.callbackId === route) { - if(!callback) this.setState({[socketId]:msg.args}); //just set state - else if(typeof callback === 'string') { //run a local node - this.run(callback,msg.args); - } - else callback(msg.args); - } - }); - return this.sockets[socketId].request({route:'subscribeSocket', args:[route,socketId, args, key,subInput]}); - } - } - -} diff --git a/tinybuild.node.config.js b/tinybuild.node.config.js index 8268b979..8e468636 100644 --- a/tinybuild.node.config.js +++ b/tinybuild.node.config.js @@ -4,7 +4,7 @@ const config = { entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types "index.node.ts" ], - outfile: "dist/index.node", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags + outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags //outdir:[] //exit point files, define for multiple bundle files bundleBrowser: false, //create plain js build? Can include globals and init scripts bundleESM: false, //create esm module js files diff --git a/todo.md b/todo.md deleted file mode 100644 index 7363da63..00000000 --- a/todo.md +++ /dev/null @@ -1,19 +0,0 @@ -## TODO - -- Make proper loaders for all of our services so they can be declared and used in the tree definitions - -- Optimize some of the remote callback system, use a single callback and just check a list of callbackIds instead of a new messageevent for every request as it will parse JSON for each callback (much more inefficient). This is only for going pedal-to-the-metal with sockets etc but why shouldn't we. - -- Make definitive benchmarks - -- Document the router etc in great detail, need to streamline it a bit more as it introduces a lot of weird options structures that are a bit convoluted. - -- fix the local struct backend, it just seems to be stringifying for some reason. - -- Forever bug testing and trying to raise things to "industry standard" without making it artificially difficult to use the whole system. We want this to be baby's first super API - -## Demos todo - -- Editor: demonstrate live editing on a multithreaded + server application - -- bring other examples more up to date, try to get closer to more typical game logic standards our examples are all made by flying by the seat of our pants and not trying to seriously model standard engine code. That's part of the point though so there's a balance to strike between creative code and familiarity. Priority 1 is readability of the logic however, as it makes complex systems that much easier to build. \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index baefe6fe..cf913bf7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,10 +4,10 @@ /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ - "target": "ESNext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, - "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "target": "es2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "es2020" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, "declaration": true, /* Generates corresponding '.d.ts' file. */ - "allowJs": true, /* Allow javascript files to be compiled. */ + "allowJs": false, /* Allow javascript files to be compiled. */ "skipLibCheck": true /* Skip type checking of declaration files. */, "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, "outDir": "./dist" /* Redirect output structure to the directory. */, diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 00000000..3e106970 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,45 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@types/node@*": + version "18.11.17" + resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.17.tgz#5c009e1d9c38f4a2a9d45c0b0c493fe6cdb4bcb5" + integrity sha512-HJSUJmni4BeDHhfzn6nF0sVmd1SMezP7/4F0Lq+aXzmp2xm9O7WXrUtHW/CHlYVtZUbByEvWidHqRtcJXGF2Ng== + +"@types/node@~18.7.15": + version "18.7.19" + resolved "https://registry.npmjs.org/@types/node/-/node-18.7.19.tgz" + integrity sha512-Sq1itGUKUX1ap7GgZlrzdBydjbsJL/NSQt/4wkAxUJ7/OS5c2WkoN6WSpWc2Yc5wtKMZOUA0VCs/j2XJadN3HA== + +"@types/ws@~8.5.3": + version "8.5.3" + resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.3.tgz#7d25a1ffbecd3c4f2d35068d0b283c037003274d" + integrity sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w== + dependencies: + "@types/node" "*" + +better-sse@~0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/better-sse/-/better-sse-0.8.0.tgz#2939fae49209f3e00d16da3edfe039a09a941177" + integrity sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA== + +brainsatplay-math@~0.0.25: + version "0.0.25" + resolved "https://registry.yarnpkg.com/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz#190d54fffed8270c9482273313f8f09420f63137" + integrity sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ== + +bson-objectid@~2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/bson-objectid/-/bson-objectid-2.0.4.tgz#339211572ef97dc98f2d68eaee7b99b7be59a089" + integrity sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ== + +web-worker@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/web-worker/-/web-worker-1.2.0.tgz#5d85a04a7fbc1e7db58f66595d7a3ac7c9c180da" + integrity sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA== + +ws@~8.11.0: + version "8.11.0" + resolved "https://registry.yarnpkg.com/ws/-/ws-8.11.0.tgz#6a0d36b8edfd9f96d8b25683db2f8d7de6e8e143" + integrity sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==
- - -
-
- - -
-
- "; - else - dialog.innerHTML = " "; - dialog.close = function() { - that.prompt_box = null; - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - canvas.parentNode.appendChild(dialog); - - if (this.ds.scale > 1) { - dialog.style.transform = "scale(" + this.ds.scale + ")"; - } - - var dialogCloseTimer = null; - var prevent_timeout = false; - LiteGraph.pointerListenerAdd(dialog,"leave", function(e) { - if (prevent_timeout) - return; - if(LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - LiteGraph.pointerListenerAdd(dialog,"enter", function(e) { - if(LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - var selInDia = dialog.querySelectorAll("select"); - if (selInDia){ - // if filtering, check focus changed to comboboxes and prevent closing - selInDia.forEach(function(selIn) { - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - }); - } - - if (that.prompt_box) { - that.prompt_box.close(); - } - that.prompt_box = dialog; - - var first = null; - var timeout = null; - var selected = null; - - var name_element = dialog.querySelector(".name"); - name_element.innerText = title; - var value_element = dialog.querySelector(".value"); - value_element.value = value; - - var input = value_element; - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13 && e.target.localName != "textarea") { - if (callback) { - callback(this.value); - } - dialog.close(); - } else { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - - var button = dialog.querySelector("button"); - button.addEventListener("click", function(e) { - if (callback) { - callback(input.value); - } - that.setDirty(true); - dialog.close(); - }); - - var rect = canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - - setTimeout(function() { - input.focus(); - }, 10); - - return dialog; - }; - - LGraphCanvas.search_limit = -1; - LGraphCanvas.prototype.showSearchBox = function(event, options) { - // proposed defaults - var def_options = { slot_from: null - ,node_from: null - ,node_to: null - ,do_type_filter: LiteGraph.search_filter_enabled // TODO check for registered_slot_[in/out]_types not empty // this will be checked for functionality enabled : filter on slot type, in and out - ,type_filter_in: false // these are default: pass to set initially set values - ,type_filter_out: false - ,show_general_if_none_on_typefilter: true - ,show_general_after_typefiltered: true - ,hide_on_mouse_leave: LiteGraph.search_hide_on_mouse_leave - ,show_all_if_empty: true - ,show_all_on_open: LiteGraph.search_show_all_on_open - }; - options = Object.assign(def_options, options || {}); - - //console.log(options); - - var that = this; - var input_html = ""; - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - var root_document = canvas.ownerDocument || document; - - var dialog = document.createElement("div"); - dialog.className = "litegraph litesearchbox graphdialog rounded"; - dialog.innerHTML = "Search "; - if (options.do_type_filter){ - dialog.innerHTML += ""; - dialog.innerHTML += ""; - } - dialog.innerHTML += "
"; - - if( root_document.fullscreenElement ) - root_document.fullscreenElement.appendChild(dialog); - else - { - root_document.body.appendChild(dialog); - root_document.body.style.overflow = "hidden"; - } - // dialog element has been appended - - if (options.do_type_filter){ - var selIn = dialog.querySelector(".slot_in_type_filter"); - var selOut = dialog.querySelector(".slot_out_type_filter"); - } - - dialog.close = function() { - that.search_box = null; - this.blur(); - canvas.focus(); - root_document.body.style.overflow = ""; - - setTimeout(function() { - that.canvas.focus(); - }, 20); //important, if canvas loses focus keys wont be captured - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - if (this.ds.scale > 1) { - dialog.style.transform = "scale(" + this.ds.scale + ")"; - } - - // hide on mouse leave - if(options.hide_on_mouse_leave){ - var prevent_timeout = false; - var timeout_close = null; - LiteGraph.pointerListenerAdd(dialog,"enter", function(e) { - if (timeout_close) { - clearTimeout(timeout_close); - timeout_close = null; - } - }); - LiteGraph.pointerListenerAdd(dialog,"leave", function(e) { - if (prevent_timeout){ - return; - } - timeout_close = setTimeout(function() { - dialog.close(); - }, 500); - }); - // if filtering, check focus changed to comboboxes and prevent closing - if (options.do_type_filter){ - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - selOut.addEventListener("click", function(e) { - prevent_timeout++; - }); - selOut.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selOut.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - } - } - - if (that.search_box) { - that.search_box.close(); - } - that.search_box = dialog; - - var helper = dialog.querySelector(".helper"); - - var first = null; - var timeout = null; - var selected = null; - - var input = dialog.querySelector("input"); - if (input) { - input.addEventListener("blur", function(e) { - this.focus(); - }); - input.addEventListener("keydown", function(e) { - if (e.keyCode == 38) { - //UP - changeSelection(false); - } else if (e.keyCode == 40) { - //DOWN - changeSelection(true); - } else if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - if (selected) { - select(selected.innerHTML); - } else if (first) { - select(first); - } else { - dialog.close(); - } - } else { - if (timeout) { - clearInterval(timeout); - } - timeout = setTimeout(refreshHelper, 250); - return; - } - e.preventDefault(); - e.stopPropagation(); - e.stopImmediatePropagation(); - return true; - }); - } - - // if should filter on type, load and fill selected and choose elements if passed - if (options.do_type_filter){ - if (selIn){ - var aSlots = LiteGraph.slot_types_in; - var nSlots = aSlots.length; // this for object :: Object.keys(aSlots).length; - - if (options.type_filter_in == LiteGraph.EVENT || options.type_filter_in == LiteGraph.ACTION) - options.type_filter_in = "_event_"; - /* this will filter on * .. but better do it manually in case - else if(options.type_filter_in === "" || options.type_filter_in === 0) - options.type_filter_in = "*";*/ - - for (var iK=0; iK (rect.height - 200)) - helper.style.maxHeight = (rect.height - event.layerY - 20) + "px"; - - /* - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - canvas.parentNode.appendChild(dialog); - */ - - input.focus(); - if (options.show_all_on_open) refreshHelper(); - - function select(name) { - if (name) { - if (that.onSearchBoxSelection) { - that.onSearchBoxSelection(name, event, graphcanvas); - } else { - var extra = LiteGraph.searchbox_extras[name.toLowerCase()]; - if (extra) { - name = extra.type; - } - - graphcanvas.graph.beforeChange(); - var node = LiteGraph.createNode(name); - if (node) { - node.pos = graphcanvas.convertEventToCanvasOffset( - event - ); - graphcanvas.graph.add(node, false); - } - - if (extra && extra.data) { - if (extra.data.properties) { - for (var i in extra.data.properties) { - node.addProperty( i, extra.data.properties[i] ); - } - } - if (extra.data.inputs) { - node.inputs = []; - for (var i in extra.data.inputs) { - node.addOutput( - extra.data.inputs[i][0], - extra.data.inputs[i][1] - ); - } - } - if (extra.data.outputs) { - node.outputs = []; - for (var i in extra.data.outputs) { - node.addOutput( - extra.data.outputs[i][0], - extra.data.outputs[i][1] - ); - } - } - if (extra.data.title) { - node.title = extra.data.title; - } - if (extra.data.json) { - node.configure(extra.data.json); - } - - } - - // join node after inserting - if (options.node_from){ - var iS = false; - switch (typeof options.slot_from){ - case "string": - iS = options.node_from.findOutputSlot(options.slot_from); - break; - case "object": - if (options.slot_from.name){ - iS = options.node_from.findOutputSlot(options.slot_from.name); - }else{ - iS = -1; - } - if (iS==-1 && typeof options.slot_from.slot_index !== "undefined") iS = options.slot_from.slot_index; - break; - case "number": - iS = options.slot_from; - break; - default: - iS = 0; // try with first if no name set - } - if (typeof options.node_from.outputs[iS] !== undefined){ - if (iS!==false && iS>-1){ - options.node_from.connectByType( iS, node, options.node_from.outputs[iS].type ); - } - }else{ - // console.warn("cant find slot " + options.slot_from); - } - } - if (options.node_to){ - var iS = false; - switch (typeof options.slot_from){ - case "string": - iS = options.node_to.findInputSlot(options.slot_from); - break; - case "object": - if (options.slot_from.name){ - iS = options.node_to.findInputSlot(options.slot_from.name); - }else{ - iS = -1; - } - if (iS==-1 && typeof options.slot_from.slot_index !== "undefined") iS = options.slot_from.slot_index; - break; - case "number": - iS = options.slot_from; - break; - default: - iS = 0; // try with first if no name set - } - if (typeof options.node_to.inputs[iS] !== undefined){ - if (iS!==false && iS>-1){ - // try connection - options.node_to.connectByTypeOutput(iS,node,options.node_to.inputs[iS].type); - } - }else{ - // console.warn("cant find slot_nodeTO " + options.slot_from); - } - } - - graphcanvas.graph.afterChange(); - } - } - - dialog.close(); - } - - function changeSelection(forward) { - var prev = selected; - if (selected) { - selected.classList.remove("selected"); - } - if (!selected) { - selected = forward - ? helper.childNodes[0] - : helper.childNodes[helper.childNodes.length]; - } else { - selected = forward - ? selected.nextSibling - : selected.previousSibling; - if (!selected) { - selected = prev; - } - } - if (!selected) { - return; - } - selected.classList.add("selected"); - selected.scrollIntoView({block: "end", behavior: "smooth"}); - } - - function refreshHelper() { - timeout = null; - var str = input.value; - first = null; - helper.innerHTML = ""; - if (!str && !options.show_all_if_empty) { - return; - } - - if (that.onSearchBox) { - var list = that.onSearchBox(helper, str, graphcanvas); - if (list) { - for (var i = 0; i < list.length; ++i) { - addResult(list[i]); - } - } - } else { - var c = 0; - str = str.toLowerCase(); - var filter = graphcanvas.filter || graphcanvas.graph.filter; - - // filter by type preprocess - if(options.do_type_filter && that.search_box){ - var sIn = that.search_box.querySelector(".slot_in_type_filter"); - var sOut = that.search_box.querySelector(".slot_out_type_filter"); - }else{ - var sIn = false; - var sOut = false; - } - - //extras - for (var i in LiteGraph.searchbox_extras) { - var extra = LiteGraph.searchbox_extras[i]; - if ((!options.show_all_if_empty || str) && extra.desc.toLowerCase().indexOf(str) === -1) { - continue; - } - var ctor = LiteGraph.registered_node_types[ extra.type ]; - if( ctor && ctor.filter != filter ) - continue; - if( ! inner_test_filter(extra.type) ) - continue; - addResult( extra.desc, "searchbox_extra" ); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - - var filtered = null; - if (Array.prototype.filter) { //filter supported - var keys = Object.keys( LiteGraph.registered_node_types ); //types - var filtered = keys.filter( inner_test_filter ); - } else { - filtered = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i) ) - filtered.push(i); - } - } - - for (var i = 0; i < filtered.length; i++) { - addResult(filtered[i]); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - - // add general type if filtering - if (options.show_general_after_typefiltered - && (sIn.value || sOut.value) - ){ - filtered_extra = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i, {inTypeOverride: sIn&&sIn.value?"*":false, outTypeOverride: sOut&&sOut.value?"*":false}) ) - filtered_extra.push(i); - } - for (var i = 0; i < filtered_extra.length; i++) { - addResult(filtered_extra[i], "generic_type"); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - } - - // check il filtering gave no results - if ((sIn.value || sOut.value) && - ( (helper.childNodes.length == 0 && options.show_general_if_none_on_typefilter) ) - ){ - filtered_extra = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i, {skipFilter: true}) ) - filtered_extra.push(i); - } - for (var i = 0; i < filtered_extra.length; i++) { - addResult(filtered_extra[i], "not_in_filter"); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - } - - function inner_test_filter( type, optsIn ) - { - var optsIn = optsIn || {}; - var optsDef = { skipFilter: false - ,inTypeOverride: false - ,outTypeOverride: false - }; - var opts = Object.assign(optsDef,optsIn); - var ctor = LiteGraph.registered_node_types[ type ]; - if(filter && ctor.filter != filter ) - return false; - if ((!options.show_all_if_empty || str) && type.toLowerCase().indexOf(str) === -1) - return false; - - // filter by slot IN, OUT types - if(options.do_type_filter && !opts.skipFilter){ - var sType = type; - - var sV = sIn.value; - if (opts.inTypeOverride!==false) sV = opts.inTypeOverride; - //if (sV.toLowerCase() == "_event_") sV = LiteGraph.EVENT; // -1 - - if(sIn && sV){ - //console.log("will check filter against "+sV); - if (LiteGraph.registered_slot_in_types[sV] && LiteGraph.registered_slot_in_types[sV].nodes){ // type is stored - //console.debug("check "+sType+" in "+LiteGraph.registered_slot_in_types[sV].nodes); - var doesInc = LiteGraph.registered_slot_in_types[sV].nodes.includes(sType); - if (doesInc!==false){ - //console.log(sType+" HAS "+sV); - }else{ - /*console.debug(LiteGraph.registered_slot_in_types[sV]); - console.log(+" DONT includes "+type);*/ - return false; - } - } - } - - var sV = sOut.value; - if (opts.outTypeOverride!==false) sV = opts.outTypeOverride; - //if (sV.toLowerCase() == "_event_") sV = LiteGraph.EVENT; // -1 - - if(sOut && sV){ - //console.log("search will check filter against "+sV); - if (LiteGraph.registered_slot_out_types[sV] && LiteGraph.registered_slot_out_types[sV].nodes){ // type is stored - //console.debug("check "+sType+" in "+LiteGraph.registered_slot_out_types[sV].nodes); - var doesInc = LiteGraph.registered_slot_out_types[sV].nodes.includes(sType); - if (doesInc!==false){ - //console.log(sType+" HAS "+sV); - }else{ - /*console.debug(LiteGraph.registered_slot_out_types[sV]); - console.log(+" DONT includes "+type);*/ - return false; - } - } - } - } - return true; - } - } - - function addResult(type, className) { - var help = document.createElement("div"); - if (!first) { - first = type; - } - help.innerText = type; - help.dataset["type"] = escape(type); - help.className = "litegraph lite-search-item"; - if (className) { - help.className += " " + className; - } - help.addEventListener("click", function(e) { - select(unescape(this.dataset["type"])); - }); - helper.appendChild(help); - } - } - - return dialog; - }; - - LGraphCanvas.prototype.showEditPropertyValue = function( node, property, options ) { - if (!node || node.properties[property] === undefined) { - return; - } - - options = options || {}; - var that = this; - - var info = node.getPropertyInfo(property); - var type = info.type; - - var input_html = ""; - - if (type == "string" || type == "number" || type == "array" || type == "object") { - input_html = ""; - } else if ( (type == "enum" || type == "combo") && info.values) { - input_html = ""; - } else if (type == "boolean" || type == "toggle") { - input_html = - ""; - } else { - console.warn("unknown type: " + type); - return; - } - - var dialog = this.createDialog( - "" + - (info.label ? info.label : property) + - "" + - input_html + - "", - options - ); - - var input = false; - if ((type == "enum" || type == "combo") && info.values) { - input = dialog.querySelector("select"); - input.addEventListener("change", function(e) { - dialog.modified(); - setValue(e.target.value); - //var index = e.target.value; - //setValue( e.options[e.selectedIndex].value ); - }); - } else if (type == "boolean" || type == "toggle") { - input = dialog.querySelector("input"); - if (input) { - input.addEventListener("click", function(e) { - dialog.modified(); - setValue(!!input.checked); - }); - } - } else { - input = dialog.querySelector("input"); - if (input) { - input.addEventListener("blur", function(e) { - this.focus(); - }); - - var v = node.properties[property] !== undefined ? node.properties[property] : ""; - if (type !== 'string') { - v = JSON.stringify(v); - } - - input.value = v; - input.addEventListener("keydown", function(e) { - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - // ENTER - inner(); // save - } else if (e.keyCode != 13) { - dialog.modified(); - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - } - } - if (input) input.focus(); - - var button = dialog.querySelector("button"); - button.addEventListener("click", inner); - - function inner() { - setValue(input.value); - } - - function setValue(value) { - - if(info && info.values && info.values.constructor === Object && info.values[value] != undefined ) - value = info.values[value]; - - if (typeof node.properties[property] == "number") { - value = Number(value); - } - if (type == "array" || type == "object") { - value = JSON.parse(value); - } - node.properties[property] = value; - if (node.graph) { - node.graph._version++; - } - if (node.onPropertyChanged) { - node.onPropertyChanged(property, value); - } - if(options.onclose) - options.onclose(); - dialog.close(); - node.setDirtyCanvas(true, true); - } - - return dialog; - }; - - // TODO refactor, theer are different dialog, some uses createDialog, some dont - LGraphCanvas.prototype.createDialog = function(html, options) { - var def_options = { checkForInput: false, closeOnLeave: true, closeOnLeave_checkModified: true }; - options = Object.assign(def_options, options || {}); - - var dialog = document.createElement("div"); - dialog.className = "graphdialog"; - dialog.innerHTML = html; - dialog.is_modified = false; - - var rect = this.canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (options.position) { - offsetx += options.position[0]; - offsety += options.position[1]; - } else if (options.event) { - offsetx += options.event.clientX; - offsety += options.event.clientY; - } //centered - else { - offsetx += this.canvas.width * 0.5; - offsety += this.canvas.height * 0.5; - } - - dialog.style.left = offsetx + "px"; - dialog.style.top = offsety + "px"; - - this.canvas.parentNode.appendChild(dialog); - - // acheck for input and use default behaviour: save on enter, close on esc - if (options.checkForInput){ - var aI = []; - var focused = false; - if (aI = dialog.querySelectorAll("input")){ - aI.forEach(function(iX) { - iX.addEventListener("keydown",function(e){ - dialog.modified(); - if (e.keyCode == 27) { - dialog.close(); - } else if (e.keyCode != 13) { - return; - } - // set value ? - e.preventDefault(); - e.stopPropagation(); - }); - if (!focused) iX.focus(); - }); - } - } - - dialog.modified = function(){ - dialog.is_modified = true; - } - dialog.close = function() { - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - var dialogCloseTimer = null; - var prevent_timeout = false; - dialog.addEventListener("mouseleave", function(e) { - if (prevent_timeout) - return; - if(options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - dialog.addEventListener("mouseenter", function(e) { - if(options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - var selInDia = dialog.querySelectorAll("select"); - if (selInDia){ - // if filtering, check focus changed to comboboxes and prevent closing - selInDia.forEach(function(selIn) { - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - }); - } - - return dialog; - }; - - LGraphCanvas.prototype.createPanel = function(title, options) { - options = options || {}; - - var ref_window = options.window || window; - var root = document.createElement("div"); - root.className = "litegraph dialog"; - root.innerHTML = "
"; - root.header = root.querySelector(".dialog-header"); - - if(options.width) - root.style.width = options.width + (options.width.constructor === Number ? "px" : ""); - if(options.height) - root.style.height = options.height + (options.height.constructor === Number ? "px" : ""); - if(options.closable) - { - var close = document.createElement("span"); - close.innerHTML = "✕"; - close.classList.add("close"); - close.addEventListener("click",function(){ - root.close(); - }); - root.header.appendChild(close); - } - root.title_element = root.querySelector(".dialog-title"); - root.title_element.innerText = title; - root.content = root.querySelector(".dialog-content"); - root.alt_content = root.querySelector(".dialog-alt-content"); - root.footer = root.querySelector(".dialog-footer"); - - root.close = function() - { - if (root.onClose && typeof root.onClose == "function"){ - root.onClose(); - } - if(root.parentNode) - root.parentNode.removeChild(root); - /* XXX CHECK THIS */ - if(this.parentNode){ - this.parentNode.removeChild(this); - } - /* XXX this was not working, was fixed with an IF, check this */ - } - - // function to swap panel content - root.toggleAltContent = function(force){ - if (typeof force != "undefined"){ - var vTo = force ? "block" : "none"; - var vAlt = force ? "none" : "block"; - }else{ - var vTo = root.alt_content.style.display != "block" ? "block" : "none"; - var vAlt = root.alt_content.style.display != "block" ? "none" : "block"; - } - root.alt_content.style.display = vTo; - root.content.style.display = vAlt; - } - - root.toggleFooterVisibility = function(force){ - if (typeof force != "undefined"){ - var vTo = force ? "block" : "none"; - }else{ - var vTo = root.footer.style.display != "block" ? "block" : "none"; - } - root.footer.style.display = vTo; - } - - root.clear = function() - { - this.content.innerHTML = ""; - } - - root.addHTML = function(code, classname, on_footer) - { - var elem = document.createElement("div"); - if(classname) - elem.className = classname; - elem.innerHTML = code; - if(on_footer) - root.footer.appendChild(elem); - else - root.content.appendChild(elem); - return elem; - } - - root.addButton = function( name, callback, options ) - { - var elem = document.createElement("button"); - elem.innerText = name; - elem.options = options; - elem.classList.add("btn"); - elem.addEventListener("click",callback); - root.footer.appendChild(elem); - return elem; - } - - root.addSeparator = function() - { - var elem = document.createElement("div"); - elem.className = "separator"; - root.content.appendChild(elem); - } - - root.addWidget = function( type, name, value, options, callback ) - { - options = options || {}; - var str_value = String(value); - type = type.toLowerCase(); - if(type == "number") - str_value = value.toFixed(3); - - var elem = document.createElement("div"); - elem.className = "property"; - elem.innerHTML = ""; - elem.querySelector(".property_name").innerText = options.label || name; - var value_element = elem.querySelector(".property_value"); - value_element.innerText = str_value; - elem.dataset["property"] = name; - elem.dataset["type"] = options.type || type; - elem.options = options; - elem.value = value; - - if( type == "code" ) - elem.addEventListener("click", function(e){ root.inner_showCodePad( this.dataset["property"] ); }); - else if (type == "boolean") - { - elem.classList.add("boolean"); - if(value) - elem.classList.add("bool-on"); - elem.addEventListener("click", function(){ - //var v = node.properties[this.dataset["property"]]; - //node.setProperty(this.dataset["property"],!v); this.innerText = v ? "true" : "false"; - var propname = this.dataset["property"]; - this.value = !this.value; - this.classList.toggle("bool-on"); - this.querySelector(".property_value").innerText = this.value ? "true" : "false"; - innerChange(propname, this.value ); - }); - } - else if (type == "string" || type == "number") - { - value_element.setAttribute("contenteditable",true); - value_element.addEventListener("keydown", function(e){ - if(e.code == "Enter" && (type != "string" || !e.shiftKey)) // allow for multiline - { - e.preventDefault(); - this.blur(); - } - }); - value_element.addEventListener("blur", function(){ - var v = this.innerText; - var propname = this.parentNode.dataset["property"]; - var proptype = this.parentNode.dataset["type"]; - if( proptype == "number") - v = Number(v); - innerChange(propname, v); - }); - } - else if (type == "enum" || type == "combo") { - var str_value = LGraphCanvas.getPropertyPrintableValue( value, options.values ); - value_element.innerText = str_value; - - value_element.addEventListener("click", function(event){ - var values = options.values || []; - var propname = this.parentNode.dataset["property"]; - var elem_that = this; - var menu = new LiteGraph.ContextMenu(values,{ - event: event, - className: "dark", - callback: inner_clicked - }, - ref_window); - function inner_clicked(v, option, event) { - //node.setProperty(propname,v); - //graphcanvas.dirty_canvas = true; - elem_that.innerText = v; - innerChange(propname,v); - return false; - } - }); - } - - root.content.appendChild(elem); - - function innerChange(name, value) - { - //console.log("change",name,value); - //that.dirty_canvas = true; - if(options.callback) - options.callback(name,value,options); - if(callback) - callback(name,value,options); - } - - return elem; - } - - if (root.onOpen && typeof root.onOpen == "function") root.onOpen(); - - return root; - }; - - LGraphCanvas.getPropertyPrintableValue = function(value, values) - { - if(!values) - return String(value); - - if(values.constructor === Array) - { - return String(value); - } - - if(values.constructor === Object) - { - var desc_value = ""; - for(var k in values) - { - if(values[k] != value) - continue; - desc_value = k; - break; - } - return String(value) + " ("+desc_value+")"; - } - } - - LGraphCanvas.prototype.closePanels = function(){ - var panel = document.querySelector("#node-panel"); - if(panel) - panel.close(); - var panel = document.querySelector("#option-panel"); - if(panel) - panel.close(); - } - - LGraphCanvas.prototype.showShowGraphOptionsPanel = function(refOpts, obEv, refMenu, refMenu2){ - if(this.constructor && this.constructor.name == "HTMLDivElement"){ - // assume coming from the menu event click - if (!obEv || !obEv.event || !obEv.event.target || !obEv.event.target.lgraphcanvas){ - console.warn("Canvas not found"); // need a ref to canvas obj - /*console.debug(event); - console.debug(event.target);*/ - return; - } - var graphcanvas = obEv.event.target.lgraphcanvas; - }else{ - // assume called internally - var graphcanvas = this; - } - graphcanvas.closePanels(); - var ref_window = graphcanvas.getCanvasWindow(); - panel = graphcanvas.createPanel("Options",{ - closable: true - ,window: ref_window - ,onOpen: function(){ - graphcanvas.OPTIONPANEL_IS_OPEN = true; - } - ,onClose: function(){ - graphcanvas.OPTIONPANEL_IS_OPEN = false; - graphcanvas.options_panel = null; - } - }); - graphcanvas.options_panel = panel; - panel.id = "option-panel"; - panel.classList.add("settings"); - - function inner_refresh(){ - - panel.content.innerHTML = ""; //clear - - var fUpdate = function(name, value, options){ - switch(name){ - /*case "Render mode": - // Case "".. - if (options.values && options.key){ - var kV = Object.values(options.values).indexOf(value); - if (kV>=0 && options.values[kV]){ - console.debug("update graph options: "+options.key+": "+kV); - graphcanvas[options.key] = kV; - //console.debug(graphcanvas); - break; - } - } - console.warn("unexpected options"); - console.debug(options); - break;*/ - default: - //console.debug("want to update graph options: "+name+": "+value); - if (options && options.key){ - name = options.key; - } - if (options.values){ - value = Object.values(options.values).indexOf(value); - } - //console.debug("update graph option: "+name+": "+value); - graphcanvas[name] = value; - break; - } - }; - - // panel.addWidget( "string", "Graph name", "", {}, fUpdate); // implement - - var aProps = LiteGraph.availableCanvasOptions; - aProps.sort(); - for(var pI in aProps){ - var pX = aProps[pI]; - panel.addWidget( "boolean", pX, graphcanvas[pX], {key: pX, on: "True", off: "False"}, fUpdate); - } - - var aLinks = [ graphcanvas.links_render_mode ]; - panel.addWidget( "combo", "Render mode", LiteGraph.LINK_RENDER_MODES[graphcanvas.links_render_mode], {key: "links_render_mode", values: LiteGraph.LINK_RENDER_MODES}, fUpdate); - - panel.addSeparator(); - - panel.footer.innerHTML = ""; // clear - - } - inner_refresh(); - - graphcanvas.canvas.parentNode.appendChild( panel ); - } - - LGraphCanvas.prototype.showShowNodePanel = function( node ) - { - this.SELECTED_NODE = node; - this.closePanels(); - var ref_window = this.getCanvasWindow(); - var that = this; - var graphcanvas = this; - var panel = this.createPanel(node.title || "",{ - closable: true - ,window: ref_window - ,onOpen: function(){ - graphcanvas.NODEPANEL_IS_OPEN = true; - } - ,onClose: function(){ - graphcanvas.NODEPANEL_IS_OPEN = false; - graphcanvas.node_panel = null; - } - }); - graphcanvas.node_panel = panel; - panel.id = "node-panel"; - panel.node = node; - panel.classList.add("settings"); - - function inner_refresh() - { - panel.content.innerHTML = ""; //clear - panel.addHTML(""+node.type+""+(node.constructor.desc || "")+""); - - panel.addHTML("

Properties

"); - - var fUpdate = function(name,value){ - graphcanvas.graph.beforeChange(node); - switch(name){ - case "Title": - node.title = value; - break; - case "Mode": - var kV = Object.values(LiteGraph.NODE_MODES).indexOf(value); - if (kV>=0 && LiteGraph.NODE_MODES[kV]){ - node.changeMode(kV); - }else{ - console.warn("unexpected mode: "+value); - } - break; - case "Color": - if (LGraphCanvas.node_colors[value]){ - node.color = LGraphCanvas.node_colors[value].color; - node.bgcolor = LGraphCanvas.node_colors[value].bgcolor; - }else{ - console.warn("unexpected color: "+value); - } - break; - default: - node.setProperty(name,value); - break; - } - graphcanvas.graph.afterChange(); - graphcanvas.dirty_canvas = true; - }; - - panel.addWidget( "string", "Title", node.title, {}, fUpdate); - - panel.addWidget( "combo", "Mode", LiteGraph.NODE_MODES[node.mode], {values: LiteGraph.NODE_MODES}, fUpdate); - - var nodeCol = ""; - if (node.color !== undefined){ - nodeCol = Object.keys(LGraphCanvas.node_colors).filter(function(nK){ return LGraphCanvas.node_colors[nK].color == node.color; }); - } - - panel.addWidget( "combo", "Color", nodeCol, {values: Object.keys(LGraphCanvas.node_colors)}, fUpdate); - - for(var pName in node.properties) - { - var value = node.properties[pName]; - var info = node.getPropertyInfo(pName); - var type = info.type || "string"; - - //in case the user wants control over the side panel widget - if( node.onAddPropertyToPanel && node.onAddPropertyToPanel(pName,panel) ) - continue; - - panel.addWidget( info.widget || info.type, pName, value, info, fUpdate); - } - - panel.addSeparator(); - - if(node.onShowCustomPanelInfo) - node.onShowCustomPanelInfo(panel); - - panel.footer.innerHTML = ""; // clear - panel.addButton("Delete",function(){ - if(node.block_delete) - return; - node.graph.remove(node); - panel.close(); - }).classList.add("delete"); - } - - panel.inner_showCodePad = function( propname ) - { - panel.classList.remove("settings"); - panel.classList.add("centered"); - - - /*if(window.CodeFlask) //disabled for now - { - panel.content.innerHTML = "
"; - var flask = new CodeFlask( "div.code", { language: 'js' }); - flask.updateCode(node.properties[propname]); - flask.onUpdate( function(code) { - node.setProperty(propname, code); - }); - } - else - {*/ - panel.alt_content.innerHTML = ""; - var textarea = panel.alt_content.querySelector("textarea"); - var fDoneWith = function(){ - panel.toggleAltContent(false); //if(node_prop_div) node_prop_div.style.display = "block"; // panel.close(); - panel.toggleFooterVisibility(true); - textarea.parentNode.removeChild(textarea); - panel.classList.add("settings"); - panel.classList.remove("centered"); - inner_refresh(); - } - textarea.value = node.properties[propname]; - textarea.addEventListener("keydown", function(e){ - if(e.code == "Enter" && e.ctrlKey ) - { - node.setProperty(propname, textarea.value); - fDoneWith(); - } - }); - panel.toggleAltContent(true); - panel.toggleFooterVisibility(false); - textarea.style.height = "calc(100% - 40px)"; - /*}*/ - var assign = panel.addButton( "Assign", function(){ - node.setProperty(propname, textarea.value); - fDoneWith(); - }); - panel.alt_content.appendChild(assign); //panel.content.appendChild(assign); - var button = panel.addButton( "Close", fDoneWith); - button.style.float = "right"; - panel.alt_content.appendChild(button); // panel.content.appendChild(button); - } - - inner_refresh(); - - this.canvas.parentNode.appendChild( panel ); - } - - LGraphCanvas.prototype.showSubgraphPropertiesDialog = function(node) - { - console.log("showing subgraph properties dialog"); - - var old_panel = this.canvas.parentNode.querySelector(".subgraph_dialog"); - if(old_panel) - old_panel.close(); - - var panel = this.createPanel("Subgraph Inputs",{closable:true, width: 500}); - panel.node = node; - panel.classList.add("subgraph_dialog"); - - function inner_refresh() - { - panel.clear(); - - //show currents - if(node.inputs) - for(var i = 0; i < node.inputs.length; ++i) - { - var input = node.inputs[i]; - if(input.not_subgraph_input) - continue; - var html = " "; - var elem = panel.addHTML(html,"subgraph_property"); - elem.dataset["name"] = input.name; - elem.dataset["slot"] = i; - elem.querySelector(".name").innerText = input.name; - elem.querySelector(".type").innerText = input.type; - elem.querySelector("button").addEventListener("click",function(e){ - node.removeInput( Number( this.parentNode.dataset["slot"] ) ); - inner_refresh(); - }); - } - } - - //add extra - var html = " + NameType"; - var elem = panel.addHTML(html,"subgraph_property extra", true); - elem.querySelector("button").addEventListener("click", function(e){ - var elem = this.parentNode; - var name = elem.querySelector(".name").value; - var type = elem.querySelector(".type").value; - if(!name || node.findInputSlot(name) != -1) - return; - node.addInput(name,type); - elem.querySelector(".name").value = ""; - elem.querySelector(".type").value = ""; - inner_refresh(); - }); - - inner_refresh(); - this.canvas.parentNode.appendChild(panel); - return panel; - } - LGraphCanvas.prototype.showSubgraphPropertiesDialogRight = function (node) { - - // console.log("showing subgraph properties dialog"); - var that = this; - // old_panel if old_panel is exist close it - var old_panel = this.canvas.parentNode.querySelector(".subgraph_dialog"); - if (old_panel) - old_panel.close(); - // new panel - var panel = this.createPanel("Subgraph Outputs", { closable: true, width: 500 }); - panel.node = node; - panel.classList.add("subgraph_dialog"); - - function inner_refresh() { - panel.clear(); - //show currents - if (node.outputs) - for (var i = 0; i < node.outputs.length; ++i) { - var input = node.outputs[i]; - if (input.not_subgraph_output) - continue; - var html = " "; - var elem = panel.addHTML(html, "subgraph_property"); - elem.dataset["name"] = input.name; - elem.dataset["slot"] = i; - elem.querySelector(".name").innerText = input.name; - elem.querySelector(".type").innerText = input.type; - elem.querySelector("button").addEventListener("click", function (e) { - node.removeOutput(Number(this.parentNode.dataset["slot"])); - inner_refresh(); - }); - } - } - - //add extra - var html = " + NameType"; - var elem = panel.addHTML(html, "subgraph_property extra", true); - elem.querySelector(".name").addEventListener("keydown", function (e) { - if (e.keyCode == 13) { - addOutput.apply(this) - } - }) - elem.querySelector("button").addEventListener("click", function (e) { - addOutput.apply(this) - }); - function addOutput() { - var elem = this.parentNode; - var name = elem.querySelector(".name").value; - var type = elem.querySelector(".type").value; - if (!name || node.findOutputSlot(name) != -1) - return; - node.addOutput(name, type); - elem.querySelector(".name").value = ""; - elem.querySelector(".type").value = ""; - inner_refresh(); - } - - inner_refresh(); - this.canvas.parentNode.appendChild(panel); - return panel; - } - LGraphCanvas.prototype.checkPanels = function() - { - if(!this.canvas) - return; - var panels = this.canvas.parentNode.querySelectorAll(".litegraph.dialog"); - for(var i = 0; i < panels.length; ++i) - { - var panel = panels[i]; - if( !panel.node ) - continue; - if( !panel.node.graph || panel.graph != this.graph ) - panel.close(); - } - } - - LGraphCanvas.onMenuNodeCollapse = function(value, options, e, menu, node) { - node.graph.beforeChange(/*?*/); - - var fApplyMultiNode = function(node){ - node.collapse(); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.graph.afterChange(/*?*/); - }; - - LGraphCanvas.onMenuNodePin = function(value, options, e, menu, node) { - node.pin(); - }; - - LGraphCanvas.onMenuNodeMode = function(value, options, e, menu, node) { - new LiteGraph.ContextMenu( - LiteGraph.NODE_MODES, - { event: e, callback: inner_clicked, parentMenu: menu, node: node } - ); - - function inner_clicked(v) { - if (!node) { - return; - } - var kV = Object.values(LiteGraph.NODE_MODES).indexOf(v); - var fApplyMultiNode = function(node){ - if (kV>=0 && LiteGraph.NODE_MODES[kV]) - node.changeMode(kV); - else{ - console.warn("unexpected mode: "+v); - node.changeMode(LiteGraph.ALWAYS); - } - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - } - - return false; - }; - - LGraphCanvas.onMenuNodeColors = function(value, options, e, menu, node) { - if (!node) { - throw "no node for color"; - } - - var values = []; - values.push({ - value: null, - content: - "No color" - }); - - for (var i in LGraphCanvas.node_colors) { - var color = LGraphCanvas.node_colors[i]; - var value = { - value: i, - content: - "" + - i + - "" - }; - values.push(value); - } - new LiteGraph.ContextMenu(values, { - event: e, - callback: inner_clicked, - parentMenu: menu, - node: node - }); - - function inner_clicked(v) { - if (!node) { - return; - } - - var color = v.value ? LGraphCanvas.node_colors[v.value] : null; - - var fApplyColor = function(node){ - if (color) { - if (node.constructor === LiteGraph.LGraphGroup) { - node.color = color.groupcolor; - } else { - node.color = color.color; - node.bgcolor = color.bgcolor; - } - } else { - delete node.color; - delete node.bgcolor; - } - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyColor(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyColor(graphcanvas.selected_nodes[i]); - } - } - node.setDirtyCanvas(true, true); - } - - return false; - }; - - LGraphCanvas.onMenuNodeShapes = function(value, options, e, menu, node) { - if (!node) { - throw "no node passed"; - } - - new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, { - event: e, - callback: inner_clicked, - parentMenu: menu, - node: node - }); - - function inner_clicked(v) { - if (!node) { - return; - } - node.graph.beforeChange(/*?*/); //node - - var fApplyMultiNode = function(node){ - node.shape = v; - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.graph.afterChange(/*?*/); //node - node.setDirtyCanvas(true); - } - - return false; - }; - - LGraphCanvas.onMenuNodeRemove = function(value, options, e, menu, node) { - if (!node) { - throw "no node passed"; - } - - var graph = node.graph; - graph.beforeChange(); - - - var fApplyMultiNode = function(node){ - if (node.removable === false) { - return; - } - graph.remove(node); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - graph.afterChange(); - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.onMenuNodeToSubgraph = function(value, options, e, menu, node) { - var graph = node.graph; - var graphcanvas = LGraphCanvas.active_canvas; - if(!graphcanvas) //?? - return; - - var nodes_list = Object.values( graphcanvas.selected_nodes || {} ); - if( !nodes_list.length ) - nodes_list = [ node ]; - - var subgraph_node = LiteGraph.createNode("graph/subgraph"); - subgraph_node.pos = node.pos.concat(); - graph.add(subgraph_node); - - subgraph_node.buildFromNodes( nodes_list ); - - graphcanvas.deselectAllNodes(); - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.onMenuNodeClone = function(value, options, e, menu, node) { - - node.graph.beforeChange(); - - var newSelected = {}; - - var fApplyMultiNode = function(node){ - if (node.clonable == false) { - return; - } - var newnode = node.clone(); - if (!newnode) { - return; - } - newnode.pos = [node.pos[0] + 5, node.pos[1] + 5]; - node.graph.add(newnode); - newSelected[newnode.id] = newnode; - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - if(Object.keys(newSelected).length){ - graphcanvas.selectNodes(newSelected); - } - - node.graph.afterChange(); - - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.node_colors = { - red: { color: "#322", bgcolor: "#533", groupcolor: "#A88" }, - brown: { color: "#332922", bgcolor: "#593930", groupcolor: "#b06634" }, - green: { color: "#232", bgcolor: "#353", groupcolor: "#8A8" }, - blue: { color: "#223", bgcolor: "#335", groupcolor: "#88A" }, - pale_blue: { - color: "#2a363b", - bgcolor: "#3f5159", - groupcolor: "#3f789e" - }, - cyan: { color: "#233", bgcolor: "#355", groupcolor: "#8AA" }, - purple: { color: "#323", bgcolor: "#535", groupcolor: "#a1309b" }, - yellow: { color: "#432", bgcolor: "#653", groupcolor: "#b58b2a" }, - black: { color: "#222", bgcolor: "#000", groupcolor: "#444" } - }; - - LGraphCanvas.prototype.getCanvasMenuOptions = function() { - var options = null; - var that = this; - if (this.getMenuOptions) { - options = this.getMenuOptions(); - } else { - options = [ - { - content: "Add Node", - has_submenu: true, - callback: LGraphCanvas.onMenuAdd - }, - { content: "Add Group", callback: LGraphCanvas.onGroupAdd }, - //{ content: "Arrange", callback: that.graph.arrange }, - //{content:"Collapse All", callback: LGraphCanvas.onMenuCollapseAll } - ]; - /*if (LiteGraph.showCanvasOptions){ - options.push({ content: "Options", callback: that.showShowGraphOptionsPanel }); - }*/ - - if (this._graph_stack && this._graph_stack.length > 0) { - options.push(null, { - content: "Close subgraph", - callback: this.closeSubgraph.bind(this) - }); - } - } - - if (this.getExtraMenuOptions) { - var extra = this.getExtraMenuOptions(this, options); - if (extra) { - options = options.concat(extra); - } - } - - return options; - }; - - //called by processContextMenu to extract the menu list - LGraphCanvas.prototype.getNodeMenuOptions = function(node) { - var options = null; - - if (node.getMenuOptions) { - options = node.getMenuOptions(this); - } else { - options = [ - { - content: "Inputs", - has_submenu: true, - disabled: true, - callback: LGraphCanvas.showMenuNodeOptionalInputs - }, - { - content: "Outputs", - has_submenu: true, - disabled: true, - callback: LGraphCanvas.showMenuNodeOptionalOutputs - }, - null, - { - content: "Properties", - has_submenu: true, - callback: LGraphCanvas.onShowMenuNodeProperties - }, - null, - { - content: "Title", - callback: LGraphCanvas.onShowPropertyEditor - }, - { - content: "Mode", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeMode - }]; - if(node.resizable !== false){ - options.push({ - content: "Resize", callback: LGraphCanvas.onMenuResizeNode - }); - } - options.push( - { - content: "Collapse", - callback: LGraphCanvas.onMenuNodeCollapse - }, - { content: "Pin", callback: LGraphCanvas.onMenuNodePin }, - { - content: "Colors", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeColors - }, - { - content: "Shapes", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeShapes - }, - null - ); - } - - if (node.onGetInputs) { - var inputs = node.onGetInputs(); - if (inputs && inputs.length) { - options[0].disabled = false; - } - } - - if (node.onGetOutputs) { - var outputs = node.onGetOutputs(); - if (outputs && outputs.length) { - options[1].disabled = false; - } - } - - if (node.getExtraMenuOptions) { - var extra = node.getExtraMenuOptions(this, options); - if (extra) { - extra.push(null); - options = extra.concat(options); - } - } - - if (node.clonable !== false) { - options.push({ - content: "Clone", - callback: LGraphCanvas.onMenuNodeClone - }); - } - - if(0) //TODO - options.push({ - content: "To Subgraph", - callback: LGraphCanvas.onMenuNodeToSubgraph - }); - - options.push(null, { - content: "Remove", - disabled: !(node.removable !== false && !node.block_delete ), - callback: LGraphCanvas.onMenuNodeRemove - }); - - if (node.graph && node.graph.onGetNodeMenuOptions) { - node.graph.onGetNodeMenuOptions(options, node); - } - - return options; - }; - - LGraphCanvas.prototype.getGroupMenuOptions = function(node) { - var o = [ - { content: "Title", callback: LGraphCanvas.onShowPropertyEditor }, - { - content: "Color", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeColors - }, - { - content: "Font size", - property: "font_size", - type: "Number", - callback: LGraphCanvas.onShowPropertyEditor - }, - null, - { content: "Remove", callback: LGraphCanvas.onMenuNodeRemove } - ]; - - return o; - }; - - LGraphCanvas.prototype.processContextMenu = function(node, event) { - var that = this; - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var menu_info = null; - var options = { - event: event, - callback: inner_option_clicked, - extra: node - }; - - if(node) - options.title = node.type; - - //check if mouse is in input - var slot = null; - if (node) { - slot = node.getSlotInPosition(event.canvasX, event.canvasY); - LGraphCanvas.active_node = node; - } - - if (slot) { - //on slot - menu_info = []; - if (node.getSlotMenuOptions) { - menu_info = node.getSlotMenuOptions(slot); - } else { - if ( - slot && - slot.output && - slot.output.links && - slot.output.links.length - ) { - menu_info.push({ content: "Disconnect Links", slot: slot }); - } - var _slot = slot.input || slot.output; - if (_slot.removable){ - menu_info.push( - _slot.locked - ? "Cannot remove" - : { content: "Remove Slot", slot: slot } - ); - } - if (!_slot.nameLocked){ - menu_info.push({ content: "Rename Slot", slot: slot }); - } - - } - options.title = - (slot.input ? slot.input.type : slot.output.type) || "*"; - if (slot.input && slot.input.type == LiteGraph.ACTION) { - options.title = "Action"; - } - if (slot.output && slot.output.type == LiteGraph.EVENT) { - options.title = "Event"; - } - } else { - if (node) { - //on node - menu_info = this.getNodeMenuOptions(node); - } else { - menu_info = this.getCanvasMenuOptions(); - var group = this.graph.getGroupOnPos( - event.canvasX, - event.canvasY - ); - if (group) { - //on group - menu_info.push(null, { - content: "Edit Group", - has_submenu: true, - submenu: { - title: "Group", - extra: group, - options: this.getGroupMenuOptions(group) - } - }); - } - } - } - - //show menu - if (!menu_info) { - return; - } - - var menu = new LiteGraph.ContextMenu(menu_info, options, ref_window); - - function inner_option_clicked(v, options, e) { - if (!v) { - return; - } - - if (v.content == "Remove Slot") { - var info = v.slot; - node.graph.beforeChange(); - if (info.input) { - node.removeInput(info.slot); - } else if (info.output) { - node.removeOutput(info.slot); - } - node.graph.afterChange(); - return; - } else if (v.content == "Disconnect Links") { - var info = v.slot; - node.graph.beforeChange(); - if (info.output) { - node.disconnectOutput(info.slot); - } else if (info.input) { - node.disconnectInput(info.slot); - } - node.graph.afterChange(); - return; - } else if (v.content == "Rename Slot") { - var info = v.slot; - var slot_info = info.input - ? node.getInputInfo(info.slot) - : node.getOutputInfo(info.slot); - var dialog = that.createDialog( - "Name", - options - ); - var input = dialog.querySelector("input"); - if (input && slot_info) { - input.value = slot_info.label || ""; - } - var inner = function(){ - node.graph.beforeChange(); - if (input.value) { - if (slot_info) { - slot_info.label = input.value; - } - that.setDirty(true); - } - dialog.close(); - node.graph.afterChange(); - } - dialog.querySelector("button").addEventListener("click", inner); - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - inner(); // save - } else if (e.keyCode != 13 && e.target.localName != "textarea") { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - input.focus(); - } - - //if(v.callback) - // return v.callback.call(that, node, options, e, menu, that, event ); - } - }; - - //API ************************************************* - //like rect but rounded corners - if (typeof(window) != "undefined" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) { - window.CanvasRenderingContext2D.prototype.roundRect = function( - x, - y, - w, - h, - radius, - radius_low - ) { - var top_left_radius = 0; - var top_right_radius = 0; - var bottom_left_radius = 0; - var bottom_right_radius = 0; - - if ( radius === 0 ) - { - this.rect(x,y,w,h); - return; - } - - if(radius_low === undefined) - radius_low = radius; - - //make it compatible with official one - if(radius != null && radius.constructor === Array) - { - if(radius.length == 1) - top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0]; - else if(radius.length == 2) - { - top_left_radius = bottom_right_radius = radius[0]; - top_right_radius = bottom_left_radius = radius[1]; - } - else if(radius.length == 4) - { - top_left_radius = radius[0]; - top_right_radius = radius[1]; - bottom_left_radius = radius[2]; - bottom_right_radius = radius[3]; - } - else - return; - } - else //old using numbers - { - top_left_radius = radius || 0; - top_right_radius = radius || 0; - bottom_left_radius = radius_low || 0; - bottom_right_radius = radius_low || 0; - } - - //top right - this.moveTo(x + top_left_radius, y); - this.lineTo(x + w - top_right_radius, y); - this.quadraticCurveTo(x + w, y, x + w, y + top_right_radius); - - //bottom right - this.lineTo(x + w, y + h - bottom_right_radius); - this.quadraticCurveTo( - x + w, - y + h, - x + w - bottom_right_radius, - y + h - ); - - //bottom left - this.lineTo(x + bottom_right_radius, y + h); - this.quadraticCurveTo(x, y + h, x, y + h - bottom_left_radius); - - //top left - this.lineTo(x, y + bottom_left_radius); - this.quadraticCurveTo(x, y, x + top_left_radius, y); - }; - }//if - - function compareObjects(a, b) { - for (var i in a) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - LiteGraph.compareObjects = compareObjects; - - function distance(a, b) { - return Math.sqrt( - (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) - ); - } - LiteGraph.distance = distance; - - function colorToString(c) { - return ( - "rgba(" + - Math.round(c[0] * 255).toFixed() + - "," + - Math.round(c[1] * 255).toFixed() + - "," + - Math.round(c[2] * 255).toFixed() + - "," + - (c.length == 4 ? c[3].toFixed(2) : "1.0") + - ")" - ); - } - LiteGraph.colorToString = colorToString; - - function isInsideRectangle(x, y, left, top, width, height) { - if (left < x && left + width > x && top < y && top + height > y) { - return true; - } - return false; - } - LiteGraph.isInsideRectangle = isInsideRectangle; - - //[minx,miny,maxx,maxy] - function growBounding(bounding, x, y) { - if (x < bounding[0]) { - bounding[0] = x; - } else if (x > bounding[2]) { - bounding[2] = x; - } - - if (y < bounding[1]) { - bounding[1] = y; - } else if (y > bounding[3]) { - bounding[3] = y; - } - } - LiteGraph.growBounding = growBounding; - - //point inside bounding box - function isInsideBounding(p, bb) { - if ( - p[0] < bb[0][0] || - p[1] < bb[0][1] || - p[0] > bb[1][0] || - p[1] > bb[1][1] - ) { - return false; - } - return true; - } - LiteGraph.isInsideBounding = isInsideBounding; - - //bounding overlap, format: [ startx, starty, width, height ] - function overlapBounding(a, b) { - var A_end_x = a[0] + a[2]; - var A_end_y = a[1] + a[3]; - var B_end_x = b[0] + b[2]; - var B_end_y = b[1] + b[3]; - - if ( - a[0] > B_end_x || - a[1] > B_end_y || - A_end_x < b[0] || - A_end_y < b[1] - ) { - return false; - } - return true; - } - LiteGraph.overlapBounding = overlapBounding; - - //Convert a hex value to its decimal value - the inputted hex must be in the - // format of a hex triplet - the kind we use for HTML colours. The function - // will return an array with three values. - function hex2num(hex) { - if (hex.charAt(0) == "#") { - hex = hex.slice(1); - } //Remove the '#' char - if there is one. - hex = hex.toUpperCase(); - var hex_alphabets = "0123456789ABCDEF"; - var value = new Array(3); - var k = 0; - var int1, int2; - for (var i = 0; i < 6; i += 2) { - int1 = hex_alphabets.indexOf(hex.charAt(i)); - int2 = hex_alphabets.indexOf(hex.charAt(i + 1)); - value[k] = int1 * 16 + int2; - k++; - } - return value; - } - - LiteGraph.hex2num = hex2num; - - //Give a array with three values as the argument and the function will return - // the corresponding hex triplet. - function num2hex(triplet) { - var hex_alphabets = "0123456789ABCDEF"; - var hex = "#"; - var int1, int2; - for (var i = 0; i < 3; i++) { - int1 = triplet[i] / 16; - int2 = triplet[i] % 16; - - hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2); - } - return hex; - } - - LiteGraph.num2hex = num2hex; - - /* LiteGraph GUI elements used for canvas editing *************************************/ - - /** - * ContextMenu from LiteGUI - * - * @class ContextMenu - * @constructor - * @param {Array} values (allows object { title: "Nice text", callback: function ... }) - * @param {Object} options [optional] Some options:\ - * - title: title to show on top of the menu - * - callback: function to call when an option is clicked, it receives the item information - * - ignore_item_callbacks: ignores the callback inside the item, it just calls the options.callback - * - event: you can pass a MouseEvent, this way the ContextMenu appears in that position - */ - function ContextMenu(values, options) { - options = options || {}; - this.options = options; - var that = this; - - //to link a menu with its parent - if (options.parentMenu) { - if (options.parentMenu.constructor !== this.constructor) { - console.error( - "parentMenu must be of class ContextMenu, ignoring it" - ); - options.parentMenu = null; - } else { - this.parentMenu = options.parentMenu; - this.parentMenu.lock = true; - this.parentMenu.current_submenu = this; - } - } - - var eventClass = null; - if(options.event) //use strings because comparing classes between windows doesnt work - eventClass = options.event.constructor.name; - if ( eventClass !== "MouseEvent" && - eventClass !== "CustomEvent" && - eventClass !== "PointerEvent" - ) { - console.error( - "Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. ("+eventClass+")" - ); - options.event = null; - } - - var root = document.createElement("div"); - root.className = "litegraph litecontextmenu litemenubar-panel"; - if (options.className) { - root.className += " " + options.className; - } - root.style.minWidth = 100; - root.style.minHeight = 100; - root.style.pointerEvents = "none"; - setTimeout(function() { - root.style.pointerEvents = "auto"; - }, 100); //delay so the mouse up event is not caught by this element - - //this prevents the default context browser menu to open in case this menu was created when pressing right button - LiteGraph.pointerListenerAdd(root,"up", - function(e) { - //console.log("pointerevents: ContextMenu up root prevent"); - e.preventDefault(); - return true; - }, - true - ); - root.addEventListener( - "contextmenu", - function(e) { - if (e.button != 2) { - //right button - return false; - } - e.preventDefault(); - return false; - }, - true - ); - - LiteGraph.pointerListenerAdd(root,"down", - function(e) { - //console.log("pointerevents: ContextMenu down"); - if (e.button == 2) { - that.close(); - e.preventDefault(); - return true; - } - }, - true - ); - - function on_mouse_wheel(e) { - var pos = parseInt(root.style.top); - root.style.top = - (pos + e.deltaY * options.scroll_speed).toFixed() + "px"; - e.preventDefault(); - return true; - } - - if (!options.scroll_speed) { - options.scroll_speed = 0.1; - } - - root.addEventListener("wheel", on_mouse_wheel, true); - root.addEventListener("mousewheel", on_mouse_wheel, true); - - this.root = root; - - //title - if (options.title) { - var element = document.createElement("div"); - element.className = "litemenu-title"; - element.innerHTML = options.title; - root.appendChild(element); - } - - //entries - var num = 0; - for (var i=0; i < values.length; i++) { - var name = values.constructor == Array ? values[i] : i; - if (name != null && name.constructor !== String) { - name = name.content === undefined ? String(name) : name.content; - } - var value = values[i]; - this.addItem(name, value, options); - num++; - } - - //close on leave? touch enabled devices won't work TODO use a global device detector and condition on that - /*LiteGraph.pointerListenerAdd(root,"leave", function(e) { - console.log("pointerevents: ContextMenu leave"); - if (that.lock) { - return; - } - if (root.closing_timer) { - clearTimeout(root.closing_timer); - } - root.closing_timer = setTimeout(that.close.bind(that, e), 500); - //that.close(e); - });*/ - - LiteGraph.pointerListenerAdd(root,"enter", function(e) { - //console.log("pointerevents: ContextMenu enter"); - if (root.closing_timer) { - clearTimeout(root.closing_timer); - } - }); - - //insert before checking position - var root_document = document; - if (options.event) { - root_document = options.event.target.ownerDocument; - } - - if (!root_document) { - root_document = document; - } - - if( root_document.fullscreenElement ) - root_document.fullscreenElement.appendChild(root); - else - root_document.body.appendChild(root); - - //compute best position - var left = options.left || 0; - var top = options.top || 0; - if (options.event) { - left = options.event.clientX - 10; - top = options.event.clientY - 10; - if (options.title) { - top -= 20; - } - - if (options.parentMenu) { - var rect = options.parentMenu.root.getBoundingClientRect(); - left = rect.left + rect.width; - } - - var body_rect = document.body.getBoundingClientRect(); - var root_rect = root.getBoundingClientRect(); - if(body_rect.height == 0) - console.error("document.body height is 0. That is dangerous, set html,body { height: 100%; }"); - - if (body_rect.width && left > body_rect.width - root_rect.width - 10) { - left = body_rect.width - root_rect.width - 10; - } - if (body_rect.height && top > body_rect.height - root_rect.height - 10) { - top = body_rect.height - root_rect.height - 10; - } - } - - root.style.left = left + "px"; - root.style.top = top + "px"; - - if (options.scale) { - root.style.transform = "scale(" + options.scale + ")"; - } - } - - ContextMenu.prototype.addItem = function(name, value, options) { - var that = this; - options = options || {}; - - var element = document.createElement("div"); - element.className = "litemenu-entry submenu"; - - var disabled = false; - - if (value === null) { - element.classList.add("separator"); - //element.innerHTML = "
" - //continue; - } else { - element.innerHTML = value && value.title ? value.title : name; - element.value = value; - - if (value) { - if (value.disabled) { - disabled = true; - element.classList.add("disabled"); - } - if (value.submenu || value.has_submenu) { - element.classList.add("has_submenu"); - } - } - - if (typeof value == "function") { - element.dataset["value"] = name; - element.onclick_callback = value; - } else { - element.dataset["value"] = value; - } - - if (value.className) { - element.className += " " + value.className; - } - } - - this.root.appendChild(element); - if (!disabled) { - element.addEventListener("click", inner_onclick); - } - if (options.autoopen) { - LiteGraph.pointerListenerAdd(element,"enter",inner_over); - } - - function inner_over(e) { - var value = this.value; - if (!value || !value.has_submenu) { - return; - } - //if it is a submenu, autoopen like the item was clicked - inner_onclick.call(this, e); - } - - //menu option clicked - function inner_onclick(e) { - var value = this.value; - var close_parent = true; - - if (that.current_submenu) { - that.current_submenu.close(e); - } - - //global callback - if (options.callback) { - var r = options.callback.call( - this, - value, - options, - e, - that, - options.node - ); - if (r === true) { - close_parent = false; - } - } - - //special cases - if (value) { - if ( - value.callback && - !options.ignore_item_callbacks && - value.disabled !== true - ) { - //item callback - var r = value.callback.call( - this, - value, - options, - e, - that, - options.extra - ); - if (r === true) { - close_parent = false; - } - } - if (value.submenu) { - if (!value.submenu.options) { - throw "ContextMenu submenu needs options"; - } - var submenu = new that.constructor(value.submenu.options, { - callback: value.submenu.callback, - event: e, - parentMenu: that, - ignore_item_callbacks: - value.submenu.ignore_item_callbacks, - title: value.submenu.title, - extra: value.submenu.extra, - autoopen: options.autoopen - }); - close_parent = false; - } - } - - if (close_parent && !that.lock) { - that.close(); - } - } - - return element; - }; - - ContextMenu.prototype.close = function(e, ignore_parent_menu) { - if (this.root.parentNode) { - this.root.parentNode.removeChild(this.root); - } - if (this.parentMenu && !ignore_parent_menu) { - this.parentMenu.lock = false; - this.parentMenu.current_submenu = null; - if (e === undefined) { - this.parentMenu.close(); - } else if ( - e && - !ContextMenu.isCursorOverElement(e, this.parentMenu.root) - ) { - ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method+"leave", e); - } - } - if (this.current_submenu) { - this.current_submenu.close(e, true); - } - - if (this.root.closing_timer) { - clearTimeout(this.root.closing_timer); - } - - // TODO implement : LiteGraph.contextMenuClosed(); :: keep track of opened / closed / current ContextMenu - // on key press, allow filtering/selecting the context menu elements - }; - - //this code is used to trigger events easily (used in the context menu mouseleave - ContextMenu.trigger = function(element, event_name, params, origin) { - var evt = document.createEvent("CustomEvent"); - evt.initCustomEvent(event_name, true, true, params); //canBubble, cancelable, detail - evt.srcElement = origin; - if (element.dispatchEvent) { - element.dispatchEvent(evt); - } else if (element.__events) { - element.__events.dispatchEvent(evt); - } - //else nothing seems binded here so nothing to do - return evt; - }; - - //returns the top most menu - ContextMenu.prototype.getTopMenu = function() { - if (this.options.parentMenu) { - return this.options.parentMenu.getTopMenu(); - } - return this; - }; - - ContextMenu.prototype.getFirstEvent = function() { - if (this.options.parentMenu) { - return this.options.parentMenu.getFirstEvent(); - } - return this.options.event; - }; - - ContextMenu.isCursorOverElement = function(event, element) { - var left = event.clientX; - var top = event.clientY; - var rect = element.getBoundingClientRect(); - if (!rect) { - return false; - } - if ( - top > rect.top && - top < rect.top + rect.height && - left > rect.left && - left < rect.left + rect.width - ) { - return true; - } - return false; - }; - - LiteGraph.ContextMenu = ContextMenu; - - LiteGraph.closeAllContextMenus = function(ref_window) { - ref_window = ref_window || window; - - var elements = ref_window.document.querySelectorAll(".litecontextmenu"); - if (!elements.length) { - return; - } - - var result = []; - for (var i = 0; i < elements.length; i++) { - result.push(elements[i]); - } - - for (var i=0; i < result.length; i++) { - if (result[i].close) { - result[i].close(); - } else if (result[i].parentNode) { - result[i].parentNode.removeChild(result[i]); - } - } - }; - - LiteGraph.extendClass = function(target, origin) { - for (var i in origin) { - //copy class properties - if (target.hasOwnProperty(i)) { - continue; - } - target[i] = origin[i]; - } - - if (origin.prototype) { - //copy prototype properties - for (var i in origin.prototype) { - //only enumerable - if (!origin.prototype.hasOwnProperty(i)) { - continue; - } - - if (target.prototype.hasOwnProperty(i)) { - //avoid overwriting existing ones - continue; - } - - //copy getters - if (origin.prototype.__lookupGetter__(i)) { - target.prototype.__defineGetter__( - i, - origin.prototype.__lookupGetter__(i) - ); - } else { - target.prototype[i] = origin.prototype[i]; - } - - //and setters - if (origin.prototype.__lookupSetter__(i)) { - target.prototype.__defineSetter__( - i, - origin.prototype.__lookupSetter__(i) - ); - } - } - } - }; - - //used by some widgets to render a curve editor - function CurveEditor( points ) - { - this.points = points; - this.selected = -1; - this.nearest = -1; - this.size = null; //stores last size used - this.must_update = true; - this.margin = 5; - } - - CurveEditor.sampleCurve = function(f,points) - { - if(!points) - return; - for(var i = 0; i < points.length - 1; ++i) - { - var p = points[i]; - var pn = points[i+1]; - if(pn[0] < f) - continue; - var r = (pn[0] - p[0]); - if( Math.abs(r) < 0.00001 ) - return p[1]; - var local_f = (f - p[0]) / r; - return p[1] * (1.0 - local_f) + pn[1] * local_f; - } - return 0; - } - - CurveEditor.prototype.draw = function( ctx, size, graphcanvas, background_color, line_color, inactive ) - { - var points = this.points; - if(!points) - return; - this.size = size; - var w = size[0] - this.margin * 2; - var h = size[1] - this.margin * 2; - - line_color = line_color || "#666"; - - ctx.save(); - ctx.translate(this.margin,this.margin); - - if(background_color) - { - ctx.fillStyle = "#111"; - ctx.fillRect(0,0,w,h); - ctx.fillStyle = "#222"; - ctx.fillRect(w*0.5,0,1,h); - ctx.strokeStyle = "#333"; - ctx.strokeRect(0,0,w,h); - } - ctx.strokeStyle = line_color; - if(inactive) - ctx.globalAlpha = 0.5; - ctx.beginPath(); - for(var i = 0; i < points.length; ++i) - { - var p = points[i]; - ctx.lineTo( p[0] * w, (1.0 - p[1]) * h ); - } - ctx.stroke(); - ctx.globalAlpha = 1; - if(!inactive) - for(var i = 0; i < points.length; ++i) - { - var p = points[i]; - ctx.fillStyle = this.selected == i ? "#FFF" : (this.nearest == i ? "#DDD" : "#AAA"); - ctx.beginPath(); - ctx.arc( p[0] * w, (1.0 - p[1]) * h, 2, 0, Math.PI * 2 ); - ctx.fill(); - } - ctx.restore(); - } - - //localpos is mouse in curve editor space - CurveEditor.prototype.onMouseDown = function( localpos, graphcanvas ) - { - var points = this.points; - if(!points) - return; - if( localpos[1] < 0 ) - return; - - //this.captureInput(true); - var w = this.size[0] - this.margin * 2; - var h = this.size[1] - this.margin * 2; - var x = localpos[0] - this.margin; - var y = localpos[1] - this.margin; - var pos = [x,y]; - var max_dist = 30 / graphcanvas.ds.scale; - //search closer one - this.selected = this.getCloserPoint(pos, max_dist); - //create one - if(this.selected == -1) - { - var point = [x / w, 1 - y / h]; - points.push(point); - points.sort(function(a,b){ return a[0] - b[0]; }); - this.selected = points.indexOf(point); - this.must_update = true; - } - if(this.selected != -1) - return true; - } - - CurveEditor.prototype.onMouseMove = function( localpos, graphcanvas ) - { - var points = this.points; - if(!points) - return; - var s = this.selected; - if(s < 0) - return; - var x = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2 ); - var y = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2 ); - var curvepos = [(localpos[0] - this.margin),(localpos[1] - this.margin)]; - var max_dist = 30 / graphcanvas.ds.scale; - this._nearest = this.getCloserPoint(curvepos, max_dist); - var point = points[s]; - if(point) - { - var is_edge_point = s == 0 || s == points.length - 1; - if( !is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10) ) - { - points.splice(s,1); - this.selected = -1; - return; - } - if( !is_edge_point ) //not edges - point[0] = Math.clamp(x,0,1); - else - point[0] = s == 0 ? 0 : 1; - point[1] = 1.0 - Math.clamp(y,0,1); - points.sort(function(a,b){ return a[0] - b[0]; }); - this.selected = points.indexOf(point); - this.must_update = true; - } - } - - CurveEditor.prototype.onMouseUp = function( localpos, graphcanvas ) - { - this.selected = -1; - return false; - } - - CurveEditor.prototype.getCloserPoint = function(pos, max_dist) - { - var points = this.points; - if(!points) - return -1; - max_dist = max_dist || 30; - var w = (this.size[0] - this.margin * 2); - var h = (this.size[1] - this.margin * 2); - var num = points.length; - var p2 = [0,0]; - var min_dist = 1000000; - var closest = -1; - var last_valid = -1; - for(var i = 0; i < num; ++i) - { - var p = points[i]; - p2[0] = p[0] * w; - p2[1] = (1.0 - p[1]) * h; - if(p2[0] < pos[0]) - last_valid = i; - var dist = vec2.distance(pos,p2); - if(dist > min_dist || dist > max_dist) - continue; - closest = i; - min_dist = dist; - } - return closest; - } - - LiteGraph.CurveEditor = CurveEditor; - - //used to create nodes from wrapping functions - LiteGraph.getParameterNames = function(func) { - return (func + "") - .replace(/[/][/].*$/gm, "") // strip single-line comments - .replace(/\s+/g, "") // strip white space - .replace(/[/][*][^/*]*[*][/]/g, "") // strip multi-line comments /**/ - .split("){", 1)[0] - .replace(/^[^(]*[(]/, "") // extract the parameters - .replace(/=[^,]+/g, "") // strip any ES6 defaults - .split(",") - .filter(Boolean); // split & filter [""] - }; - - /* helper for interaction: pointer, touch, mouse Listeners - used by LGraphCanvas DragAndScale ContextMenu*/ - LiteGraph.pointerListenerAdd = function(oDOM, sEvIn, fCall, capture=false) { - if (!oDOM || !oDOM.addEventListener || !sEvIn || typeof fCall!=="function"){ - //console.log("cant pointerListenerAdd "+oDOM+", "+sEvent+", "+fCall); - return; // -- break -- - } - - var sMethod = LiteGraph.pointerevents_method; - var sEvent = sEvIn; - - // UNDER CONSTRUCTION - // convert pointerevents to touch event when not available - if (sMethod=="pointer" && !window.PointerEvent){ - console.warn("sMethod=='pointer' && !window.PointerEvent"); - console.log("Converting pointer["+sEvent+"] : down move up cancel enter TO touchstart touchmove touchend, etc .."); - switch(sEvent){ - case "down":{ - sMethod = "touch"; - sEvent = "start"; - break; - } - case "move":{ - sMethod = "touch"; - //sEvent = "move"; - break; - } - case "up":{ - sMethod = "touch"; - sEvent = "end"; - break; - } - case "cancel":{ - sMethod = "touch"; - //sEvent = "cancel"; - break; - } - case "enter":{ - console.log("debug: Should I send a move event?"); // ??? - break; - } - // case "over": case "out": not used at now - default:{ - console.warn("PointerEvent not available in this browser ? The event "+sEvent+" would not be called"); - } - } - } - - switch(sEvent){ - //both pointer and move events - case "down": case "up": case "move": case "over": case "out": case "enter": - { - oDOM.addEventListener(sMethod+sEvent, fCall, capture); - } - // only pointerevents - case "leave": case "cancel": case "gotpointercapture": case "lostpointercapture": - { - if (sMethod!="mouse"){ - return oDOM.addEventListener(sMethod+sEvent, fCall, capture); - } - } - // not "pointer" || "mouse" - default: - return oDOM.addEventListener(sEvent, fCall, capture); - } - } - LiteGraph.pointerListenerRemove = function(oDOM, sEvent, fCall, capture=false) { - if (!oDOM || !oDOM.removeEventListener || !sEvent || typeof fCall!=="function"){ - //console.log("cant pointerListenerRemove "+oDOM+", "+sEvent+", "+fCall); - return; // -- break -- - } - switch(sEvent){ - //both pointer and move events - case "down": case "up": case "move": case "over": case "out": case "enter": - { - if (LiteGraph.pointerevents_method=="pointer" || LiteGraph.pointerevents_method=="mouse"){ - oDOM.removeEventListener(LiteGraph.pointerevents_method+sEvent, fCall, capture); - } - } - // only pointerevents - case "leave": case "cancel": case "gotpointercapture": case "lostpointercapture": - { - if (LiteGraph.pointerevents_method=="pointer"){ - return oDOM.removeEventListener(LiteGraph.pointerevents_method+sEvent, fCall, capture); - } - } - // not "pointer" || "mouse" - default: - return oDOM.removeEventListener(sEvent, fCall, capture); - } - } - - Math.clamp = function(v, a, b) { - return a > v ? a : b < v ? b : v; - }; - - if (typeof window != "undefined" && !window["requestAnimationFrame"]) { - window.requestAnimationFrame = - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - function(callback) { - window.setTimeout(callback, 1000 / 60); - }; - } -})(this); - -if (typeof exports != "undefined") { - exports.LiteGraph = this.LiteGraph; -} - - diff --git a/examples/editing/litegraph.js/css/litegraph.css b/examples/editing/litegraph.js/css/litegraph.css deleted file mode 100644 index 918858f4..00000000 --- a/examples/editing/litegraph.js/css/litegraph.css +++ /dev/null @@ -1,680 +0,0 @@ -/* this CSS contains only the basic CSS needed to run the app and use it */ - -.lgraphcanvas { - /*cursor: crosshair;*/ - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - outline: none; - font-family: Tahoma, sans-serif; -} - -.lgraphcanvas * { - box-sizing: border-box; -} - -.litegraph.litecontextmenu { - font-family: Tahoma, sans-serif; - position: fixed; - top: 100px; - left: 100px; - min-width: 100px; - color: #aaf; - padding: 0; - box-shadow: 0 0 10px black !important; - background-color: #2e2e2e !important; - z-index: 10; -} - -.litegraph.litecontextmenu.dark { - background-color: #000 !important; -} - -.litegraph.litecontextmenu .litemenu-title img { - margin-top: 2px; - margin-left: 2px; - margin-right: 4px; -} - -.litegraph.litecontextmenu .litemenu-entry { - margin: 2px; - padding: 2px; -} - -.litegraph.litecontextmenu .litemenu-entry.submenu { - background-color: #2e2e2e !important; -} - -.litegraph.litecontextmenu.dark .litemenu-entry.submenu { - background-color: #000 !important; -} - -.litegraph .litemenubar ul { - font-family: Tahoma, sans-serif; - margin: 0; - padding: 0; -} - -.litegraph .litemenubar li { - font-size: 14px; - color: #999; - display: inline-block; - min-width: 50px; - padding-left: 10px; - padding-right: 10px; - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - cursor: pointer; -} - -.litegraph .litemenubar li:hover { - background-color: #777; - color: #eee; -} - -.litegraph .litegraph .litemenubar-panel { - position: absolute; - top: 5px; - left: 5px; - min-width: 100px; - background-color: #444; - box-shadow: 0 0 3px black; - padding: 4px; - border-bottom: 2px solid #aaf; - z-index: 10; -} - -.litegraph .litemenu-entry, -.litemenu-title { - font-size: 12px; - color: #aaa; - padding: 0 0 0 4px; - margin: 2px; - padding-left: 2px; - -moz-user-select: none; - -webkit-user-select: none; - user-select: none; - cursor: pointer; -} - -.litegraph .litemenu-entry .icon { - display: inline-block; - width: 12px; - height: 12px; - margin: 2px; - vertical-align: top; -} - -.litegraph .litemenu-entry.checked .icon { - background-color: #aaf; -} - -.litegraph .litemenu-entry .more { - float: right; - padding-right: 5px; -} - -.litegraph .litemenu-entry.disabled { - opacity: 0.5; - cursor: default; -} - -.litegraph .litemenu-entry.separator { - display: block; - border-top: 1px solid #333; - border-bottom: 1px solid #666; - width: 100%; - height: 0px; - margin: 3px 0 2px 0; - background-color: transparent; - padding: 0 !important; - cursor: default !important; -} - -.litegraph .litemenu-entry.has_submenu { - border-right: 2px solid cyan; -} - -.litegraph .litemenu-title { - color: #dde; - background-color: #111; - margin: 0; - padding: 2px; - cursor: default; -} - -.litegraph .litemenu-entry:hover:not(.disabled):not(.separator) { - background-color: #444 !important; - color: #eee; - transition: all 0.2s; -} - -.litegraph .litemenu-entry .property_name { - display: inline-block; - text-align: left; - min-width: 80px; - min-height: 1.2em; -} - -.litegraph .litemenu-entry .property_value { - display: inline-block; - background-color: rgba(0, 0, 0, 0.5); - text-align: right; - min-width: 80px; - min-height: 1.2em; - vertical-align: middle; - padding-right: 10px; -} - -.litegraph.litesearchbox { - font-family: Tahoma, sans-serif; - position: absolute; - background-color: rgba(0, 0, 0, 0.5); - padding-top: 4px; -} - -.litegraph.litesearchbox input, -.litegraph.litesearchbox select { - margin-top: 3px; - min-width: 60px; - min-height: 1.5em; - background-color: black; - border: 0; - color: white; - padding-left: 10px; - margin-right: 5px; -} - -.litegraph.litesearchbox .name { - display: inline-block; - min-width: 60px; - min-height: 1.5em; - padding-left: 10px; -} - -.litegraph.litesearchbox .helper { - overflow: auto; - max-height: 200px; - margin-top: 2px; -} - -.litegraph.lite-search-item { - font-family: Tahoma, sans-serif; - background-color: rgba(0, 0, 0, 0.5); - color: white; - padding-top: 2px; -} - -.litegraph.lite-search-item.not_in_filter{ - /*background-color: rgba(50, 50, 50, 0.5);*/ - /*color: #999;*/ - color: #B99; - font-style: italic; -} - -.litegraph.lite-search-item.generic_type{ - /*background-color: rgba(50, 50, 50, 0.5);*/ - /*color: #DD9;*/ - color: #999; - font-style: italic; -} - -.litegraph.lite-search-item:hover, -.litegraph.lite-search-item.selected { - cursor: pointer; - background-color: white; - color: black; -} - -/* DIALOGs ******/ - -.litegraph .dialog { - position: absolute; - top: 50%; - left: 50%; - margin-top: -150px; - margin-left: -200px; - - background-color: #2A2A2A; - - min-width: 400px; - min-height: 200px; - box-shadow: 0 0 4px #111; - border-radius: 6px; -} - -.litegraph .dialog.settings { - left: 10px; - top: 10px; - height: calc( 100% - 20px ); - margin: auto; - max-width: 50%; -} - -.litegraph .dialog.centered { - top: 50px; - left: 50%; - position: absolute; - transform: translateX(-50%); - min-width: 600px; - min-height: 300px; - height: calc( 100% - 100px ); - margin: auto; -} - -.litegraph .dialog .close { - float: right; - margin: 4px; - margin-right: 10px; - cursor: pointer; - font-size: 1.4em; -} - -.litegraph .dialog .close:hover { - color: white; -} - -.litegraph .dialog .dialog-header { - color: #AAA; - border-bottom: 1px solid #161616; -} - -.litegraph .dialog .dialog-header { height: 40px; } -.litegraph .dialog .dialog-footer { height: 50px; padding: 10px; border-top: 1px solid #1a1a1a;} - -.litegraph .dialog .dialog-header .dialog-title { - font: 20px "Arial"; - margin: 4px; - padding: 4px 10px; - display: inline-block; -} - -.litegraph .dialog .dialog-content, .litegraph .dialog .dialog-alt-content { - height: calc(100% - 90px); - width: 100%; - min-height: 100px; - display: inline-block; - color: #AAA; - /*background-color: black;*/ - overflow: auto; -} - -.litegraph .dialog .dialog-content h3 { - margin: 10px; -} - -.litegraph .dialog .dialog-content .connections { - flex-direction: row; -} - -.litegraph .dialog .dialog-content .connections .connections_side { - width: calc(50% - 5px); - min-height: 100px; - background-color: black; - display: flex; -} - -.litegraph .dialog .node_type { - font-size: 1.2em; - display: block; - margin: 10px; -} - -.litegraph .dialog .node_desc { - opacity: 0.5; - display: block; - margin: 10px; -} - -.litegraph .dialog .separator { - display: block; - width: calc( 100% - 4px ); - height: 1px; - border-top: 1px solid #000; - border-bottom: 1px solid #333; - margin: 10px 2px; - padding: 0; -} - -.litegraph .dialog .property { - margin-bottom: 2px; - padding: 4px; -} - -.litegraph .dialog .property:hover { - background: #545454; -} - -.litegraph .dialog .property_name { - color: #737373; - display: inline-block; - text-align: left; - vertical-align: top; - width: 160px; - padding-left: 4px; - overflow: hidden; - margin-right: 6px; -} - -.litegraph .dialog .property:hover .property_name { - color: white; -} - -.litegraph .dialog .property_value { - display: inline-block; - text-align: right; - color: #AAA; - background-color: #1A1A1A; - /*width: calc( 100% - 122px );*/ - max-width: calc( 100% - 162px ); - min-width: 200px; - max-height: 300px; - min-height: 20px; - padding: 4px; - padding-right: 12px; - overflow: hidden; - cursor: pointer; - border-radius: 3px; -} - -.litegraph .dialog .property_value:hover { - color: white; -} - -.litegraph .dialog .property.boolean .property_value { - padding-right: 30px; - color: #A88; - /*width: auto; - float: right;*/ -} - -.litegraph .dialog .property.boolean.bool-on .property_name{ - color: #8A8; -} -.litegraph .dialog .property.boolean.bool-on .property_value{ - color: #8A8; -} - -.litegraph .dialog .btn { - border: 0; - border-radius: 4px; - padding: 4px 20px; - margin-left: 0px; - background-color: #060606; - color: #8e8e8e; -} - -.litegraph .dialog .btn:hover { - background-color: #111; - color: #FFF; -} - -.litegraph .dialog .btn.delete:hover { - background-color: #F33; - color: black; -} - -.litegraph .subgraph_property { - padding: 4px; -} - -.litegraph .subgraph_property:hover { - background-color: #333; -} - -.litegraph .subgraph_property.extra { - margin-top: 8px; -} - -.litegraph .subgraph_property span.name { - font-size: 1.3em; - padding-left: 4px; -} - -.litegraph .subgraph_property span.type { - opacity: 0.5; - margin-right: 20px; - padding-left: 4px; -} - -.litegraph .subgraph_property span.label { - display: inline-block; - width: 60px; - padding: 0px 10px; -} - -.litegraph .subgraph_property input { - width: 140px; - color: #999; - background-color: #1A1A1A; - border-radius: 4px; - border: 0; - margin-right: 10px; - padding: 4px; - padding-left: 10px; -} - -.litegraph .subgraph_property button { - background-color: #1c1c1c; - color: #aaa; - border: 0; - border-radius: 2px; - padding: 4px 10px; - cursor: pointer; -} - -.litegraph .subgraph_property.extra { - color: #ccc; -} - -.litegraph .subgraph_property.extra input { - background-color: #111; -} - -.litegraph .bullet_icon { - margin-left: 10px; - border-radius: 10px; - width: 12px; - height: 12px; - background-color: #666; - display: inline-block; - margin-top: 2px; - margin-right: 4px; - transition: background-color 0.1s ease 0s; - -moz-transition: background-color 0.1s ease 0s; -} - -.litegraph .bullet_icon:hover { - background-color: #698; - cursor: pointer; -} - -/* OLD */ - -.graphcontextmenu { - padding: 4px; - min-width: 100px; -} - -.graphcontextmenu-title { - color: #dde; - background-color: #222; - margin: 0; - padding: 2px; - cursor: default; -} - -.graphmenu-entry { - box-sizing: border-box; - margin: 2px; - padding-left: 20px; - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - transition: all linear 0.3s; -} - -.graphmenu-entry.event, -.litemenu-entry.event { - border-left: 8px solid orange; - padding-left: 12px; -} - -.graphmenu-entry.disabled { - opacity: 0.3; -} - -.graphmenu-entry.submenu { - border-right: 2px solid #eee; -} - -.graphmenu-entry:hover { - background-color: #555; -} - -.graphmenu-entry.separator { - background-color: #111; - border-bottom: 1px solid #666; - height: 1px; - width: calc(100% - 20px); - -moz-width: calc(100% - 20px); - -webkit-width: calc(100% - 20px); -} - -.graphmenu-entry .property_name { - display: inline-block; - text-align: left; - min-width: 80px; - min-height: 1.2em; -} - -.graphmenu-entry .property_value, -.litemenu-entry .property_value { - display: inline-block; - background-color: rgba(0, 0, 0, 0.5); - text-align: right; - min-width: 80px; - min-height: 1.2em; - vertical-align: middle; - padding-right: 10px; -} - -.graphdialog { - position: absolute; - top: 10px; - left: 10px; - min-height: 2em; - background-color: #333; - font-size: 1.2em; - box-shadow: 0 0 10px black !important; - z-index: 10; -} - -.graphdialog.rounded { - border-radius: 12px; - padding-right: 2px; -} - -.graphdialog .name { - display: inline-block; - min-width: 60px; - min-height: 1.5em; - padding-left: 10px; -} - -.graphdialog input, -.graphdialog textarea, -.graphdialog select { - margin: 3px; - min-width: 60px; - min-height: 1.5em; - background-color: black; - border: 0; - color: white; - padding-left: 10px; - outline: none; -} - -.graphdialog textarea { - min-height: 150px; -} - -.graphdialog button { - margin-top: 3px; - vertical-align: top; - background-color: #999; - border: 0; -} - -.graphdialog button.rounded, -.graphdialog input.rounded { - border-radius: 0 12px 12px 0; -} - -.graphdialog .helper { - overflow: auto; - max-height: 200px; -} - -.graphdialog .help-item { - padding-left: 10px; -} - -.graphdialog .help-item:hover, -.graphdialog .help-item.selected { - cursor: pointer; - background-color: white; - color: black; -} - -.litegraph .dialog { - min-height: 0; -} -.litegraph .dialog .dialog-content { -display: block; -} -.litegraph .dialog .dialog-content .subgraph_property { -padding: 5px; -} -.litegraph .dialog .dialog-footer { -margin: 0; -} -.litegraph .dialog .dialog-footer .subgraph_property { -margin-top: 0; -display: flex; -align-items: center; -padding: 5px; -} -.litegraph .dialog .dialog-footer .subgraph_property .name { -flex: 1; -} -.litegraph .graphdialog { -display: flex; -align-items: center; -border-radius: 20px; -padding: 4px 10px; -position: fixed; -} -.litegraph .graphdialog .name { -padding: 0; -min-height: 0; -font-size: 16px; -vertical-align: middle; -} -.litegraph .graphdialog .value { -font-size: 16px; -min-height: 0; -margin: 0 10px; -padding: 2px 5px; -} -.litegraph .graphdialog input[type="checkbox"] { -width: 16px; -height: 16px; -} -.litegraph .graphdialog button { -padding: 4px 18px; -border-radius: 20px; -cursor: pointer; -} - diff --git a/examples/editing/litegraph.js/package.json b/examples/editing/litegraph.js/package.json deleted file mode 100644 index 6a298d6a..00000000 --- a/examples/editing/litegraph.js/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "litegraph.js", - "version": "0.7.14", - "description": "A graph node editor similar to PD or UDK Blueprints. It works in an HTML5 Canvas and allows to export graphs to be included in applications.", - "main": "build/litegraph.core.js", - "types": "src/litegraph.d.ts", - "directories": { - "doc": "doc" - }, - "private": false, - "scripts": { - "prebuild": "rimraf build", - "build": "grunt build", - "start": "nodemon utils/server.js", - "test": "jest", - "test:allVersions": "./utils/test.sh", - "prettier": "npx prettier --write src/**/*.* css/**/*.*", - "lint": "npx eslint src", - "lint:fix": "npx eslint --fix src" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/jagenjo/litegraph.js.git" - }, - "author": "jagenjo", - "license": "MIT", - "files": [ - "build", - "css/litegraph.css", - "src/litegraph.d.ts" - ], - "bugs": { - "url": "https://github.com/jagenjo/litegraph.js/issues" - }, - "homepage": "https://github.com/jagenjo/litegraph.js#readme", - "devDependencies": { - "@types/jest": "^28.1.3", - "eslint": "^8.37.0 ", - "eslint-plugin-jest": "^27.2.1", - "express": "^4.17.1", - "google-closure-compiler": "^20171112.0.0", - "grunt": "^1.1.0", - "grunt-cli": "^1.2.0", - "grunt-closure-tools": "^1.0.0", - "grunt-contrib-concat": "^1.0.1", - "jest": "^28.1.3", - "nodemon": "^1.19.4", - "rimraf": "^2.7.1" - } -} diff --git a/examples/editing/litegraph.js/src/litegraph.d.ts b/examples/editing/litegraph.js/src/litegraph.d.ts deleted file mode 100644 index 6629e779..00000000 --- a/examples/editing/litegraph.js/src/litegraph.d.ts +++ /dev/null @@ -1,1506 +0,0 @@ -// Type definitions for litegraph.js 0.7.0 -// Project: litegraph.js -// Definitions by: NateScarlet - -export type Vector2 = [number, number]; -export type Vector4 = [number, number, number, number]; -export type widgetTypes = - | "number" - | "slider" - | "combo" - | "text" - | "toggle" - | "button"; -export type SlotShape = - | typeof LiteGraph.BOX_SHAPE - | typeof LiteGraph.CIRCLE_SHAPE - | typeof LiteGraph.ARROW_SHAPE - | typeof LiteGraph.SQUARE_SHAPE - | number; // For custom shapes - -/** https://github.com/jagenjo/litegraph.js/tree/master/guides#node-slots */ -export interface INodeSlot { - name: string; - type: string | -1; - label?: string; - dir?: - | typeof LiteGraph.UP - | typeof LiteGraph.RIGHT - | typeof LiteGraph.DOWN - | typeof LiteGraph.LEFT; - color_on?: string; - color_off?: string; - shape?: SlotShape; - locked?: boolean; - nameLocked?: boolean; -} - -export interface INodeInputSlot extends INodeSlot { - link: LLink["id"] | null; -} -export interface INodeOutputSlot extends INodeSlot { - links: LLink["id"][] | null; -} - -export type WidgetCallback = ( - this: T, - value: T["value"], - graphCanvas: LGraphCanvas, - node: LGraphNode, - pos: Vector2, - event?: MouseEvent -) => void; - -export interface IWidget { - name: string | null; - value: TValue; - options?: TOptions; - type?: widgetTypes; - y?: number; - property?: string; - last_y?: number; - clicked?: boolean; - marker?: boolean; - callback?: WidgetCallback; - /** Called by `LGraphCanvas.drawNodeWidgets` */ - draw?( - ctx: CanvasRenderingContext2D, - node: LGraphNode, - width: number, - posY: number, - height: number - ): void; - /** - * Called by `LGraphCanvas.processNodeWidgets` - * https://github.com/jagenjo/litegraph.js/issues/76 - */ - mouse?( - event: MouseEvent, - pos: Vector2, - node: LGraphNode - ): boolean; - /** Called by `LGraphNode.computeSize` */ - computeSize?(width: number): [number, number]; -} -export interface IButtonWidget extends IWidget { - type: "button"; -} -export interface IToggleWidget - extends IWidget { - type: "toggle"; -} -export interface ISliderWidget - extends IWidget { - type: "slider"; -} -export interface INumberWidget extends IWidget { - type: "number"; -} -export interface IComboWidget - extends IWidget< - string[], - { - values: - | string[] - | ((widget: IComboWidget, node: LGraphNode) => string[]); - } - > { - type: "combo"; -} - -export interface ITextWidget extends IWidget { - type: "text"; -} - -export interface IContextMenuItem { - content: string; - callback?: ContextMenuEventListener; - /** Used as innerHTML for extra child element */ - title?: string; - disabled?: boolean; - has_submenu?: boolean; - submenu?: { - options: ContextMenuItem[]; - } & IContextMenuOptions; - className?: string; -} -export interface IContextMenuOptions { - callback?: ContextMenuEventListener; - ignore_item_callbacks?: Boolean; - event?: MouseEvent | CustomEvent; - parentMenu?: ContextMenu; - autoopen?: boolean; - title?: string; - extra?: any; -} - -export type ContextMenuItem = IContextMenuItem | null; -export type ContextMenuEventListener = ( - value: ContextMenuItem, - options: IContextMenuOptions, - event: MouseEvent, - parentMenu: ContextMenu | undefined, - node: LGraphNode -) => boolean | void; - -export const LiteGraph: { - VERSION: number; - - CANVAS_GRID_SIZE: number; - - NODE_TITLE_HEIGHT: number; - NODE_TITLE_TEXT_Y: number; - NODE_SLOT_HEIGHT: number; - NODE_WIDGET_HEIGHT: number; - NODE_WIDTH: number; - NODE_MIN_WIDTH: number; - NODE_COLLAPSED_RADIUS: number; - NODE_COLLAPSED_WIDTH: number; - NODE_TITLE_COLOR: string; - NODE_TEXT_SIZE: number; - NODE_TEXT_COLOR: string; - NODE_SUBTEXT_SIZE: number; - NODE_DEFAULT_COLOR: string; - NODE_DEFAULT_BGCOLOR: string; - NODE_DEFAULT_BOXCOLOR: string; - NODE_DEFAULT_SHAPE: string; - DEFAULT_SHADOW_COLOR: string; - DEFAULT_GROUP_FONT: number; - - LINK_COLOR: string; - EVENT_LINK_COLOR: string; - CONNECTING_LINK_COLOR: string; - - MAX_NUMBER_OF_NODES: number; //avoid infinite loops - DEFAULT_POSITION: Vector2; //default node position - VALID_SHAPES: ["default", "box", "round", "card"]; //,"circle" - - //shapes are used for nodes but also for slots - BOX_SHAPE: 1; - ROUND_SHAPE: 2; - CIRCLE_SHAPE: 3; - CARD_SHAPE: 4; - ARROW_SHAPE: 5; - SQUARE_SHAPE: 6; - - //enums - INPUT: 1; - OUTPUT: 2; - - EVENT: -1; //for outputs - ACTION: -1; //for inputs - - ALWAYS: 0; - ON_EVENT: 1; - NEVER: 2; - ON_TRIGGER: 3; - - UP: 1; - DOWN: 2; - LEFT: 3; - RIGHT: 4; - CENTER: 5; - - STRAIGHT_LINK: 0; - LINEAR_LINK: 1; - SPLINE_LINK: 2; - - NORMAL_TITLE: 0; - NO_TITLE: 1; - TRANSPARENT_TITLE: 2; - AUTOHIDE_TITLE: 3; - - node_images_path: string; - - debug: boolean; - catch_exceptions: boolean; - throw_errors: boolean; - /** if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits */ - allow_scripts: boolean; - /** node types by string */ - registered_node_types: Record; - /** used for dropping files in the canvas */ - node_types_by_file_extension: Record; - /** node types by class name */ - Nodes: Record; - - /** used to add extra features to the search box */ - searchbox_extras: Record< - string, - { - data: { outputs: string[][]; title: string }; - desc: string; - type: string; - } - >; - - createNode(type: string): T; - /** Register a node class so it can be listed when the user wants to create a new one */ - registerNodeType(type: string, base: { new (): LGraphNode }): void; - /** removes a node type from the system */ - unregisterNodeType(type: string): void; - /** Removes all previously registered node's types. */ - clearRegisteredTypes(): void; - /** - * Create a new node type by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function. - * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output. - * @param name node name with namespace (p.e.: 'math/sum') - * @param func - * @param param_types an array containing the type of every parameter, otherwise parameters will accept any type - * @param return_type string with the return type, otherwise it will be generic - * @param properties properties to be configurable - */ - wrapFunctionAsNode( - name: string, - func: (...args: any[]) => any, - param_types?: string[], - return_type?: string, - properties?: object - ): void; - - /** - * Adds this method to all node types, existing and to be created - * (You can add it to LGraphNode.prototype but then existing node types wont have it) - */ - addNodeMethod(name: string, func: (...args: any[]) => any): void; - - /** - * Create a node of a given type with a name. The node is not attached to any graph yet. - * @param type full name of the node class. p.e. "math/sin" - * @param name a name to distinguish from other nodes - * @param options to set options - */ - createNode( - type: string, - title: string, - options: object - ): T; - - /** - * Returns a registered node type with a given name - * @param type full name of the node class. p.e. "math/sin" - */ - getNodeType(type: string): LGraphNodeConstructor; - - /** - * Returns a list of node types matching one category - * @method getNodeTypesInCategory - * @param {String} category category name - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the node classes - */ - getNodeTypesInCategory( - category: string, - filter: string - ): LGraphNodeConstructor[]; - - /** - * Returns a list with all the node type categories - * @method getNodeTypesCategories - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the names of the categories - */ - getNodeTypesCategories(filter: string): string[]; - - /** debug purposes: reloads all the js scripts that matches a wildcard */ - reloadNodes(folder_wildcard: string): void; - - getTime(): number; - LLink: typeof LLink; - LGraph: typeof LGraph; - DragAndScale: typeof DragAndScale; - compareObjects(a: object, b: object): boolean; - distance(a: Vector2, b: Vector2): number; - colorToString(c: string): string; - isInsideRectangle( - x: number, - y: number, - left: number, - top: number, - width: number, - height: number - ): boolean; - growBounding(bounding: Vector4, x: number, y: number): Vector4; - isInsideBounding(p: Vector2, bb: Vector4): boolean; - hex2num(hex: string): [number, number, number]; - num2hex(triplet: [number, number, number]): string; - ContextMenu: typeof ContextMenu; - extendClass(target: A, origin: B): A & B; - getParameterNames(func: string): string[]; -}; - -export type serializedLGraph< - TNode = ReturnType, - // https://github.com/jagenjo/litegraph.js/issues/74 - TLink = [number, number, number, number, number, string], - TGroup = ReturnType -> = { - last_node_id: LGraph["last_node_id"]; - last_link_id: LGraph["last_link_id"]; - nodes: TNode[]; - links: TLink[]; - groups: TGroup[]; - config: LGraph["config"]; - version: typeof LiteGraph.VERSION; -}; - -export declare class LGraph { - static supported_types: string[]; - static STATUS_STOPPED: 1; - static STATUS_RUNNING: 2; - - constructor(o?: object); - - filter: string; - catch_errors: boolean; - /** custom data */ - config: object; - elapsed_time: number; - fixedtime: number; - fixedtime_lapse: number; - globaltime: number; - inputs: any; - iteration: number; - last_link_id: number; - last_node_id: number; - last_update_time: number; - links: Record; - list_of_graphcanvas: LGraphCanvas[]; - outputs: any; - runningtime: number; - starttime: number; - status: typeof LGraph.STATUS_RUNNING | typeof LGraph.STATUS_STOPPED; - - private _nodes: LGraphNode[]; - private _groups: LGraphGroup[]; - private _nodes_by_id: Record; - /** nodes that are executable sorted in execution order */ - private _nodes_executable: - | (LGraphNode & { onExecute: NonNullable }[]) - | null; - /** nodes that contain onExecute */ - private _nodes_in_order: LGraphNode[]; - private _version: number; - - getSupportedTypes(): string[]; - /** Removes all nodes from this graph */ - clear(): void; - /** Attach Canvas to this graph */ - attachCanvas(graphCanvas: LGraphCanvas): void; - /** Detach Canvas to this graph */ - detachCanvas(graphCanvas: LGraphCanvas): void; - /** - * Starts running this graph every interval milliseconds. - * @param interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate - */ - start(interval?: number): void; - /** Stops the execution loop of the graph */ - stop(): void; - /** - * Run N steps (cycles) of the graph - * @param num number of steps to run, default is 1 - */ - runStep(num?: number, do_not_catch_errors?: boolean): void; - /** - * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than - * nodes with only inputs. - */ - updateExecutionOrder(): void; - /** This is more internal, it computes the executable nodes in order and returns it */ - computeExecutionOrder(only_onExecute: boolean, set_level: any): T; - /** - * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively. - * It doesn't include the node itself - * @return an array with all the LGraphNodes that affect this node, in order of execution - */ - getAncestors(node: LGraphNode): LGraphNode[]; - /** - * Positions every node in a more readable manner - */ - arrange(margin?: number,layout?: string): void; - /** - * Returns the amount of time the graph has been running in milliseconds - * @return number of milliseconds the graph has been running - */ - getTime(): number; - - /** - * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant - * @return number of milliseconds the graph has been running - */ - getFixedTime(): number; - - /** - * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct - * if the nodes are using graphical actions - * @return number of milliseconds it took the last cycle - */ - getElapsedTime(): number; - /** - * Sends an event to all the nodes, useful to trigger stuff - * @param eventName the name of the event (function to be called) - * @param params parameters in array format - */ - sendEventToAllNodes(eventName: string, params: any[], mode?: any): void; - - sendActionToCanvas(action: any, params: any[]): void; - /** - * Adds a new node instance to this graph - * @param node the instance of the node - */ - add(node: LGraphNode, skip_compute_order?: boolean): void; - /** - * Called when a new node is added - * @param node the instance of the node - */ - onNodeAdded(node: LGraphNode): void; - /** Removes a node from the graph */ - remove(node: LGraphNode): void; - /** Returns a node by its id. */ - getNodeById(id: number): LGraphNode | undefined; - /** - * Returns a list of nodes that matches a class - * @param classObject the class itself (not an string) - * @return a list with all the nodes of this type - */ - findNodesByClass( - classObject: LGraphNodeConstructor - ): T[]; - /** - * Returns a list of nodes that matches a type - * @param type the name of the node type - * @return a list with all the nodes of this type - */ - findNodesByType(type: string): T[]; - /** - * Returns the first node that matches a name in its title - * @param title the name of the node to search - * @return the node or null - */ - findNodeByTitle(title: string): T | null; - /** - * Returns a list of nodes that matches a name - * @param title the name of the node to search - * @return a list with all the nodes with this name - */ - findNodesByTitle(title: string): T[]; - /** - * Returns the top-most node in this position of the canvas - * @param x the x coordinate in canvas space - * @param y the y coordinate in canvas space - * @param nodes_list a list with all the nodes to search from, by default is all the nodes in the graph - * @return the node at this position or null - */ - getNodeOnPos( - x: number, - y: number, - node_list?: LGraphNode[], - margin?: number - ): T | null; - /** - * Returns the top-most group in that position - * @param x the x coordinate in canvas space - * @param y the y coordinate in canvas space - * @return the group or null - */ - getGroupOnPos(x: number, y: number): LGraphGroup | null; - - onAction(action: any, param: any): void; - trigger(action: any, param: any): void; - /** Tell this graph it has a global graph input of this type */ - addInput(name: string, type: string, value?: any): void; - /** Assign a data to the global graph input */ - setInputData(name: string, data: any): void; - /** Returns the current value of a global graph input */ - getInputData(name: string): T; - /** Changes the name of a global graph input */ - renameInput(old_name: string, name: string): false | undefined; - /** Changes the type of a global graph input */ - changeInputType(name: string, type: string): false | undefined; - /** Removes a global graph input */ - removeInput(name: string): boolean; - /** Creates a global graph output */ - addOutput(name: string, type: string, value: any): void; - /** Assign a data to the global output */ - setOutputData(name: string, value: string): void; - /** Returns the current value of a global graph output */ - getOutputData(name: string): T; - - /** Renames a global graph output */ - renameOutput(old_name: string, name: string): false | undefined; - /** Changes the type of a global graph output */ - changeOutputType(name: string, type: string): false | undefined; - /** Removes a global graph output */ - removeOutput(name: string): boolean; - triggerInput(name: string, value: any): void; - setCallback(name: string, func: (...args: any[]) => any): void; - beforeChange(info?: LGraphNode): void; - afterChange(info?: LGraphNode): void; - connectionChange(node: LGraphNode): void; - /** returns if the graph is in live mode */ - isLive(): boolean; - /** clears the triggered slot animation in all links (stop visual animation) */ - clearTriggeredSlots(): void; - /* Called when something visually changed (not the graph!) */ - change(): void; - setDirtyCanvas(fg: boolean, bg: boolean): void; - /** Destroys a link */ - removeLink(link_id: number): void; - /** Creates a Object containing all the info about this graph, it can be serialized */ - serialize(): T; - /** - * Configure a graph from a JSON string - * @param data configure a graph from a JSON string - * @returns if there was any error parsing - */ - configure(data: object, keep_old?: boolean): boolean | undefined; - load(url: string): void; -} - -export type SerializedLLink = [number, string, number, number, number, number]; -export declare class LLink { - id: number; - type: string; - origin_id: number; - origin_slot: number; - target_id: number; - target_slot: number; - constructor( - id: number, - type: string, - origin_id: number, - origin_slot: number, - target_id: number, - target_slot: number - ); - configure(o: LLink | SerializedLLink): void; - serialize(): SerializedLLink; -} - -export type SerializedLGraphNode = { - id: T["id"]; - type: T["type"]; - pos: T["pos"]; - size: T["size"]; - flags: T["flags"]; - mode: T["mode"]; - inputs: T["inputs"]; - outputs: T["outputs"]; - title: T["title"]; - properties: T["properties"]; - widgets_values?: IWidget["value"][]; -}; - -/** https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#lgraphnode */ -export declare class LGraphNode { - static title_color: string; - static title: string; - static type: null | string; - static widgets_up: boolean; - constructor(title?: string); - - title: string; - type: null | string; - size: Vector2; - graph: null | LGraph; - graph_version: number; - pos: Vector2; - is_selected: boolean; - mouseOver: boolean; - - id: number; - - //inputs available: array of inputs - inputs: INodeInputSlot[]; - outputs: INodeOutputSlot[]; - connections: any[]; - - //local data - properties: Record; - properties_info: any[]; - - flags: Partial<{ - collapsed: boolean - }>; - - color: string; - bgcolor: string; - boxcolor: string; - shape: - | typeof LiteGraph.BOX_SHAPE - | typeof LiteGraph.ROUND_SHAPE - | typeof LiteGraph.CIRCLE_SHAPE - | typeof LiteGraph.CARD_SHAPE - | typeof LiteGraph.ARROW_SHAPE; - - serialize_widgets: boolean; - skip_list: boolean; - - /** Used in `LGraphCanvas.onMenuNodeMode` */ - mode?: - | typeof LiteGraph.ON_EVENT - | typeof LiteGraph.ON_TRIGGER - | typeof LiteGraph.NEVER - | typeof LiteGraph.ALWAYS; - - /** If set to true widgets do not start after the slots */ - widgets_up: boolean; - /** widgets start at y distance from the top of the node */ - widgets_start_y: number; - /** if you render outside the node, it will be clipped */ - clip_area: boolean; - /** if set to false it wont be resizable with the mouse */ - resizable: boolean; - /** slots are distributed horizontally */ - horizontal: boolean; - /** if true, the node will show the bgcolor as 'red' */ - has_errors?: boolean; - - /** configure a node from an object containing the serialized info */ - configure(info: SerializedLGraphNode): void; - /** serialize the content */ - serialize(): SerializedLGraphNode; - /** Creates a clone of this node */ - clone(): this; - /** serialize and stringify */ - toString(): string; - /** get the title string */ - getTitle(): string; - /** sets the value of a property */ - setProperty(name: string, value: any): void; - /** sets the output data */ - setOutputData(slot: number, data: any): void; - /** sets the output data */ - setOutputDataType(slot: number, type: string): void; - /** - * Retrieves the input data (data traveling through the connection) from one slot - * @param slot - * @param force_update if set to true it will force the connected node of this slot to output data into this link - * @return data or if it is not connected returns undefined - */ - getInputData(slot: number, force_update?: boolean): T; - /** - * Retrieves the input data type (in case this supports multiple input types) - * @param slot - * @return datatype in string format - */ - getInputDataType(slot: number): string; - /** - * Retrieves the input data from one slot using its name instead of slot number - * @param slot_name - * @param force_update if set to true it will force the connected node of this slot to output data into this link - * @return data or if it is not connected returns null - */ - getInputDataByName(slot_name: string, force_update?: boolean): T; - /** tells you if there is a connection in one input slot */ - isInputConnected(slot: number): boolean; - /** tells you info about an input connection (which node, type, etc) */ - getInputInfo( - slot: number - ): { link: number; name: string; type: string | 0 } | null; - /** returns the node connected in the input slot */ - getInputNode(slot: number): LGraphNode | null; - /** returns the value of an input with this name, otherwise checks if there is a property with that name */ - getInputOrProperty(name: string): T; - /** tells you the last output data that went in that slot */ - getOutputData(slot: number): T | null; - /** tells you info about an output connection (which node, type, etc) */ - getOutputInfo( - slot: number - ): { name: string; type: string; links: number[] } | null; - /** tells you if there is a connection in one output slot */ - isOutputConnected(slot: number): boolean; - /** tells you if there is any connection in the output slots */ - isAnyOutputConnected(): boolean; - /** retrieves all the nodes connected to this output slot */ - getOutputNodes(slot: number): LGraphNode[]; - /** Triggers an event in this node, this will trigger any output with the same name */ - trigger(action: string, param: any): void; - /** - * Triggers an slot event in this node - * @param slot the index of the output slot - * @param param - * @param link_id in case you want to trigger and specific output link in a slot - */ - triggerSlot(slot: number, param: any, link_id?: number): void; - /** - * clears the trigger slot animation - * @param slot the index of the output slot - * @param link_id in case you want to trigger and specific output link in a slot - */ - clearTriggeredSlot(slot: number, link_id?: number): void; - /** - * add a new property to this node - * @param name - * @param default_value - * @param type string defining the output type ("vec3","number",...) - * @param extra_info this can be used to have special properties of the property (like values, etc) - */ - addProperty( - name: string, - default_value: any, - type: string, - extra_info?: object - ): T; - /** - * add a new output slot to use in this node - * @param name - * @param type string defining the output type ("vec3","number",...) - * @param extra_info this can be used to have special properties of an output (label, special color, position, etc) - */ - addOutput( - name: string, - type: string | -1, - extra_info?: Partial - ): INodeOutputSlot; - /** - * add a new output slot to use in this node - * @param array of triplets like [[name,type,extra_info],[...]] - */ - addOutputs( - array: [string, string | -1, Partial | undefined][] - ): void; - /** remove an existing output slot */ - removeOutput(slot: number): void; - /** - * add a new input slot to use in this node - * @param name - * @param type string defining the input type ("vec3","number",...), it its a generic one use 0 - * @param extra_info this can be used to have special properties of an input (label, color, position, etc) - */ - addInput( - name: string, - type: string | -1, - extra_info?: Partial - ): INodeInputSlot; - /** - * add several new input slots in this node - * @param array of triplets like [[name,type,extra_info],[...]] - */ - addInputs( - array: [string, string | -1, Partial | undefined][] - ): void; - /** remove an existing input slot */ - removeInput(slot: number): void; - /** - * add an special connection to this node (used for special kinds of graphs) - * @param name - * @param type string defining the input type ("vec3","number",...) - * @param pos position of the connection inside the node - * @param direction if is input or output - */ - addConnection( - name: string, - type: string, - pos: Vector2, - direction: string - ): { - name: string; - type: string; - pos: Vector2; - direction: string; - links: null; - }; - setValue(v: any): void; - /** computes the size of a node according to its inputs and output slots */ - computeSize(): [number, number]; - /** - * https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#node-widgets - * @return created widget - */ - addWidget( - type: T["type"], - name: string, - value: T["value"], - callback?: WidgetCallback | string, - options?: T["options"] - ): T; - - addCustomWidget(customWidget: T): T; - - /** - * returns the bounding of the object, used for rendering purposes - * @return [x, y, width, height] - */ - getBounding(): Vector4; - /** checks if a point is inside the shape of a node */ - isPointInside( - x: number, - y: number, - margin?: number, - skipTitle?: boolean - ): boolean; - /** checks if a point is inside a node slot, and returns info about which slot */ - getSlotInPosition( - x: number, - y: number - ): { - input?: INodeInputSlot; - output?: INodeOutputSlot; - slot: number; - link_pos: Vector2; - }; - /** - * returns the input slot with a given name (used for dynamic slots), -1 if not found - * @param name the name of the slot - * @return the slot (-1 if not found) - */ - findInputSlot(name: string): number; - /** - * returns the output slot with a given name (used for dynamic slots), -1 if not found - * @param name the name of the slot - * @return the slot (-1 if not found) - */ - findOutputSlot(name: string): number; - /** - * connect this node output to the input of another node - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param targetNode the target node - * @param targetSlot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) - * @return {Object} the link_info is created, otherwise null - */ - connect( - slot: number | string, - targetNode: LGraphNode, - targetSlot: number | string - ): T | null; - /** - * disconnect one output to an specific node - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param target_node the target node to which this slot is connected [Optional, if not target_node is specified all nodes will be disconnected] - * @return if it was disconnected successfully - */ - disconnectOutput(slot: number | string, targetNode?: LGraphNode): boolean; - /** - * disconnect one input - * @param slot (could be the number of the slot or the string with the name of the slot) - * @return if it was disconnected successfully - */ - disconnectInput(slot: number | string): boolean; - /** - * returns the center of a connection point in canvas coords - * @param is_input true if if a input slot, false if it is an output - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param out a place to store the output, to free garbage - * @return the position - **/ - getConnectionPos( - is_input: boolean, - slot: number | string, - out?: Vector2 - ): Vector2; - /** Force align to grid */ - alignToGrid(): void; - /** Console output */ - trace(msg: string): void; - /** Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ - setDirtyCanvas(fg: boolean, bg: boolean): void; - loadImage(url: string): void; - /** Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */ - captureInput(v: any): void; - /** Collapse the node to make it smaller on the canvas */ - collapse(force: boolean): void; - /** Forces the node to do not move or realign on Z */ - pin(v?: boolean): void; - localToScreen(x: number, y: number, graphCanvas: LGraphCanvas): Vector2; - - // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-appearance - onDrawBackground?( - ctx: CanvasRenderingContext2D, - canvas: HTMLCanvasElement - ): void; - onDrawForeground?( - ctx: CanvasRenderingContext2D, - canvas: HTMLCanvasElement - ): void; - - // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-behaviour - onMouseDown?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseMove?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseUp?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseEnter?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseLeave?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onKey?(event: KeyboardEvent, pos: Vector2, graphCanvas: LGraphCanvas): void; - - /** Called by `LGraphCanvas.selectNodes` */ - onSelected?(): void; - /** Called by `LGraphCanvas.deselectNode` */ - onDeselected?(): void; - /** Called by `LGraph.runStep` `LGraphNode.getInputData` */ - onExecute?(): void; - /** Called by `LGraph.serialize` */ - onSerialize?(o: SerializedLGraphNode): void; - /** Called by `LGraph.configure` */ - onConfigure?(o: SerializedLGraphNode): void; - /** - * when added to graph (warning: this is called BEFORE the node is configured when loading) - * Called by `LGraph.add` - */ - onAdded?(graph: LGraph): void; - /** - * when removed from graph - * Called by `LGraph.remove` `LGraph.clear` - */ - onRemoved?(): void; - /** - * if returns false the incoming connection will be canceled - * Called by `LGraph.connect` - * @param inputIndex target input slot number - * @param outputType type of output slot - * @param outputSlot output slot object - * @param outputNode node containing the output - * @param outputIndex index of output slot - */ - onConnectInput?( - inputIndex: number, - outputType: INodeOutputSlot["type"], - outputSlot: INodeOutputSlot, - outputNode: LGraphNode, - outputIndex: number - ): boolean; - /** - * if returns false the incoming connection will be canceled - * Called by `LGraph.connect` - * @param outputIndex target output slot number - * @param inputType type of input slot - * @param inputSlot input slot object - * @param inputNode node containing the input - * @param inputIndex index of input slot - */ - onConnectOutput?( - outputIndex: number, - inputType: INodeInputSlot["type"], - inputSlot: INodeInputSlot, - inputNode: LGraphNode, - inputIndex: number - ): boolean; - - /** - * Called just before connection (or disconnect - if input is linked). - * A convenient place to switch to another input, or create new one. - * This allow for ability to automatically add slots if needed - * @param inputIndex - * @return selected input slot index, can differ from parameter value - */ - onBeforeConnectInput?( - inputIndex: number - ): number; - - /** a connection changed (new one or removed) (LiteGraph.INPUT or LiteGraph.OUTPUT, slot, true if connected, link_info, input_info or output_info ) */ - onConnectionsChange( - type: number, - slotIndex: number, - isConnected: boolean, - link: LLink, - ioSlot: (INodeOutputSlot | INodeInputSlot) - ): void; - - /** - * if returns false, will abort the `LGraphNode.setProperty` - * Called when a property is changed - * @param property - * @param value - * @param prevValue - */ - onPropertyChanged?(property: string, value: any, prevValue: any): void | boolean; - - /** Called by `LGraphCanvas.processContextMenu` */ - getMenuOptions?(graphCanvas: LGraphCanvas): ContextMenuItem[]; - getSlotMenuOptions?(slot: INodeSlot): ContextMenuItem[]; -} - -export type LGraphNodeConstructor = { - new (): T; -}; - -export type SerializedLGraphGroup = { - title: LGraphGroup["title"]; - bounding: LGraphGroup["_bounding"]; - color: LGraphGroup["color"]; - font: LGraphGroup["font"]; -}; -export declare class LGraphGroup { - title: string; - private _bounding: Vector4; - color: string; - font: string; - - configure(o: SerializedLGraphGroup): void; - serialize(): SerializedLGraphGroup; - move(deltaX: number, deltaY: number, ignoreNodes?: boolean): void; - recomputeInsideNodes(): void; - isPointInside: LGraphNode["isPointInside"]; - setDirtyCanvas: LGraphNode["setDirtyCanvas"]; -} - -export declare class DragAndScale { - constructor(element?: HTMLElement, skipEvents?: boolean); - offset: [number, number]; - scale: number; - max_scale: number; - min_scale: number; - onredraw: Function | null; - enabled: boolean; - last_mouse: Vector2; - element: HTMLElement | null; - visible_area: Vector4; - bindEvents(element: HTMLElement): void; - computeVisibleArea(): void; - onMouse(e: MouseEvent): void; - toCanvasContext(ctx: CanvasRenderingContext2D): void; - convertOffsetToCanvas(pos: Vector2): Vector2; - convertCanvasToOffset(pos: Vector2): Vector2; - mouseDrag(x: number, y: number): void; - changeScale(value: number, zooming_center?: Vector2): void; - changeDeltaScale(value: number, zooming_center?: Vector2): void; - reset(): void; -} - -/** - * This class is in charge of rendering one graph inside a canvas. And provides all the interaction required. - * Valid callbacks are: onNodeSelected, onNodeDeselected, onShowNodePanel, onNodeDblClicked - * - * @param canvas the canvas where you want to render (it accepts a selector in string format or the canvas element itself) - * @param graph - * @param options { skip_rendering, autoresize } - */ -export declare class LGraphCanvas { - static node_colors: Record< - string, - { - color: string; - bgcolor: string; - groupcolor: string; - } - >; - static link_type_colors: Record; - static gradients: object; - static search_limit: number; - - static getFileExtension(url: string): string; - static decodeHTML(str: string): string; - - static onMenuCollapseAll(): void; - static onMenuNodeEdit(): void; - static onShowPropertyEditor( - item: any, - options: any, - e: any, - menu: any, - node: any - ): void; - /** Create menu for `Add Group` */ - static onGroupAdd: ContextMenuEventListener; - /** Create menu for `Add Node` */ - static onMenuAdd: ContextMenuEventListener; - static showMenuNodeOptionalInputs: ContextMenuEventListener; - static showMenuNodeOptionalOutputs: ContextMenuEventListener; - static onShowMenuNodeProperties: ContextMenuEventListener; - static onResizeNode: ContextMenuEventListener; - static onMenuNodeCollapse: ContextMenuEventListener; - static onMenuNodePin: ContextMenuEventListener; - static onMenuNodeMode: ContextMenuEventListener; - static onMenuNodeColors: ContextMenuEventListener; - static onMenuNodeShapes: ContextMenuEventListener; - static onMenuNodeRemove: ContextMenuEventListener; - static onMenuNodeClone: ContextMenuEventListener; - - constructor( - canvas: HTMLCanvasElement | string, - graph?: LGraph, - options?: { - skip_render?: boolean; - autoresize?: boolean; - } - ); - - static active_canvas: HTMLCanvasElement; - - allow_dragcanvas: boolean; - allow_dragnodes: boolean; - /** allow to control widgets, buttons, collapse, etc */ - allow_interaction: boolean; - /** allows to change a connection with having to redo it again */ - allow_reconnect_links: boolean; - /** allow selecting multi nodes without pressing extra keys */ - multi_select: boolean; - /** No effect */ - allow_searchbox: boolean; - always_render_background: boolean; - autoresize?: boolean; - background_image: string; - bgcanvas: HTMLCanvasElement; - bgctx: CanvasRenderingContext2D; - canvas: HTMLCanvasElement; - canvas_mouse: Vector2; - clear_background: boolean; - connecting_node: LGraphNode | null; - connections_width: number; - ctx: CanvasRenderingContext2D; - current_node: LGraphNode | null; - default_connection_color: { - input_off: string; - input_on: string; - output_off: string; - output_on: string; - }; - default_link_color: string; - dirty_area: Vector4 | null; - dirty_bgcanvas?: boolean; - dirty_canvas?: boolean; - drag_mode: boolean; - dragging_canvas: boolean; - dragging_rectangle: Vector4 | null; - ds: DragAndScale; - /** used for transition */ - editor_alpha: number; - filter: any; - fps: number; - frame: number; - graph: LGraph; - highlighted_links: Record; - highquality_render: boolean; - inner_text_font: string; - is_rendering: boolean; - last_draw_time: number; - last_mouse: Vector2; - /** - * Possible duplicated with `last_mouse` - * https://github.com/jagenjo/litegraph.js/issues/70 - */ - last_mouse_position: Vector2; - /** Timestamp of last mouse click, defaults to 0 */ - last_mouseclick: number; - links_render_mode: - | typeof LiteGraph.STRAIGHT_LINK - | typeof LiteGraph.LINEAR_LINK - | typeof LiteGraph.SPLINE_LINK; - live_mode: boolean; - node_capturing_input: LGraphNode | null; - node_dragged: LGraphNode | null; - node_in_panel: LGraphNode | null; - node_over: LGraphNode | null; - node_title_color: string; - node_widget: [LGraphNode, IWidget] | null; - /** Called by `LGraphCanvas.drawBackCanvas` */ - onDrawBackground: - | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) - | null; - /** Called by `LGraphCanvas.drawFrontCanvas` */ - onDrawForeground: - | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) - | null; - onDrawOverlay: ((ctx: CanvasRenderingContext2D) => void) | null; - /** Called by `LGraphCanvas.processMouseDown` */ - onMouse: ((event: MouseEvent) => boolean) | null; - /** Called by `LGraphCanvas.drawFrontCanvas` and `LGraphCanvas.drawLinkTooltip` */ - onDrawLinkTooltip: ((ctx: CanvasRenderingContext2D, link: LLink, _this: this) => void) | null; - /** Called by `LGraphCanvas.selectNodes` */ - onNodeMoved: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeSelected` */ - onNodeSelected: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.deselectNode` */ - onNodeDeselected: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeDblClicked` */ - onShowNodePanel: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeDblClicked` */ - onNodeDblClicked: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.selectNodes` */ - onSelectionChange: ((nodes: Record) => void) | null; - /** Called by `LGraphCanvas.showSearchBox` */ - onSearchBox: - | (( - helper: Element, - value: string, - graphCanvas: LGraphCanvas - ) => string[]) - | null; - onSearchBoxSelection: - | ((name: string, event: MouseEvent, graphCanvas: LGraphCanvas) => void) - | null; - pause_rendering: boolean; - render_canvas_border: boolean; - render_collapsed_slots: boolean; - render_connection_arrows: boolean; - render_connections_border: boolean; - render_connections_shadows: boolean; - render_curved_connections: boolean; - render_execution_order: boolean; - render_only_selected: boolean; - render_shadows: boolean; - render_title_colored: boolean; - round_radius: number; - selected_group: null | LGraphGroup; - selected_group_resizing: boolean; - selected_nodes: Record; - show_info: boolean; - title_text_font: string; - /** set to true to render title bar with gradients */ - use_gradients: boolean; - visible_area: DragAndScale["visible_area"]; - visible_links: LLink[]; - visible_nodes: LGraphNode[]; - zoom_modify_alpha: boolean; - - /** clears all the data inside */ - clear(): void; - /** assigns a graph, you can reassign graphs to the same canvas */ - setGraph(graph: LGraph, skipClear?: boolean): void; - /** opens a graph contained inside a node in the current graph */ - openSubgraph(graph: LGraph): void; - /** closes a subgraph contained inside a node */ - closeSubgraph(): void; - /** assigns a canvas */ - setCanvas(canvas: HTMLCanvasElement, skipEvents?: boolean): void; - /** binds mouse, keyboard, touch and drag events to the canvas */ - bindEvents(): void; - /** unbinds mouse events from the canvas */ - unbindEvents(): void; - - /** - * this function allows to render the canvas using WebGL instead of Canvas2D - * this is useful if you plant to render 3D objects inside your nodes, it uses litegl.js for webgl and canvas2DtoWebGL to emulate the Canvas2D calls in webGL - **/ - enableWebGL(): void; - - /** - * marks as dirty the canvas, this way it will be rendered again - * @param fg if the foreground canvas is dirty (the one containing the nodes) - * @param bg if the background canvas is dirty (the one containing the wires) - */ - setDirty(fg: boolean, bg: boolean): void; - - /** - * Used to attach the canvas in a popup - * @return the window where the canvas is attached (the DOM root node) - */ - getCanvasWindow(): Window; - /** starts rendering the content of the canvas when needed */ - startRendering(): void; - /** stops rendering the content of the canvas (to save resources) */ - stopRendering(): void; - - processMouseDown(e: MouseEvent): boolean | undefined; - processMouseMove(e: MouseEvent): boolean | undefined; - processMouseUp(e: MouseEvent): boolean | undefined; - processMouseWheel(e: MouseEvent): boolean | undefined; - - /** returns true if a position (in graph space) is on top of a node little corner box */ - isOverNodeBox(node: LGraphNode, canvasX: number, canvasY: number): boolean; - /** returns true if a position (in graph space) is on top of a node input slot */ - isOverNodeInput( - node: LGraphNode, - canvasX: number, - canvasY: number, - slotPos: Vector2 - ): boolean; - - /** process a key event */ - processKey(e: KeyboardEvent): boolean | undefined; - - copyToClipboard(): void; - pasteFromClipboard(): void; - processDrop(e: DragEvent): void; - checkDropItem(e: DragEvent): void; - processNodeDblClicked(n: LGraphNode): void; - processNodeSelected(n: LGraphNode, e: MouseEvent): void; - processNodeDeselected(node: LGraphNode): void; - - /** selects a given node (or adds it to the current selection) */ - selectNode(node: LGraphNode, add?: boolean): void; - /** selects several nodes (or adds them to the current selection) */ - selectNodes(nodes?: LGraphNode[], add?: boolean): void; - /** removes a node from the current selection */ - deselectNode(node: LGraphNode): void; - /** removes all nodes from the current selection */ - deselectAllNodes(): void; - /** deletes all nodes in the current selection from the graph */ - deleteSelectedNodes(): void; - - /** centers the camera on a given node */ - centerOnNode(node: LGraphNode): void; - /** changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom */ - setZoom(value: number, center: Vector2): void; - /** brings a node to front (above all other nodes) */ - bringToFront(node: LGraphNode): void; - /** sends a node to the back (below all other nodes) */ - sendToBack(node: LGraphNode): void; - /** checks which nodes are visible (inside the camera area) */ - computeVisibleNodes(nodes: LGraphNode[]): LGraphNode[]; - /** renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes) */ - draw(forceFG?: boolean, forceBG?: boolean): void; - /** draws the front canvas (the one containing all the nodes) */ - drawFrontCanvas(): void; - /** draws some useful stats in the corner of the canvas */ - renderInfo(ctx: CanvasRenderingContext2D, x: number, y: number): void; - /** draws the back canvas (the one containing the background and the connections) */ - drawBackCanvas(): void; - /** draws the given node inside the canvas */ - drawNode(node: LGraphNode, ctx: CanvasRenderingContext2D): void; - /** draws graphic for node's slot */ - drawSlotGraphic(ctx: CanvasRenderingContext2D, pos: number[], shape: SlotShape, horizontal: boolean): void; - /** draws the shape of the given node in the canvas */ - drawNodeShape( - node: LGraphNode, - ctx: CanvasRenderingContext2D, - size: [number, number], - fgColor: string, - bgColor: string, - selected: boolean, - mouseOver: boolean - ): void; - /** draws every connection visible in the canvas */ - drawConnections(ctx: CanvasRenderingContext2D): void; - /** - * draws a link between two points - * @param a start pos - * @param b end pos - * @param link the link object with all the link info - * @param skipBorder ignore the shadow of the link - * @param flow show flow animation (for events) - * @param color the color for the link - * @param startDir the direction enum - * @param endDir the direction enum - * @param numSublines number of sublines (useful to represent vec3 or rgb) - **/ - renderLink( - a: Vector2, - b: Vector2, - link: object, - skipBorder: boolean, - flow: boolean, - color?: string, - startDir?: number, - endDir?: number, - numSublines?: number - ): void; - - computeConnectionPoint( - a: Vector2, - b: Vector2, - t: number, - startDir?: number, - endDir?: number - ): void; - - drawExecutionOrder(ctx: CanvasRenderingContext2D): void; - /** draws the widgets stored inside a node */ - drawNodeWidgets( - node: LGraphNode, - posY: number, - ctx: CanvasRenderingContext2D, - activeWidget: object - ): void; - /** process an event on widgets */ - processNodeWidgets( - node: LGraphNode, - pos: Vector2, - event: Event, - activeWidget: object - ): void; - /** draws every group area in the background */ - drawGroups(canvas: any, ctx: CanvasRenderingContext2D): void; - adjustNodesSize(): void; - /** resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode */ - resize(width?: number, height?: number): void; - /** - * switches to live mode (node shapes are not rendered, only the content) - * this feature was designed when graphs where meant to create user interfaces - **/ - switchLiveMode(transition?: boolean): void; - onNodeSelectionChange(): void; - touchHandler(event: TouchEvent): void; - - showLinkMenu(link: LLink, e: any): false; - prompt( - title: string, - value: any, - callback: Function, - event: any - ): HTMLDivElement; - showSearchBox(event?: MouseEvent): void; - showEditPropertyValue(node: LGraphNode, property: any, options: any): void; - createDialog( - html: string, - options?: { position?: Vector2; event?: MouseEvent } - ): void; - - convertOffsetToCanvas: DragAndScale["convertOffsetToCanvas"]; - convertCanvasToOffset: DragAndScale["convertCanvasToOffset"]; - /** converts event coordinates from canvas2D to graph coordinates */ - convertEventToCanvasOffset(e: MouseEvent): Vector2; - /** adds some useful properties to a mouse event, like the position in graph coordinates */ - adjustMouseEvent(e: MouseEvent): void; - - getCanvasMenuOptions(): ContextMenuItem[]; - getNodeMenuOptions(node: LGraphNode): ContextMenuItem[]; - getGroupMenuOptions(): ContextMenuItem[]; - /** Called by `getCanvasMenuOptions`, replace default options */ - getMenuOptions?(): ContextMenuItem[]; - /** Called by `getCanvasMenuOptions`, append to default options */ - getExtraMenuOptions?(): ContextMenuItem[]; - /** Called when mouse right click */ - processContextMenu(node: LGraphNode, event: Event): void; -} - -declare class ContextMenu { - static trigger( - element: HTMLElement, - event_name: string, - params: any, - origin: any - ): void; - static isCursorOverElement(event: MouseEvent, element: HTMLElement): void; - static closeAllContextMenus(window: Window): void; - constructor(values: ContextMenuItem[], options?: IContextMenuOptions, window?: Window); - options: IContextMenuOptions; - parentMenu?: ContextMenu; - lock: boolean; - current_submenu?: ContextMenu; - addItem( - name: string, - value: ContextMenuItem, - options?: IContextMenuOptions - ): void; - close(e?: MouseEvent, ignore_parent_menu?: boolean): void; - getTopMenu(): void; - getFirstEvent(): void; -} - -declare global { - interface CanvasRenderingContext2D { - /** like rect but rounded corners */ - roundRect( - x: number, - y: number, - width: number, - height: number, - radius: number, - radiusLow: number - ): void; - } - - interface Math { - clamp(v: number, min: number, max: number): number; - } -} diff --git a/examples/editing/litegraphScripts.ts b/examples/editing/litegraphScripts.ts deleted file mode 100644 index e30e3dea..00000000 --- a/examples/editing/litegraphScripts.ts +++ /dev/null @@ -1,670 +0,0 @@ -import {ConnectionInfo, EventHandler, Graph, GraphNode, - GraphNodeProperties, Listener, WorkerInfo, getCallbackFromString, - wchtmlloader -} from '../../index' -import { replaceListenerArg } from './listenerManip'; - -import { LiteGraph, LGraph, LGraphCanvas, LGraphNode} from './litegraph.js' - -export type LGraphNodeProps = { - __renderHTML?:boolean, //do we want to visualize elements inside the node or on a blank page area (like a typical document vs in-editor) Make this toggle between where it renders in the page/editor - __widget?:{ - //we can use the built-in widgets and/or we can renderHtml, just figure out how to access the html to set them next to each other somehow - } - __position?:{ - //will be set by default otherwise based on proximity to connections - } -} & GraphNodeProperties; - -export type LGraphNodeM = LGraphNode & { - triggers:any, - __node:GraphNode, - __graph:Graph, - __unique:string,//GraphNode unique Id for event lookup - editor:LGraph, tag:string, key?:string, - subs:{[key:string]:{ sub:number, listener:Listener }} - __settings?:{ - mode?:'nodeMethod' //default, a node just runs a function method or a getter for a variable - | 'nodeInstance' //alternatively, we can break out several variables on node - | 'subGraph', //or this is a node on a subgraph for a node, so implicitly all variable are "this", i.e. for internal listeners to states for containing logic (ala blueprints) - - nodeOutputs?:string[], - [key:string]:any - }, - - firstConnect:boolean //internal -} - - -const execPin = '►'; //for modded litegraph - -//https://stackoverflow.com/questions/9091838/get-function-parameter-names-for-interface-purposes -export function getFnParamNames(fn){ - if(typeof fn !== 'string') fn = fn.toString(); - const arrowMatch = fn.match(/\(?[^]*?\)?\s*=>/) - if (arrowMatch) return arrowMatch[0].replace(/[()\s]/gi,'').replace('=>','').split(',') - const match = fn.match(/\([^]*?\)/) - return match ? match[0].replace(/[()\s]/gi,'').split(',') : [] -} - - -export let registered = new Map(); -export let created = new Map(); - -export function addNodeToLGraph(node, graph, editor:LGraph) { - let roots = graph.__node.roots; - let hasNode = registered.get(node.__node.tag) as LGraphNodeM; - if (!hasNode) { - registerNode(node, roots[node.__node.tag],undefined,editor); - for(const key in node) { - if(key !== 'get' && !key.startsWith('__')) - registerNode(node, roots[node.__node.tag], key, editor); - } - - } -} - -export function registerLGraphNodesFromGraph(graph:Graph, editor:LGraph) { - graph.__node.nodes.forEach((node) => { - addNodeToLGraph(node,graph, editor); - }); -} - -//the positioning stuff is incorrect (I broke it then forgot what it did) -export const updateNodePosition = (current, sourceNode, lastNode) => { - const previous = lastNode ? lastNode : sourceNode; - const [ x, y ] = previous.pos; - const [ width, height ] = previous.size; - - current.pos = [x + width + 50, y + height + 50]; // Update position at the end -} - -//fix!!! -export function updateArgNodePosition (target, nodes, lastNode) { - - const [ targetX ] = lastNode ? lastNode.pos : target.pos - const [ targetWidth ] = lastNode ? lastNode.size : target.size - - nodes.forEach((n:LGraphNodeM) => { - const [ _, y ] = n.pos - const [ __, height ] = n.size - - //let bb = n.getBounding(); //include bounding box? - - n.pos = [targetX - targetWidth - 50, y + height + 50]; - }); -} - -export function createNode(name:string, LGraph:LGraph, duplicate = false) { - const got = created.get(name); - if (!duplicate && got) return got as LGraphNodeM; - const node = LiteGraph.createNode(name); - created.set(name, node as LGraphNodeM) - LGraph.add(node); - return node as LGraphNodeM; -} - - - - -export function renderLGraphFromExistingEvents( - listeners:EventHandler['triggers'], - LGraph:LGraph -) { - - let minY = 0; - let lastNode; - for(const key in listeners) { - let tarr = listeners[key] as any as Listener[]; - let nodes = [] as any[]; - for(const trigger of tarr) { - //console.log(trigger); - if(!trigger.tkey) continue; - //create each node in the arg stack if exists, connect by arg position, exec pins only at listener level - - const name = trigger.tkey ? trigger.target+'.'+trigger.tkey : trigger.target as string; - let node = createNode(name,LGraph,true); - let srcname = trigger.key ? trigger.source+'.'+trigger.key : trigger.source as string; - - let hasNode = created.get(srcname); - let srcnode = createNode(srcname, LGraph, false); - - - //console.log(name,node,srcname,srcnode); - - updateNodePosition(node, srcnode, lastNode); - lastNode = hasNode; - - if(!hasNode) { - srcnode.pos[1] = minY + 25; - } - - node.pos[0] = srcnode.pos[0] + 50; - if(minY > node.pos[1]) node.pos[1] = minY + 50; - else node.pos[1] = srcnode.pos[1] + 50; - minY = node.pos[1]; - - //set x and y offset - - if(trigger.__args) { - let lastargnode; - const iterateArg = (arg, node, i) => { - if(typeof arg === 'object') { - let cb = arg.__callback ? arg.__callback : arg.__input; - if(cb) { - let argnode = createNode(cb as string,LGraph, true); - argnode.connect(1, node, i); //todo: several argument slots? - if(arg.__args) { - let argnodes = [] as any[]; - arg.__args.forEach((a,j) => { - argnodes.push(iterateArg(a,argnode,j+1)); - }); - if(argnodes.length > 0) { - updateArgNodePosition(argnode, argnodes, lastargnode); - argnodes.forEach((n) => { - if(minY > n.pos[1]) minY = n.pos[1]; - }); - } - } - lastargnode = argnode; - return argnode; - } - } else if (typeof arg === 'string') { - let argnode = createNode(arg, LGraph, true); - argnode.connect(1, node, i); //todo: several argument slots? - lastargnode = argnode; - return argnode; - } - } - - let argnodes = [] as any[]; - trigger.__args.forEach((arg,i) => { - argnodes.push(iterateArg(arg,node,i+1)); - }); - - if(argnodes.length > 0) { - updateArgNodePosition(node, argnodes, lastargnode); - argnodes.forEach((n) => { - if(minY > n.pos[1]) minY = n.pos[1]; - }); - } - } - - srcnode.connect(0,node,0); - node.subs[Object.keys(node.subs).length] = { sub:trigger.sub, listener:trigger }; - nodes.push(node); - } - for(const node of nodes) { - node.firstConnect = false; //future connections will trigger the subscription swapping - } - } -} - - //creates a new nested arg array from visual connections -const getArgsFromNode = (editor:LGraph, - currentOutputNode:LGraphNodeM, args=[] as any[], previousNode?:LGraphNodeM, curDepth = 0, wasAdded = {} //prevent circular infinite looping -) => { - currentOutputNode.inputs.forEach((inp,i) => { - if(i>0) { //don't use first slot, which we labeled as an exec pin - if(inp.link) { //all arg inputs only have one link (not the case for exec links which may have .extraLinks) - if(editor) { - let link = editor.links[inp.link]; - let inputNodei = editor.getNodeById(link.origin_id); - let origin = link.origin_slot; - if(inputNodei) { - if(inputNodei.outputs[origin].name === 'Get') { - args[i - 1] = inputNodei.title; //the title is the node or method key - //stop it here - } else { - args[i - 1] = { __callback:inputNodei.title }; - curDepth++; - if(wasAdded[link.origin_id]) { //prevent infinite recursion - args[i - 1].__args[i-1] = wasAdded[link.origin_id]; - } else { //go get em otherwise - inputNodei.inputs.forEach((inpj, j) => { - if(j > 0) { - if(inpj.link) { - if(!args[i-1].__args) { - args[i-1].__args = []; - wasAdded[link.origin_id] = args[i - 1].__args; - } - let linkj = editor.links[inpj.link]; - let inputNodej = editor.getNodeById(linkj.origin_id); - let originj = linkj.origin_slot; - if(inputNodej) { - args[i - 1].__args = getArgsFromNode( - editor, - inputNodej as LGraphNodeM, - args[i - 1].__args, - inputNodei as LGraphNodeM, - curDepth, - wasAdded - ); - } - } - } - }); - } - } - } - } - } else args[i-1] = undefined; - } - }); - - return args; -} - - -const checkNodeForSubscriptionUpdate = ( - self:LGraphNodeM, editor:LGraph, inputIndex, outputType, outputSlot, outputNode, outputIndex -) => { - - let execChanged = false; //do we need to update subscriptions? - - if( - (self.inputs[inputIndex].name === execPin && outputSlot.name !== execPin) - || - (self.inputs[inputIndex].name !== execPin && outputSlot.name === execPin) - ) { - return false; //reject a non-event connection - } else { - //these are both exec inputs - execChanged = true; - } - - //a link is updated so check if we have an exec on this node - if(!execChanged && !(Object.keys(self.inputs).find((v) => { if(self.inputs[v].name === execPin && self.inputs[v].link) return true; }) || (self.inputs[0] as any).extraLinks)) - execChanged = true; - - if(execChanged) { - //these are subscriptions - //graph.subscribe() - //and/oor modify the listener - } else { - - /* - * - * - * On connecting to an arg input, - * - * - */ - - let args = getArgsFromNode(editor, self as LGraphNodeM); - - const subNode = (i, sourceNode) => { - if(self.subs[i]) { - let listener = self.subs[i].listener; - let sub = self.subs[i].sub; - self.__graph.unsubscribe(listener.target as string, sub, listener.tkey, listener.subInput); - } else { - - } - let sub = self.__graph.subscribe( - sourceNode.tag, self.tag, args - ); - self.subs[i] = { - sub, - listener:self.__graph.__node.state.getEvent( - sourceNode.__unique + sourceNode.key ? '.'+sourceNode.key : '', - sub - ) as any as Listener - }; - } - - if((self.inputs[0] as any).link) { - let sourceNode = editor.getNodeById((self.inputs[0] as any).link.origin_id) as LGraphNodeM; - if(sourceNode) subNode(0,sourceNode); - } - if((self.inputs[0] as any).extraLinks) { - let i = 0; - for(const key in (self.inputs[0] as any).extraLinks) { - i++; - let sourceNode = editor.getNodeById(editor.links[key].origin_id) as LGraphNodeM; - if(sourceNode) subNode(i,sourceNode); - } - } - - //now propagate upstream if any outputs on the outputNode continue on - if(self.outputs) { - let checked = {} as any; - self.outputs.forEach((output) => { - //rebuild/swap args in active listeners - if(editor && output.links) { - output.links.forEach((link) => { - let outputNode = editor.getNodeById(editor.links[link].target_id); - if(!checked[editor.links[link].target_id]) { - checked[editor.links[link].target_id] = true; - //update subs - if(outputNode) - checkNodeForSubscriptionUpdate(outputNode as LGraphNodeM,editor,editor.links[link].target_slot,undefined,self.outputs[editor.links[link].origin_slot],undefined,undefined); - } - }); - - } - }); - } - - } -} - - - - -export function registerNode( - node: GraphNode, - root?:Function|GraphNodeProperties, - key?: string, - editor?:LGraph -) { - - - const tag = node.__node.tag; - const name = key ? `${tag}.${key}` : tag; - - let hasNode = registered.get(name) as LGraphNodeM; - if (hasNode) return name; - - - const NewNode = function() { - let self = this as LGraphNodeM; - self.title = name; - - self.triggers = node.__listeners ? node.__listeners : {}; - self.__node = node; - self.tag = tag; - self.key = key; - self.__unique = node.__node.unique; - self.__graph = node.__node.graph; - self.editor = editor as LGraph; - self.subs = {}; - self.firstConnect = true; - - let params; - - let setOutputNameFromFunction = (fn) => { - let str = typeof fn === 'string' ? fn : fn.toString() as string; - let isNative = str.indexOf('[native code]') > -1; - if(isNative) { - self.addInput('', 0 as any); - self.addOutput('', 0 as any); - return; - } - let idx = str.lastIndexOf('return'); - if(idx !== str.indexOf('return')) { //multiple return statements so we can't determine which one, just use a blank output - self.addOutput('', 0 as any); - return; - } - if(idx > -1) {//if exits - idx+=5; - //get output name - let lastIndex = str.lastIndexOf(';'); - if(lastIndex === -1 && lastIndex > idx) { - lastIndex = str.lastIndexOf('}'); - } - let substr; - if(lastIndex > -1 && lastIndex > idx) substr = str.substring(idx+1,lastIndex); - if(substr) self.addOutput(substr, 0 as any); //todo: can we type this at all? else do it dynamically - else self.addOutput('', 0 as any); - } - } - - self.addInput(execPin,-1); //fix to be able to add/remove contextually - self.addOutput(execPin,-1); //fix to be able to add/remove contextually - - if(key && root?.[key]) { - if(typeof root[key] === 'function') { - setOutputNameFromFunction(root[key]) - params = getFnParamNames(root[key]); - } else { - let typ = typeof root[key] as string; - if(typ === 'undefined') typ = 0 as any; - self.addInput('Set', typ); - self.addOutput('Get', typ); - } - } - if(typeof root === 'function') { - setOutputNameFromFunction(root); - params = getFnParamNames(root); - } else if(root?.__operator || root?.default) { - setOutputNameFromFunction(root.__operator ? root.__operator : root.default); - params = getFnParamNames(root.__operator ? root.__operator : root.default); - } - if(params) { - params.forEach((p,i) => { - if(p || params.length > 1) self.addInput(p,0 as any); - }); - } - - // for (let key in self) this.addInput(key) - - self.onExecute = function() { - //this can trigger the node operator here or the method of a node to cause downstream effects - } - - self.onAdded = function(graph:LGraph) { - // - } - - self.onRemoved = function() { - //graph.unsubscribe - } - - //when an input (left side) is connected on this node from an output (right side) on another node - self.onConnectInput = function(inputIndex, outputType, outputSlot, outputNode, outputIndex) { - - if(!self.firstConnect) - checkNodeForSubscriptionUpdate(self, editor as LGraph, inputIndex, outputType, outputSlot, outputNode, outputIndex); - - console.log('onConnectInput',{inputIndex, outputType, outputSlot, outputNode, outputIndex}); - - return true; - } - - //when an output is connected on this node, can just use onConnectInput - self.onConnectOutput = function(outputIndex, inputType, inputSlot, inputNode, inputIndex) { - //graph.subscribe(); - //console.log('onConnectOutput',{outputIndex, inputType, inputSlot, inputNode, inputIndex}); - - return true; - } - - self.onConnectionsChange = function(type, slotIndex, isConnected, link, ioSlot) { - //console.log('onConnectionsChange',{type, slotIndex, isConnected, link, ioSlot}); - if(!isConnected) { - //graph.unsubscribe(); - } - } - - // if(node?.__listeners) for(const key in node.__listeners) { - // //add outputs - // } - - // if(node?.__args) for(const key in node.__args) { - // //adds inputs - // } - - //self.addWidget('slider',...); //todo - - if(node?.__element && node?.__renderHTML) { - //we should be able to render the element over the node. The editor is in a canvas so we need to use the - // position X and Y of the canvas element (relative to the pageX and pageY), - // then set the HTML over the top of it and account for the size in the canvas elmeent using the html bounding box - } - - } as any as (new () => LGraphNodeM); - - LiteGraph.registerNodeType(name, NewNode); //now registered in system - - registered.set(name, NewNode); - - return name; - -} - - - - - -export function getListenersFromWorker(worker:WorkerInfo) { - return worker.run('getListenerJSON'); -} //build the graph from this result - -export function setSubscriptionOnWorker(worker:WorkerInfo, nodeEvent:string, onEvent:any, args?:any[], key?:string, subInput?:boolean, blocking?:boolean) { - return worker.subscribe(nodeEvent, onEvent, args, key, subInput, blocking); -} - -export function subscribeNodeToWorker(worker:WorkerInfo, node:LGraphNodeM) { - -} - -//todo: create a worker node - - - -export function registerRemoteNode( - root:Function|GraphNodeProperties|string, - tag:string, - endpoint:ConnectionInfo, - key?: string, - editor?:LGraph -) { - - const name = key ? `${tag}.${key}` : tag; - - let hasNode = registered.get(name) as LGraphNodeM; - if (hasNode) return name; - - - const NewNode = function() { - let self = this as LGraphNodeM; - self.title = name; - - self.tag = tag; - self.key = key; - self.editor = editor as LGraph; - self.subs = {}; - self.firstConnect = true; - - let params; - - let setOutputNameFromFunction = (fn) => { - let str = typeof fn === 'string' ? fn : fn.toString() as string; - let isNative = str.indexOf('[native code]') > -1; - if(isNative) { - self.addInput('', 0 as any); - self.addOutput('', 0 as any); - return; - } - let idx = str.lastIndexOf('return'); - if(idx !== str.indexOf('return')) { //multiple return statements so we can't determine which one, just use a blank output - self.addOutput('', 0 as any); - return; - } - if(idx > -1) {//if exits - idx+=5; - //get output name - let lastIndex = str.lastIndexOf(';'); - if(lastIndex === -1 && lastIndex > idx) { - lastIndex = str.lastIndexOf('}'); - } - let substr; - if(lastIndex > -1 && lastIndex > idx) substr = str.substring(idx+1,lastIndex); - if(substr) self.addOutput(substr, 0 as any); //todo: can we type this at all? else do it dynamically - else self.addOutput('', 0 as any); - } - } - - self.addInput(execPin,-1); //fix to be able to add/remove contextually - self.addOutput(execPin,-1); //fix to be able to add/remove contextually - - if(key && root?.[key]) { - if(typeof root[key] === 'function') { - setOutputNameFromFunction(root[key]) - params = getFnParamNames(root[key]); - } else { - let typ = typeof root[key] as string; - if(typ === 'undefined') typ = 0 as any; - self.addInput('Set', typ); - self.addOutput('Get', typ); - } - } - if(typeof root === 'function') { - setOutputNameFromFunction(root); - params = getFnParamNames(root); - } else if(typeof root === 'object' && (root?.__operator || root?.default)) { - setOutputNameFromFunction(root.__operator ? root.__operator : root.default); - params = getFnParamNames(root.__operator ? root.__operator : root.default); - } - if(params) { - params.forEach((p,i) => { - if(p || params.length > 1) self.addInput(p,0 as any); - }); - } - - // for (let key in self) this.addInput(key) - - self.onExecute = function() { - //this can trigger the node operator here or the method of a node to cause downstream effects - } - - self.onAdded = function(graph:LGraph) { - // - } - - self.onRemoved = function() { - //graph.unsubscribe - } - - //when an input (left side) is connected on this node from an output (right side) on another node - self.onConnectInput = function(inputIndex, outputType, outputSlot, outputNode, outputIndex) { - - if(!self.firstConnect) - checkNodeForSubscriptionUpdate(self, editor as LGraph, inputIndex, outputType, outputSlot, outputNode, outputIndex); - - console.log('onConnectInput',{inputIndex, outputType, outputSlot, outputNode, outputIndex}); - - return true; - } - - //when an output is connected on this node, can just use onConnectInput - self.onConnectOutput = function(outputIndex, inputType, inputSlot, inputNode, inputIndex) { - //graph.subscribe(); - //console.log('onConnectOutput',{outputIndex, inputType, inputSlot, inputNode, inputIndex}); - - return true; - } - - self.onConnectionsChange = function(type, slotIndex, isConnected, link, ioSlot) { - //console.log('onConnectionsChange',{type, slotIndex, isConnected, link, ioSlot}); - if(!isConnected) { - //graph.unsubscribe(); - } - } - - // if(node?.__listeners) for(const key in node.__listeners) { - // //add outputs - // } - - // if(node?.__args) for(const key in node.__args) { - // //adds inputs - // } - - //self.addWidget('slider',...); //todo - - // if(node?.__element && node?.__renderHTML) { - // //we should be able to render the element over the node. The editor is in a canvas so we need to use the - // // position X and Y of the canvas element (relative to the pageX and pageY), - // // then set the HTML over the top of it and account for the size in the canvas elmeent using the html bounding box - // } - - } as any as (new () => LGraphNodeM); - - LiteGraph.registerNodeType(name, NewNode); //now registered in system - - registered.set(name, NewNode); - - return name; - -} \ No newline at end of file diff --git a/examples/editing/old/WebComponent.ts b/examples/editing/old/WebComponent.ts deleted file mode 100644 index 293f739d..00000000 --- a/examples/editing/old/WebComponent.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { Graph, GraphNode, GraphNodeProperties } from "../../src/core/Graph"; -import { wchtmlloader } from '../../src/loaders/html/wc.loader'; - -export class WebComponent { - - [x: keyof GraphNodeProperties]: GraphNodeProperties[keyof GraphNodeProperties] - - node: GraphNode - useShadow = true - - - constructor(properties: GraphNodeProperties) { - - // ----------------- Handle Web Component Properties ----------------- - Object.assign(this, properties); - } - - connect (properties: GraphNodeProperties, graph?: Graph, parent?: GraphNode) { - - if (graph) { - const node = graph.add(properties, parent) - if (node) { - this.node = node - this.__props = this.node.__props - } else console.error('Could not add node to graph', properties) - } else { - this.graph = new Graph({ - properties, - loaders: { wchtmlloader } - }) - - this.node = this.graph.get(this.graph.__node.tag) - } - - this.__props = this.node.__props - - return this.node - } - -} - -export default WebComponent \ No newline at end of file diff --git a/examples/editing/old/context/ContextMenu.ts b/examples/editing/old/context/ContextMenu.ts deleted file mode 100644 index c2b95b99..00000000 --- a/examples/editing/old/context/ContextMenu.ts +++ /dev/null @@ -1,99 +0,0 @@ -import WebComponent from "../WebComponent"; - -import style from './styles.css' -import html from './index.html' - -type MenuItem = { - text: string; - onclick: (e:any, returned: any) => any - } - - - type Response = { - condition: (target: HTMLElement[]) => boolean | any - contents: (ev: MouseEvent) => MenuItem[]; - } - - -export class ContextMenu extends WebComponent { - - responses: Map = new Map() - - constructor() { - super({ - __element: 'escode-context-menu', - __template: html, - __css: style - }) - - this.connect(this) - } - - __onrender () { - this.list = (this.shadowRoot ?? this).querySelector('ul') - - /** close the right click context menu on click */ - window.addEventListener('click', this.onClick) - - /** - present the right click context menu ONLY for the elements having the right class - */ - window.addEventListener('contextmenu', this.onContextMenu) - - } - - - onClick() { - this.style.display = 'none'; - if (this.style.display === 'block') document.body.style.overflow = '' - } - - setResponse = (id, info: Response) => this.responses.set(id, info) - - delete = (id) => this.responses.delete(id) - - onContextMenu = (e) => { - - document.body.style.overflow = 'hidden' - - - this.list.innerHTML = '' // Clear - - - let count = 0; - this.responses.forEach((o) => { - // console.log(o, o.condition(selected)) - - const isMatch = o.condition(e.path ?? [e.target]) - if (isMatch) { - e.preventDefault(); - - // Correct for Parent Window Offset - let parent = (this.parentNode as any) - if (parent.host) parent = parent.host // LitElement correction - var rect = parent.getBoundingClientRect() - this.style.left = e.clientX - rect.left + 'px' - this.style.top = e.clientY - rect.top + 'px' - this.style.display = 'block' - const list = o.contents(e) ?? [] - - if (list.length > 0) { - - if (count > 0) this.list.appendChild(document.createElement('hr')) // Split - - list.forEach(item => { - const li = document.createElement('li') - li.innerHTML = item.text - li.onclick = (ev) => { - item.onclick(ev, isMatch) - } - this.list.appendChild(li) - }) - - count++ - } - } - }) - } - -} \ No newline at end of file diff --git a/examples/editing/old/context/index.html b/examples/editing/old/context/index.html deleted file mode 100644 index e2d1b049..00000000 --- a/examples/editing/old/context/index.html +++ /dev/null @@ -1 +0,0 @@ -
    \ No newline at end of file diff --git a/examples/editing/old/context/styles.css b/examples/editing/old/context/styles.css deleted file mode 100644 index 3b54c68a..00000000 --- a/examples/editing/old/context/styles.css +++ /dev/null @@ -1,52 +0,0 @@ -:host { - border-radius: 10px; - box-shadow: 0 1px 5px 0 rgb(0 0 0 / 20%); - position: absolute; - display: none; - z-index: 10000; - padding: 5px; - color: black; - font-size: 80%; - min-width: 200px; - background: rgba(255, 255, 255, 0.8); - backdrop-filter: blur(6px); -} - -ul, -li { - list-style: none; - margin: 0; - padding: 0; - border-radius: 3px; - user-select: none; -} - -li { - /* border-bottom:solid 1px #CCC; */ - padding: 5px 10px; -} - -li:last-child { - border: none; -} - -li:hover { - background: #EEE; -} - -hr { - margin: 5px; -} - -@media (prefers-color-scheme: dark) { - - :host { - background: rgba(100, 100, 100, 0.8); - color: white; - } - - li:hover { - background: #AAA; - } - -} \ No newline at end of file diff --git a/examples/editing/old/editor/Editor.ts b/examples/editing/old/editor/Editor.ts deleted file mode 100644 index 343b0fd7..00000000 --- a/examples/editing/old/editor/Editor.ts +++ /dev/null @@ -1,934 +0,0 @@ -import { Graph, GraphNode, GraphNodeProperties } from "../../../src/core/Graph" -import { WebComponent } from "../WebComponent"; -import style from './styles.css' -import html from './index.html' -import context from "./context"; -import { Node, NodeProps } from "./node/Node"; -import { Listener } from "./listener/Listener"; -import drag from './utils/drag' - -export default class Editor extends WebComponent { - - - - // GraphScript Behaviors - __onrender = (el) => { - - // ------------------------- Track Elements from the Template ------------------------- - const grid = (el.shadowRoot ?? el).querySelector('#grid') - - this.elements = { grid } - - // ------------------------- Handle Events ------------------------- - el.addEventListener('mousedown', e => { - this.context.start = { x: e.clientX - this.context.point.x, y: e.clientY - this.context.point.y }; - this.mouseDown = true - }) - - window.addEventListener('mouseup', e => { this.mouseDown = false} ) - el.addEventListener('wheel', this.scale) - el.addEventListener('mousemove', this.pan) - - const rect = grid.getBoundingClientRect() - - this.middle = { - x: rect.width / 2, - y: rect.height / 2 - } - - } - - // UI Editing - context: { - zoom: number, - - minZoom: number, - maxZoom: number, - - start: { - x: number, - y: number - }, - point: { - x: number, - y: number - } - } = { - zoom: 1, - minZoom: 0.6 / window.devicePixelRatio, - maxZoom: 3.0, - start: {x: 0, y: 0}, - point: {x: 0, y: 0} - - } - editing: HTMLElement | null = null - mouseDown:boolean = false - #loaded: boolean = false - - nodes: Map = new Map() - listeners: Map = new Map() - toResolve: Function[] = [] - - // GraphScript Management - graphs: { - context: Graph - active: Graph | GraphNode - } - - // listeners: any = {} - ui?: Element - - #selectElements: any = [] - - propertiesToSubscribe: Set = new Set() - nodePaths: Set = new Set() - - #fIter = 0 - - elements: { - context?: Element, - create?: Element, - grid: HTMLElement - } - - constructor (graph, parentNode?: GraphNodeProperties['parentNode']) { - - // -------------- Create a Hidden Internal Graph -------------- - super({ - __element: 'escode-editor', - __template: html, - __css: style, - useShadow: true, - parentNode - }) - - // this.graph = new Graph({ root: this }) - - this.connect(this) - - // -------------- Setup Keyboard Shortcuts -------------- - document.onkeydown = (e) => { - if (e.ctrlKey && e.code == 'KeyS') { - e.preventDefault() - console.error('Save not defined...') - // app.save() // Global save. - } - }; - - // Set graphs blank if not defined - const contextGraph = new Graph() - this.graphs = { context: contextGraph, active: contextGraph } - // -------------- Set Context Graph -------------- - this.setGraph(graph ?? contextGraph) - - this.createContextMenu() - } - - createContextMenu = () => { - // --------------------------------------------------------------------------------------------------------- - // ------------------------------------- Setting Context Menu Response ------------------------------------- - // --------------------------------------------------------------------------------------------------------- - - if (!context.parentNode) document.body.appendChild(context.__props) - - // Setting Context Menu Responses - context.setResponse(`escode-graph-editor_nodes_${Math.random()}`, { - condition: (path) => { - let returned: any = false - this.nodes.forEach(n => { - if (path.includes(n.__props)) returned = n - }) - return returned - }, - contents: () => { - return [ - { - text: 'Delete', - onclick: (_, node) => { - this.removeNode(node) - } - } - ] - - } - }) - - - context.setResponse(`escode-graph-editor_${Math.random()}`, { - condition: (path) => path.includes(this.__props), - contents: (ev) => { - return [ - { - text: 'Add Component', - onclick: async () => { - - const grid = this.elements.grid - if (grid) { - var rect = grid.getBoundingClientRect(); - var x = ev.clientX - rect.left; //x position within the element. - var y = ev.clientY - rect.top; //y position within the element. - - - console.error('Cannot add a component!') - // // Blur the Background - // const overlay = new Overlay() - - // // Create a Modal - // const modal = new Modal({open: true, header: 'Components', footer: 'All ES Components can be found on the ESCode repository.'}) - // overlay.appendChild(modal) - - // modal.onClose = () => { - // overlay.open = false - // } - - // // Show Node Options in a List - // const result = await new Promise((resolve) => { - - // const list = new Tree({ - // target: this.plugins, - // conditions: { - // value: (o) => !!o.__ // Check if a component - // }, - // onClick: (tag, thing:any) => { - // resolve({tag, info: Object.assign({}, thing)}) // Copying thing so that it doesn't get modified globally - // } // pass a shallow copy onwards - // }) - // modal.appendChild(list) - // document.body.appendChild(overlay) - // // this.workspace.parentNode.appendChild(overlay) - // overlay.open = true - - // }) as any // TODO: Add ES Component types... - - // // Add essential info - // const info = result.info - - // const tag = `${result.tag}_${Math.floor(1000*Math.random())}` // generate tag from plugin - - // // extend info for escode - // delete info?.__escode // delete existing instance-specific info - - // this.workspace.addNode({ tag, info, x, y }) - // modal.open = false - // overlay.open = false - } - }, - }, - // { - // text: 'Do another thing', - // onclick: () => { - // console.warn('MUST DO SOMETHING') - // } - // } - ] - } - }) - } - - - // Set Graph on the Editor and React to Listeners - setGraph = (graph: Editor['graphs']['context']) => { - if (graph) { - - this.graphs.context = graph - this.setActive(graph) - - const nodes = Array.from(graph.__node.nodes.values()) - - this.nodePaths = new Set(nodes.map(o => o.__node.tag)) - this.propertiesToSubscribe = new Set(this.nodePaths) - - nodes.forEach(o => { - const listeners = o.__listeners - if (listeners) { - for (let key in listeners) this.#onListenerAdded(key, listeners[key], o) - } - }) - } else { - this.listeners = new Map() - } - } - - setActive = (node: Editor['graphs']['active']) => { - this.#loaded = false - const active = this.graphs.active = node - const nodes = active.__node.nodes as Editor['graphs']['active']['__node']['nodes'] - - nodes.forEach((n,key) => { - let gN = this.nodes.get(n.__node.tag); - - if (!gN){ - gN = this.addNode({ - tag: key, - info: n, - editor: this - }) - } - }) - - // for (let key in this.graph.edges) { - - // let nodeEdges = this.graph.edges[key] - - // // String shortcut - // if (typeof nodeEdges === 'string') nodeEdges = {[nodeEdges]: true} - - // for (let targetKey in nodeEdges) { - // const info = nodeEdges[targetKey] - // const output = (this.edgeMode === 'from') ? this.match(key) : this.match(targetKey, info) - // const input = (this.edgeMode === 'from') ? this.match(targetKey, info) : this.match(key) - - // const edges = {} - - // // Don't duplicate on construction - // const outTag = output.port.tag - // if (!edges[outTag]) edges[outTag] = [] - // if (!edges[outTag].includes(input.port.tag)){ - - // await this.resolveEdge({ - // info, - // input: input.port, - // output: output.port - // }); - - // edges[outTag].push(input.port.tag) - // } - - // } - // } - // } - - - - - // ---------------------- Auto Layout New Nodes ---------------------- // - let notMoved: any[] = [] - this.nodes.forEach((node) => { - if (node.info.__escode) { - const info = node.info.__escode; - if (info.x === 0 && info.y === 0) notMoved.push(node); - else notMoved.push(node); - } - }); - - this.autolayout(notMoved) - this.#transform() // Move to center - this.#loaded = true - } - - // Exposed method for removing a listener - removeListener = (key, value, bound) => { - console.error('Remove Listener to the graph here...') - this.#onListenerRemoved(key, value, bound) - } - - // Exposed method for adding a listener - addListener = (from, to, bound) => { - console.error('Add Listener to the graph here...') - this.#onListenerAdded(from, to, bound) - } - - // InitializE the editor UI when the UI is ready - setUI = (ui: Element=document.body) => { - if (this.ui) Array.from(this.ui.children).forEach(c => c.remove()) - this.ui = ui - - if (this.ui) { - - const createListenerInfo = this.#createListenerUI() - // Create Listener UI - const create = document.createElement('div') - create.appendChild(createListenerInfo.element) - this.ui.appendChild(create) - this.elements.create = create - - // Show context Listeners - const context = document.createElement('div') - context.id = 'context' - const contextHeader = document.createElement('h3') - contextHeader.innerText = 'context Listeners' - context.appendChild(contextHeader) - this.ui.appendChild(context) - this.elements.context = context - - // Add all listeners to the UI - for (let bound in this.listeners) { - for (let key in this.listeners[bound]) this.listeners[bound][key].forEach(value => this.#addListenerToUI(key, value, bound)) - } - } - } - - // -------------- Internal Event Managers -------------- - #onListenerAdded = (key, value, bound) => { - - bound = (typeof bound !== 'string') ? bound.__node.tag : bound - if (!this.listeners[bound]) this.listeners[bound] = {} - if (!this.listeners[bound][key]) this.listeners[bound][key] = [] - this.listeners[bound][key].push(value) - - if (this.ui) this.#addListenerToUI(key, value, bound) - } - - #onListenerRemoved = (key, value, bound) => { - console.error('Remove Listener from UI' , key, value, bound) - } - - - - // ----------------------------------------------------------- // - // ----------------- Ugly UI Management Code ----------------- // - // ----------------------------------------------------------- // - - #createListenerUI = (from?, value: any = {}, bound?) => { - const noArgs = !from && Object.keys(value).length === 0 && !bound - - const options = this.propertiesToSubscribe - let to = typeof value === 'string' ? value : undefined //value.__output - - const ogOptionsSize = options.size - - // Resolve Callback - const resolvePath = (path) => { - if (!this.nodePaths.has(path)) { - if (typeof path === 'string' && path.includes('FUNCTION_')) path = `${bound}.${path}` - } - return path - } - - const isValid = (path) => typeof path !== 'function' && typeof path !== 'boolean' && typeof path !== 'object' - - const addPathToOptions = (path) => { - if (path && !options.has(path) && isValid(path)) { - path = resolvePath(path) - options.add(path) // Ignore Function or Boolean Callbacks - } - } - - let callback = value.__callback - - if (callback && typeof callback === 'function') { - callback.gsEditorId = this.#fIter - callback = `FUNCTION_${this.#fIter}` // NOTE: These functions are all the same! - this.#fIter++ - } - else if (typeof callback === 'boolean') callback = bound - - // Assign To and Callback - if (callback && to) console.error('Has Both', callback && to) - if (!to) to = callback - addPathToOptions(to) - - const states = {from, to, bound, value} - - const div = document.createElement('div') - div.style.border = '1px solid black' - div.style.padding = '10px' - div.style.position = 'relative' - - let button = document.createElement('button') - if (noArgs) { - button.innerText = 'Create' - button.onclick = () => { - const {from, to, bound, value} = states - if (bound && from) { - console.error('Actually subscribe to the listener here', states) - this.#onListenerAdded(from, value, bound) - } - } - - } else { - button.innerText = 'Remove' - button.onclick = () => { - div.remove() - this.removeListener(from, to, bound) - } - } - - button.style.position = 'absolute' - button.style.top = '0' - button.style.right = '0' - - div.appendChild(button) - - - const fromContainer = document.createElement('div') - const fromLabel = document.createElement('label') - fromLabel.innerText = 'From' - const fromSelect = document.createElement('select') - fromSelect.id = 'from' - fromContainer.appendChild(fromLabel) - fromContainer.appendChild(fromSelect) - - const boundContainer = document.createElement('div') - const boundLabel = document.createElement('label') - boundLabel.innerText = 'Bound To' - const boundSelect = document.createElement('select') - boundSelect.id = 'bound' - boundContainer.appendChild(boundLabel) - boundContainer.appendChild(boundSelect) - - const toContainer = document.createElement('div') - const toLabel = document.createElement('label') - toLabel.innerText = 'To' - const toSelect = document.createElement('select') - toSelect.id = 'to' - toContainer.appendChild(toLabel) - toContainer.appendChild(toSelect) - - const createIO = (value) => { - - const ioStates = {} - const inputContainer = document.createElement('div') - const inputHeader = document.createElement('h4') - inputHeader.innerText = 'Input' - inputContainer.appendChild(inputHeader) - const inputSelect = document.createElement('select') - inputSelect.id = 'input' - inputContainer.appendChild(inputSelect) - - this.#addSelectElement(inputSelect, { - value: value.__input, - onchange: (ev) => { - const value = ev.target.value - this.#onSelectChange(ev, states) - states.value.__input = value - } - }, this.propertiesToSubscribe, true) - - - // array[ind] = output(input(args)) - const argsContainer = document.createElement('div') - const argsHeader = document.createElement('h4') - argsHeader.innerText = 'Arguments' - argsContainer.appendChild(argsHeader) - const argsContained = document.createElement('div') - argsContainer.appendChild(argsContained) - argsContained.style.display = 'flex' - - const createArgs = (args) => { - args.forEach((arg, i) => { - if (typeof arg === 'object') { - const io = createIO(arg) - states.value.__args[i] = io.states - argsContained.appendChild(io.element) - } else { - const argContainer = document.createElement('div') - const argSelect = document.createElement('select') - argContainer.appendChild(argSelect) - argsContained.appendChild(argContainer) - addPathToOptions(arg) - this.#addSelectElement(argSelect, { - value: arg, - onchange: (ev) => { - const value = ev.target.value - this.#onSelectChange(ev, states) - if (!states.value.__args) states.value.__args = [] - states.value.__args[i] = value - } - }, this.propertiesToSubscribe, true) - } - }) - } - - if (value.__args) createArgs(value.__args) - else createArgs([undefined]) - - const output = value.__output - const isSimple = !(output && typeof output === 'object') - - const outputContainer = document.createElement('div') - const outputHeader = document.createElement('h4') - outputHeader.innerText = 'Output' - outputContainer.appendChild(outputHeader) - - let outputValue; - if (isSimple) outputValue = document.createElement('div') - else { - const ioInfo = createIO(output) - outputValue = ioInfo.element - states.value.__output = ioInfo.states - } - - outputContainer.appendChild(outputValue) - if (isSimple) { - - const select = document.createElement('select') - select.id = 'output' - outputContainer.appendChild(select) - - this.#addSelectElement(select, { - value: output, - onchange: (ev) => { - const value = ev.target.value - this.#onSelectChange(ev, states) - states.value.__output = value - } - }, this.propertiesToSubscribe, true) - - // if (hasOutput) outputValue.innerText = output - // else outputValue.innerText = 'N/A' - } else { - states.value.__output - } - - - const ioContainer = document.createElement('div') - ioContainer.appendChild(inputContainer) - ioContainer.appendChild(argsContainer) - ioContainer.appendChild(outputContainer) - return { - element: ioContainer, - states: ioStates - } - } - - const io = createIO(value) - - - div.appendChild(fromContainer) - div.appendChild(boundContainer) - div.appendChild(toContainer) - div.appendChild(io.element) - - if (ogOptionsSize !== options.size) this.#updateSelectElements() - - this.#addSelectElement(fromSelect, { - value: from, - onchange: (ev) => this.#onSelectChange(ev, states, 'from') - }) - - this.#addSelectElement(toSelect, { - value: to, - onchange: (ev) => this.#onSelectChange(ev, states, 'to') - }) - - this.#addSelectElement(boundSelect,{ - value: bound, - onchange: (ev) => this.#onSelectChange(ev, states, 'bound') - }, this.nodePaths) - - return { - element: div, - states - } - } - - #addListenerToUI = (from, value, bound) => { - - const info = this.#createListenerUI(from, value, bound) - - this.elements.context?.appendChild(info.element) - } - - #addSelectElement = (el, configuration, options=this.propertiesToSubscribe, includeOutput = false) => { - - if (typeof configuration !== 'object') configuration = {value: configuration} - - const info = { - el, - configuration, - options, - includeOutput - } - this.#selectElements.push(info) - this.#updateSelectElement(info) - } - - #updateSelectElements = () => this.#selectElements.forEach(o => this.#updateSelectElement(o)) - - #onSelectChange = (ev, states, key?) => { - const value = ev.target.value - const node = this.graphs.active.__node.nodes.get(states.from) - if (node) { - const unique =node.__node.unique - const triggers = this.graphs.active.__node.state.triggers[unique] - if (states.value.sub !== undefined) { - const trigger = triggers[states.value.sub] - console.error('To Update Trigger', value, trigger) - } - } else { - console.error('No Node Found', states) - } - - if (key) states[key] = value - - } - - #updateSelectElement = (info) => { - - const configuration = info.configuration - const value = configuration.value - const el = info.el as HTMLSelectElement - if (el.children.length) Array.from(el.children).forEach(c => c.remove()) - - // Create grayed out selection - const option = document.createElement('option') - option.value = '' - option.innerText = 'N/A' - option.selected = true - option.disabled = true - el.appendChild(option) - - const opts = [...info.options] - if (info.includeOutput) opts.unshift('__output') - - - - opts.forEach(key => { - const option = document.createElement('option') - if (key === value) option.selected = true - option.value = key - option.innerText = key - el.appendChild(option) - }) - - if (configuration.onchange) el.onchange = configuration.onchange - - } - - - // // Events - // onedgeadded?: (edge:GraphEdge) => void = () => {} - // onedgeremoved?: (edge:GraphEdge) => void = () => {} - // onnodeadded?: (node:GraphNode) => void = () => {} - // onnoderemoved?: (node:GraphNode) => void = () => {} - - drag = (item: GraphNode | any) => { - // add drag handler - drag(this, item, () => { - this.resize([item]) - }, () => { - if (!this.editing) this.editing = item - }, () => { - if (this.editing instanceof Node) this.editing = null - }) - } - - resize = (nodes = Array.from(this.nodes.values())) => { - nodes.forEach(node => node.edges.forEach(e => e.resize())) - } - -// Currently laying out nodes in a rough square with more nodes in the columns -autolayout = (nodes: Map | Node[] = this.nodes) => { - let offset = 50 - - nodes = (nodes instanceof Map ? Array.from(nodes.values()) : nodes) as Node[] - - let nPerRow = Math.floor(Math.sqrt(nodes.length)) - - let rowSizes: any[] = [] - let colSizes: any[] = [] - let info: any[] = [] - - nodes.forEach((n, i) => { - - const col = i % nPerRow - const row = Math.floor(i/nPerRow) - - const dimensions = [ - { - value: col, - sizes: colSizes, - dimension: 'height' - }, - { - value: row, - sizes: rowSizes, - dimension: 'width' - } - ] - - const rect = n.node.__props.getBoundingClientRect() - info.push({ - rect, - col, - row - }) - - dimensions.forEach(o => { - let isNew = false - if (o.sizes[o.value] === undefined) { - isNew = true - o.sizes[o.value] = 0 - } - - o.sizes[o.value] += rect[o.dimension] - if (!isNew) o.sizes[o.value] += offset - }) - - }) - - // Set top-left viewport location - const width = this.context.point.x = rowSizes.length ? Math.max(...rowSizes) : 0 - const height = this.context.point.y = colSizes.length ? Math.max(...colSizes) : 0 - - // Actually move nodes - let rowAcc: any[] = [] - let colAcc: any[] = [] - nodes.forEach((n, i) => { - const nInfo = info[i] - - if (colAcc[nInfo.col] === undefined) colAcc[nInfo.col] = 0 - else colAcc[nInfo.col] += offset - - if (rowAcc[nInfo.row] === undefined) rowAcc[nInfo.row] = 0 - else rowAcc[nInfo.row] += offset - - const x = this.middle.x + colAcc[nInfo.col] - width // Set Column - const y = this.middle.y + rowAcc[nInfo.row] - height // Set Row - n.updatePosition(x, y) - - // Update with Shift - rowAcc[nInfo.row] += nInfo.rect.height - colAcc[nInfo.col] += nInfo.rect.width - }) - - - } - - // Behavior - scale = (e) => { - e.preventDefault() - let xs = (e.clientX - this.context.point.x) / this.context.zoom; - let ys = (e.clientY - this.context.point.y) / this.context.zoom; - let delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY); - this.context.zoom = (delta > 0) ? (this.context.zoom * 1.2) : (this.context.zoom / 1.2); - if (this.context.zoom < this.context.minZoom) this.context.zoom = this.context.minZoom // clamp - if (this.context.zoom > this.context.maxZoom) this.context.zoom = this.context.maxZoom // clamp - - - this.context.point.x = e.clientX - xs * this.context.zoom; - this.context.point.y = e.clientY - ys * this.context.zoom; - - this.#transform() - } - - #transform = () => { - const grid = this.elements.grid - if (grid) grid.style['transform'] = `translate(calc(-50% + ${this.context.point.x}px), calc(-50% + ${this.context.point.y}px)) scale(${this.context.zoom*100}%)` - } - - - - pan = (e) => { - - // e.preventDefault(); - - if (!this.editing){ - - if (e.target.parentNode){ - - // Transform relative to Parent - let rectParent = e.target.parentNode.getBoundingClientRect(); - let curXParent = (e.clientX - rectParent.left)/rectParent.width; //x position within the element. - let curYParent = (e.clientY - rectParent.top)/rectParent.height; //y position within the element. - - if (this.mouseDown){ - - this.context.point.x = (e.clientX - this.context.start.x); - this.context.point.y = (e.clientY - this.context.start.y); - this.#transform() - } - this.relXParent = curXParent - this.relYParent = curYParent - } - } - } - - - // ---------------------- Add Nodes and Listeners ---------------------- // - removeNode = (node: string | Node) => { - node = ((typeof node === 'string') ? this.nodes.get(node) : node) as Node - - if ( - this.onnoderemoved instanceof Function // callback is a function - ) this.onnoderemoved(node) - - - // update ui - node.deinit(false) - this.nodes.delete(node.tag) - - } - - addNode = (props: NodeProps) => { - - if (!props.editor) props.editor = this - - // shift position to the middle - if (props.info?.__escode?.x) props.x = props.info.__escode.x - if (props.info?.__escode?.y) props.y = props.info.__escode.y - - // Only run autolayout after UI has rendered - const gN = new Node(props, this.elements.grid) - - this.nodes.set(gN.tag, gN) - - if (this.onnodeadded instanceof Function) this.onnodeadded(gN) - - return gN - } - - resolveEdge = async (info, willAwait=true) => { - - if (this.editing?.tagName === 'escode-listener') { - const component = this.editing as any as Listener // TODO: Fix this - await component.link(info) - return component - } else { - - const tempId = `${Math.round( 10000 * Math.random())}` - const edge = new Listener({editor: this, ...info}, this.elements.grid) - this.editing = edge.graph.__props - - this.edges.setNode(tempId, edge) // Place temp into DOM to trigger edge.rendered - - edge.ready.then(res => { - if (res){ - this.edges.delete(tempId) - this.edges.setNode(edge.id, edge) - edge.resize() - } - }).catch(() => {}) - - if (willAwait) await edge.ready // Wait until the edge is complete - - this.editing = null - return edge - } - } - - - match = (route:string, edgeInfo: any = {}) => { - - let tags = route.split('.') - let match = this.nodes.get(tags[0]); - - if (!match) throw new Error('Node not found: ' + route) - - // If no port name, choose between operator and default - const portName = (tags.length === 1) ? (match.info.__operator ? '__operator' : 'default') : tags.slice(1).join('.'); // fallback to default port - - tags.forEach(t => { - const temp = this.nodes.get(t) - if (temp) match = temp - }) - - let port; - try { - port = match.ports.get(portName); - if (!port) { - // alert('Port not found: ' + route) - port = match.addPort({tag: portName, node: match, value: edgeInfo.target}) - } - } catch (e) { - console.error('failed to get port', e, route, this.nodes) - } - - return { - port, - match - } -} - -} \ No newline at end of file diff --git a/examples/editing/old/editor/context.ts b/examples/editing/old/editor/context.ts deleted file mode 100644 index 6b3b4861..00000000 --- a/examples/editing/old/editor/context.ts +++ /dev/null @@ -1,4 +0,0 @@ -import '../context/ContextMenu' -import { ContextMenu } from '../context/ContextMenu' -export const context = new ContextMenu() -export default context \ No newline at end of file diff --git a/examples/editing/old/editor/index.html b/examples/editing/old/editor/index.html deleted file mode 100644 index 4cb72bce..00000000 --- a/examples/editing/old/editor/index.html +++ /dev/null @@ -1,5 +0,0 @@ -
    -
    - -
    -
    \ No newline at end of file diff --git a/examples/editing/old/editor/listener/Listener.ts b/examples/editing/old/editor/listener/Listener.ts deleted file mode 100644 index 0a559ae8..00000000 --- a/examples/editing/old/editor/listener/Listener.ts +++ /dev/null @@ -1,26 +0,0 @@ -import WebComponent from "../../WebComponent"; - -import style from './styles.css' - -export class Listener extends WebComponent { - - - constructor(props: any, parentNode?: HTMLElement) { - - const html = `` - - super({ - __element: 'escode-listener', - __template: html, - __css: style, - parentNode - }) - - this.connect( - this, - // props.editor.graph - ) - - } - -} \ No newline at end of file diff --git a/examples/editing/old/editor/listener/styles.css b/examples/editing/old/editor/listener/styles.css deleted file mode 100644 index ff40988b..00000000 --- a/examples/editing/old/editor/listener/styles.css +++ /dev/null @@ -1,50 +0,0 @@ -:host * { - box-sizing: border-box; - } - - :host { - display: block; - pointer-events: none; - --grid-color: rgb(210, 210, 210); - } - - :host > div { - width: 100%; - display: flex; - align-items: center; - justify-content: space-between; - font-size:7px; - } - - .input { - transform: translateX(-50%); - left: 0; - } - - .output { - transform: translateX(50%); - right: 0; - } - - .output.hidden { - pointer-events: none; - background: transparent; - } - - .port { - pointer-events: all; - width: 10px; - height: 10px; - background: gray; - cursor: pointer; - border-radius: 10px; - z-index: -1; - } - - @media (prefers-color-scheme: dark) { - - :host { - --grid-color: rgb(45, 45, 45); - } - - } \ No newline at end of file diff --git a/examples/editing/old/editor/node/Node.ts b/examples/editing/old/editor/node/Node.ts deleted file mode 100644 index ddd9016a..00000000 --- a/examples/editing/old/editor/node/Node.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { GraphNode, GraphNodeProperties } from "../../../../../src/core/Graph"; -import WebComponent from "../../../WebComponent"; -import Editor from "../Editor"; -import { Listener } from "../listener/Listener"; -import { PortProps, Port } from "./port/Port"; - -import style from './styles.css' - -export const isPrivate = (key) => key[0] === '_' // NOTE: Is redeclared from common/standards.js - - export type NodeProps = { - editor: Editor - x?: number; - y?: number; - tag?: string, - info: GraphNode; // Add ES Component types... - - __onrender?: GraphNodeProperties['__onrender'] - } - - - -export class Node extends WebComponent { - - // workspace: GraphNodeProps['workspace']; - tag: string; - x: number = 0; - y: number = 0; - info: NodeProps['info']; - edges: Map = new Map() - ports: Map = new Map() - portCategories: { - properties: Map, - components: Map, - default: Map, - } = { - properties: new Map(), - components: new Map(), - default: new Map(), - } - - editor: Editor - portOrder = ['default', 'components', 'properties'] - - elements: { - main: HTMLDivElement - } = { - main: document.createElement('div') - } - - - __onrender(el) { - if (this.info) this.updatePorts() - - // if (!this.editor) this.editor = (this.parentNode.parentNode as any).host - - // add drag handler - this.editor.drag(this) - - this.edges.forEach(e => e.resize()) // resize all edges after - } - - constructor(node: NodeProps, parentNode?: HTMLElement) { - - const html = ` -
    - -
    - ` - - super({ - __element: 'escode-node', - __template: html, - __css: style, - // useShadow: true, - parentNode - }) - - this.elements.main.id = 'ports' - this.elements.main.innerHTML = `
    ` - - // if (node.__onrender) { - // const onrender = this.__onrender - // this.__onrender = (el) => { - // onrender(el) // Old onrender - // node.__onrender(el) - // } - // } - - - this.editor = node.editor - - this.connect( - this, - this.editor.graph - ) - - const container = (this.node.shadowRoot).querySelector('div') - container.appendChild(this.elements.main) - this.setNode(node.info) - } - - updatePosition (x, y) { - if (x !== undefined) this.x = x - if (y !== undefined) this.y = y - this.__props.style.transform = `translate(${this.x}px, ${this.y}px)` - } - - setNode (info) { - this.info = info - if (!this.info.__escode) this.info.__escode = { x: 0, y:0 } // Save ESCode Properties - - this.tag = this.info.__node.tag - this.id = this.info.__node.unique - - this.info.__escode.x = this.x = this.info.__escode.x ?? 0 - this.info.__escode.y = this.y = this.info.__escode.y ?? 0 - this.updatePorts(info) - } - - async updatePorts(info=this.info) { - const notify = (tag, value, type) => { - const got = this.portCategories[type].get(tag) - - if (got === value) console.warn('Redeclared port: ', `${this.tag}.${tag}`) - else { - console.error('Port conflict: ', `${this.tag}.${tag}`) - } - } - - const type = 'properties' - - let n = 0 - Object.keys(info).forEach((tag, i) => { - if (tag.slice(0,2) === '__') return // no __ special properties - if (isPrivate(tag)) return // no underscore (pseudo-private) properties - - let thisType = type - if (tag === 'default' || tag === '__operator') thisType = 'default' - if (this.portCategories?.[thisType]?.has(tag)) { - notify(tag, this.ports.get(tag), thisType) - return - } - console.log('Trying to add', tag, i) - if (n < 20) { - this.addPort({ tag, node: this, type: thisType as 'properties' || 'default'}) - n++ - } - }) - - // Add Port for Each Active ES Component instance (i.e. the internal graph) - const components = info.__children as {[x:string]: GraphNode} - if (components) { - const type = 'children' - Object.keys(components).forEach((tag) => { - if (this.portCategories?.[type]?.has(tag)) { - notify(tag, this.ports.get(tag), type) - return - } - console.log('Adding Port: ', tag, type, this) - this.addPort({ tag, type, node: this }) - }) - } - - } - - willUpdate (updatedProps) { - - if ((updatedProps.has('x') || updatedProps.has('y')) && this.info.__escode){ - this.info.__escode.x = this.x // brainsatplay extension - this.info._escode.y = this.y // brainsatplay extension - } - - if (updatedProps.has('info')) this.updatePorts() - } - - - setEdge (edge) { this.edges.set(edge.id, edge) } - - deleteEdge(id) { - this.edges.delete(id) - } - - #addPortCategory (type: string) { - - let ports = this.elements[type] - - if (!ports) { - this.elements[type] = ports = document.createElement('div') - ports.id = `${type}Ports` - - const idx = this.portOrder.findIndex(str => str === type) - const beforeChild = this.elements.main.children[idx] - if (beforeChild) this.elements.main.insertBefore(ports, beforeChild); - else this.elements.main.appendChild(ports) - } - - return ports - } - - addPort (info: PortProps) { - - const type = info.type ?? 'default' - - const categoryDiv = this.#addPortCategory(type) - const category = this.portCategories[type] ?? this.portCategories.default // Set in type-specific registry - - const port = new Port({ ...info, node: this}) - this.ports.set(port.tag, port) - category.set(port.tag, port) - - console.log('Appending', port) - categoryDiv.appendChild(port.__props) // Append to port category - - - return port - } - - deinit (triggerInWorkspace = true) { - if (triggerInWorkspace) this.editor.removeNode(this) - this.edges.forEach(e => e.deinit()) // Remove edges - this.remove() - } - -} \ No newline at end of file diff --git a/examples/editing/old/editor/node/port/Port.ts b/examples/editing/old/editor/node/port/Port.ts deleted file mode 100644 index d1030ff0..00000000 --- a/examples/editing/old/editor/node/port/Port.ts +++ /dev/null @@ -1,103 +0,0 @@ -import WebComponent from "../../../../WebComponent"; -import { Node } from "../Node"; -export const isListenerPort = (key) => !!key.match(/\[Function_[[0-9]+]/) // TODO: Register in standards somewhere... - -import style from './styles.css' - -export const isPrivate = (key) => key[0] === '_' // NOTE: Is redeclared from common/standards.js - -export type PortProps = { - // tree: {[x:string]: any} - // plot?: Function[], - // onPlot?: Function - // preprocess?: Function, - tag: string - node: Node, - value?: any, - type?: 'properties' | 'children' | 'default' -} - - -export class Port extends WebComponent { - - - node: PortProps['node'] - tag: PortProps['tag'] - type: PortProps['type'] - value: PortProps['value'] - - element: HTMLDivElement - output: HTMLDivElement - input: HTMLDivElement - - - resolving: boolean = false - edges: Map = new Map() - - constructor(port: PortProps, parentNode?: HTMLElement) { - - const tag = port.tag - - const html = ` -
    - ${tag} -
    - ` - - super({ - __element: 'escode-port', - __template: html, - __css: style, - // useShadow: false, - parentNode - }) - - this.node = port.node - this.tag = tag - this.value = port.value - this.type = port.type ?? 'properties' - - this.connect( - this, - this.node.editor.graph, - this.node.node - ) - } - - // updated(changedProperties) { - // this.element = this.shadowRoot.querySelector("div") - // if (!this.node) this.node = (this.parentNode.parentNode.parentNode as any).host - // } - - setEdge = (edge) => { - this.edges.set(edge.id, edge) - this.node.setEdge(edge) // Nodify node - } - - deleteEdge = (id) => { - this.edges.delete(id) - this.node.deleteEdge(id) // Nodify node - } - - resolveEdge = async (ev) => { - if (!this.resolving){ - this.resolving = true - const type = (ev.path[0].classList.contains('input')) ? 'input' : 'output' - if (this.node.workspace) await this.node.workspace.resolveEdge({[type]: this}).catch(e => console.warn(`[escode]: ${e}`)) - this.resolving = false - } - } - - onmousedown = this.resolveEdge - - onmouseup = (ev) => { - const maybeEdge = this.node.workspace.editing - if ( - 'node' in maybeEdge - && 'box' in maybeEdge - && 'svgInfo' in maybeEdge - ) this.resolveEdge(ev) - } - - -} \ No newline at end of file diff --git a/examples/editing/old/editor/node/port/styles.css b/examples/editing/old/editor/node/port/styles.css deleted file mode 100644 index 1f87a85a..00000000 --- a/examples/editing/old/editor/node/port/styles.css +++ /dev/null @@ -1,37 +0,0 @@ -:host * { - box-sizing: border-box; - } - - :host { - pointer-events: none; - width: 100%; - display: flex; - align-items: center; - justify-content: space-between; - font-size:7px; - } - - .input { - transform: translateX(-50%); - left: 0; - } - - .output { - transform: translateX(50%); - right: 0; - } - - .output.hidden { - pointer-events: none; - background: transparent; - } - - .port { - pointer-events: all; - width: 10px; - height: 10px; - background: gray; - cursor: pointer; - border-radius: 10px; - z-index: -1; - } diff --git a/examples/editing/old/editor/node/styles.css b/examples/editing/old/editor/node/styles.css deleted file mode 100644 index bd2cebd2..00000000 --- a/examples/editing/old/editor/node/styles.css +++ /dev/null @@ -1,45 +0,0 @@ -:host { - font-family: var(--escode-font-family, sans-serif); - position: absolute; - box-sizing: border-box; - top: 10px; - left: 10px; - user-select: none; - z-index: 1; -} - -:host>div { - min-width: 50px; - background: rgb(60, 60, 60); -} - -#header { - color: var(--escode-primary-font-color, white); - font-size: 8px; - background: var(--escode-primary-color, black); - padding: 5px; - padding-right: 25px; - font-weight: 800; -} - - -#ports { - min-height: 10px; - color: var(--escode-secondary-font-color, white); - background: var(--escode-secondary-color); -} - -#ports>div:not(:last-child) { - border-bottom: 1px solid var(--escode-secondary-font-color, gray); -} - -#ports escode-graph-port { - padding: 2px 0px; -} - -@media (prefers-color-scheme: dark) { - #header { - color: var(--escode-primary-font-color-dark, var(--escode-primary-font-color, black)); - background: var(--escode-primary-color-dark, var(--escode-primary-color, white)); - } -} \ No newline at end of file diff --git a/examples/editing/old/editor/styles.css b/examples/editing/old/editor/styles.css deleted file mode 100644 index 0419c52b..00000000 --- a/examples/editing/old/editor/styles.css +++ /dev/null @@ -1,54 +0,0 @@ - -:host * { - box-sizing: border-box; - } - - :host { - --escode-dark-background-color: rgb(30, 30, 30); - } - - #container { - width: 100%; - align-items: center; - justify-content: center; - position: relative; - height: 100%; - overflow: hidden; - background: rgb(245, 245, 245); - } - - #grid { - overflow: hidden; - height: 100%; - display: block; - --grid-size: 5000px; - --grid-color: rgb(210, 210, 210); - background: white; - - position: relative; - background-image: - repeating-linear-gradient(var(--grid-color) 0 1px, transparent 1px 100%), - repeating-linear-gradient(90deg, var(--grid-color) 0 1px, transparent 1px 100%); - background-size: 20px 20px; - width: var(--grid-size); - height: var(--grid-size); - } - - #grid:active:hover { - cursor: move; - } - - escode-node { - cursor: move; - } - - @media (prefers-color-scheme: dark) { - :host > * { - background-color: rgb(40, 40, 40); - } - - #grid { - --grid-color: rgb(80, 80, 80); - background: var(--escode-dark-background-color); - } - } \ No newline at end of file diff --git a/examples/editing/old/editor/utils/drag.ts b/examples/editing/old/editor/utils/drag.ts deleted file mode 100644 index c7e2208e..00000000 --- a/examples/editing/old/editor/utils/drag.ts +++ /dev/null @@ -1,91 +0,0 @@ -import Editor from "../Editor"; -import { Node } from "../node/Node"; -import { Port } from "../node/port/Port"; - -const dragElement = (workspace:Editor, dragItem: Node, onMove, onDown,onUp) => { - var active = false; - var currentX; - var currentY; - var initialX; - var initialY; - var xOffset = 0; - var yOffset = 0; - var defaultScale = 1.0 - - // container.addEventListener("touchstart", dragStart, false); - // container.addEventListener("touchend", dragEnd, false); - // container.addEventListener("touchmove", drag, false); - - (dragItem.shadowRoot ?? dragItem).addEventListener("mousedown", dragStart, false); - window.addEventListener("mouseup", dragEnd, false); - window.addEventListener("mousemove", drag, false); - - // let transform = dragItem.style.cssText.match(/transform: ([^;].+);\s?/) // TODO: Check persistence - // let transformString: string - // if (transform) transformString = transform[1] - - // if (transformString) { - // // let scale = transformString.match(/scale\(([^\)].+)\)\s?/) - // // if (scale) scale = scale[1] - // // else scale = 1 - - // let translateString = transformString.match(/translate\(([^\)].+)\)\s?/) - // if (translateString){ - // let arr = translateString[1].split(',') - // xOffset = parseFloat(arr[0].split('px')[0]) - // yOffset = parseFloat(arr[1].split('px')[0]) - // } - // } else { - // dragItem.style.transform = `scale(${defaultScale})`; - // } - - function dragStart(e) { - - const x = dragItem.x - const y = dragItem.y - - if (e.type === "touchstart") { - initialX = (e.touches[0].clientX - (workspace.context.zoom*defaultScale)*x); - initialY = (e.touches[0].clientY - (workspace.context.zoom*defaultScale)*y); - } else { - initialX = (e.clientX - (workspace.context.zoom*defaultScale)*x); - initialY = (e.clientY - (workspace.context.zoom*defaultScale)*y); - } - - // Account For Nested Control Objects - if (dragItem.shadowRoot.contains(e.target)){ - if (!(e.target instanceof Port)) active = true; - onDown() - } - } - - function dragEnd() { - initialX = currentX; - initialY = currentY; - - active = false; - onUp() - } - - function drag(e) { - if (active) { - - e.preventDefault(); - - if (e.type === "touchmove") { - currentX = (e.touches[0].clientX - initialX)/(workspace.context.zoom*defaultScale); - currentY = (e.touches[0].clientY - initialY)/(workspace.context.zoom*defaultScale); - } else { - currentX = (e.clientX - initialX)/(workspace.context.zoom*defaultScale); - currentY = (e.clientY - initialY)/(workspace.context.zoom*defaultScale); - } - - - dragItem.updatePosition(currentX, currentY) - - onMove() - } - } -} - -export default dragElement \ No newline at end of file diff --git a/examples/editing/old/index.html b/examples/editing/old/index.html deleted file mode 100644 index 43496878..00000000 --- a/examples/editing/old/index.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - -
    - -
    - -
    -
    - - - - - \ No newline at end of file diff --git a/examples/editing/old/index.ts b/examples/editing/old/index.ts deleted file mode 100644 index be7d4055..00000000 --- a/examples/editing/old/index.ts +++ /dev/null @@ -1,134 +0,0 @@ -import {Graph} from '../../../src/core/Graph' -import { htmlloader } from '../../../src/loaders/html/html.loader'; -import Editor from './editor/Editor'; -const ui = document.getElementById('ui') // NOTE: This is not becoming the parent node... - -let graph = new Graph({ - loaders:{ - htmlloader - }, - roots:{ - - nodeA:{ - __operator:function add(a,b) { - console.log('run nodeA', a, b); - return a+b; - }, - toAdd:2, - __listeners:{ - 'nodeA':'toAdd' - } - }, - - nodeB:{ - __operator:function multiply(a,b) { - console.log('run nodeB', a, b); - return a*b; - }, - __listeners:{ - 'nodeA':{ __callback:true, __args:['__output', 'nodeA.toAdd'] } - } - }, - - nodeC:{ - __operator:function exponent(a,b) { - console.log('run nodeC', a, b); - return Math.pow(a,b); - }, - __listeners:{ - 'nodeB':{ __callback:true, __args: ['__output',{ - __input:'Math.cos', - __output:{ - __input:'Math.pow', //this returns the final output for the argument list - //__output:(inp)=>{ return inp; } //function or object, etc - __args:['__output', 4] - } - }] } - } - }, - - nodeD:{ - parentNode: ui, // NOTE: This is not rendering... - __element:'div', - innerHTML:'operator output (from child): ', - __operator:function divide(a,b) { - console.log('run nodeD', a, b); - console.log('output:',a/b); - return a/b; - }, - log10:function (a) { - console.log('run nodeD.log10', a); - return Math.log10(a); - }, - __children:{ - output: { - __element:'span', - __operator:function(outp) { - console.log('child node received: ', outp); - this.innerHTML = outp; - }, - } - }, - __listeners:{ - 'nodeC':'log10', - 'nodeD.log10':{ __callback:true, __args:['__output', 3] } - } - }, - - Math - - } -}); - -const list = document.querySelector('#list'); -const editDiv = document.querySelector('#editor'); -const editor = new Editor(graph, editDiv); -if (list) editor.setUI(list) - -// let nodeAInternalSub = graph.subscribe( -// 'nodeA', -// 'nodeA.toAdd' -// ); - -// let nodeBSub = graph.subscribe( -// 'nodeA', -// 'nodeB', -// ['__output','nodeA.toAdd'], -// ); - -// let nodeCSub = graph.subscribe( -// 'nodeB', -// 'nodeC', -// ['__output', { -// __input:'Math.cos', -// __output:{ -// __input:'Math.pow', //this returns the final output for the argument list -// __args:['__output', 4] -// } -// }] -// ); - -// let nodeDSub = graph.subscribe( -// 'nodeC', -// 'nodeD.log10' -// ); - -// let nodeDInternalSub = graph.subscribe( -// 'nodeD.log10', -// 'nodeD', -// ['__output', 3] -// ); - -graph.run('nodeA', 3,4); - -graph.clearListeners('nodeC','nodeB'); - -graph.run('nodeA', 4,5) //should only call nodeB now - - -// const animate = () => { -// graph.run('nodeA', 3,4) //should only call nodeB now -// setTimeout(animate, 100); -// } - -// animate() \ No newline at end of file diff --git a/examples/editing/old/package-lock.json b/examples/editing/old/package-lock.json deleted file mode 100644 index fd55bd66..00000000 --- a/examples/editing/old/package-lock.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "escode", - "version": "0.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "escode", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "devDependencies": {} - } - } -} diff --git a/examples/editing/old/package.json b/examples/editing/old/package.json deleted file mode 100644 index 118c5bc1..00000000 --- a/examples/editing/old/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "escode", - "version": "0.0.0", - "description": "An IDE built in GraphScript", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "Garrett Flynn", - "license": "LGPL-3.0-or-later", - "dependencies": {}, - "devDependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} \ No newline at end of file diff --git a/examples/editing/old/tinybuild.config.js b/examples/editing/old/tinybuild.config.js deleted file mode 100644 index 616f1938..00000000 --- a/examples/editing/old/tinybuild.config.js +++ /dev/null @@ -1,37 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: false, - sourcemap: false, - loader: { '.css':'text', '.html':'text'} - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/editing/package-lock.json b/examples/editing/package-lock.json deleted file mode 100644 index 59fcbc34..00000000 --- a/examples/editing/package-lock.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "tinybuildapp5363", - "version": "0.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "tinybuildapp5363", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "dependencies": { - "litegraph.js": "^0.7.14", - "web-worker": "^1.2.0" - } - }, - "../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.202", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.17.10", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.9.5" - } - }, - "node_modules/litegraph.js": { - "version": "0.7.14", - "resolved": "https://registry.npmjs.org/litegraph.js/-/litegraph.js-0.7.14.tgz", - "integrity": "sha512-xVC0a/D3uLZkpdV/HxyrruDIWM0vMOoIhgaUQXYymQ8pKgbeQZKR0OfuI0c7IpQxC+M/uoc9BRDl2Fm0Q3bW0w==" - }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - } - }, - "dependencies": { - "litegraph.js": { - "version": "0.7.14", - "resolved": "https://registry.npmjs.org/litegraph.js/-/litegraph.js-0.7.14.tgz", - "integrity": "sha512-xVC0a/D3uLZkpdV/HxyrruDIWM0vMOoIhgaUQXYymQ8pKgbeQZKR0OfuI0c7IpQxC+M/uoc9BRDl2Fm0Q3bW0w==" - }, - "web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - } - } -} diff --git a/examples/editing/package.json b/examples/editing/package.json deleted file mode 100644 index fc7fc57e..00000000 --- a/examples/editing/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "tinybuildapp5363", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": { - "litegraph.js": "^0.7.14", - "web-worker": "^1.2.0" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/examples/editing/proxyMenu.ts b/examples/editing/proxyMenu.ts deleted file mode 100644 index 906646e4..00000000 --- a/examples/editing/proxyMenu.ts +++ /dev/null @@ -1,340 +0,0 @@ -//add proxy menu - -import { Graph, getAllProperties } from "../../src/core/Graph"; -import { parseFunctionFromText } from "../../src/services/utils"; -import { LGraph } from "./litegraph.js/src/litegraph"; -import { addNodeToLGraph } from "./litegraphScripts"; - -let inpTypes = { - "string":(p,k,v)=>{ - p[k] = v - return p[k]; - }, - "boolean":(p,k,v)=>{if(v.toLowerCase() === "false" || v === "0" || v === "null") p[k] = false; else p[k] = true; return p[k];}, - "number":(p,k,v)=>{p[k] = parseFloat(v); return p[k];}, - "function":(p,k,v)=>{p[k] = parseFunctionFromText(v); return p[k];}, //evals - "object":(p,k,v)=>{ v.replace("'",'"'); p[k] = JSON.parse(v);}, - "array":(p,k,v)=>{ if(!v.startsWith('[')) v = `[${v}]`; v.replace("'",'"'); p[k]=JSON.parse(v); return p[k]; }, //encapsulate strings in an array - "functionSpreadArgs":(p,k,v)=>{ - if(typeof p[k] === 'function') { - let split = v.split(','); - split.forEach((s,i) => { - if(s.startsWith('function') || s.startsWith('(')) { - parsed[i] = parseFunctionFromText(s); - } - }); - let joined = `[${split.join(',')}]`; - joined.replace("'",'"'); - let parsed = JSON.parse(joined) as any[]; - return p[k](...parsed); - } - } -}; - -export let makeProxyMenu = (proxyable:{[key:string]:any}, graph:Graph, editor:LGraph) => { - let instantiateProxy = (key, args:any[]=[]) => { - let proxy = new proxyable[key](...args); - let keys = getAllProperties(proxy); - return {proxy, keys}; - } - - let container = document.createElement('div'); - let nameInput = document.createElement('input'); - let keydropdown = document.createElement('select'); - let constructorInput = document.createElement('input'); - let constructButton = document.createElement('button'); - constructButton.innerHTML = "Construct"; - - let proxySetupContainer = document.createElement('div'); - let propertydropdown = document.createElement('select'); - let propertyInput = document.createElement('input'); - let setProp = document.createElement('button'); - setProp.innerHTML = "Eval" - let propertyInputType = document.createElement('select'); - let createProxy = document.createElement('button'); - createProxy.innerHTML = "Create Node"; - - - Object.keys(inpTypes).forEach((t,i) => { - propertyInputType.insertAdjacentHTML('beforeend',``) - }); - - container.insertAdjacentHTML('beforeend',`
    Class to instantiate: `); - container.appendChild(keydropdown); - container.insertAdjacentHTML('beforeend',`
    Class constructor args (evals as a spread array): `); - container.appendChild(constructorInput); - container.appendChild(constructButton); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Name Node: `); - proxySetupContainer.appendChild(nameInput); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Class Property: `); - proxySetupContainer.appendChild(propertydropdown); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Property Type: `); - proxySetupContainer.appendChild(propertyInputType); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Input: `); - proxySetupContainer.appendChild(propertyInput); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Set: `); - proxySetupContainer.appendChild(setProp); - proxySetupContainer.insertAdjacentHTML('beforeend',`
    Add to Graph: `); - proxySetupContainer.appendChild(createProxy); - proxySetupContainer.style.display = "none"; - container.appendChild(proxySetupContainer); - - for(const key in proxyable) { - keydropdown.insertAdjacentHTML('beforeend',``); - } - keydropdown.value = ""; - - keydropdown.onchange = (ev) => { - let value = keydropdown.value; - proxySetupContainer.style.display = "none"; - constructButton.onclick = () => { - let args = constructorInput.value as any; - let split = args.split(','); - split.forEach((s,i) => { - if(s.startsWith('function') || s.startsWith('(')) { - parsed[i] = parseFunctionFromText(s); - } - }); - let joined = `[${split.join(',')}]`; - joined = joined.replace(/'/g,'"'); - let parsed = JSON.parse(joined) as any[]; - - let {proxy, keys} = instantiateProxy(value, parsed); - - nameInput.value = `${value}${Math.floor(Math.random()*1000000000000000)}`; - - propertydropdown.innerHTML = ""; - keys.forEach((k) => { - propertydropdown.insertAdjacentHTML('beforeend',``); - }); - propertydropdown.onchange = (ev) => { - let t = typeof proxy[propertydropdown.value]; - propertyInputType.value = t === "undefined" ? "string" : t; - if(t !== 'function') { - propertyInput.value = proxy[propertydropdown.value]; - } else propertyInput.value = ""; - } - setProp.onclick = (ev) => { - if(inpTypes[propertyInputType.value]) - inpTypes[propertyInputType.value](proxy, propertydropdown.value, propertyInput.value) - } - createProxy.onclick = (ev) => { - let props = { - __node:nameInput.value ? { - tag:nameInput.value - } : undefined, - __props:proxy - //todo: could instead list all the non-functional values from proxy here so they get set on the proxy when the node is created - }; - let node = graph.add(props); - addNodeToLGraph(node, graph, editor); - nameInput.value = `${value}${Math.floor(Math.random()*1000000000000000)}`; - } - - proxySetupContainer.style.display = ""; - } - - } - - return container; - -} - - -export let makeNodePropsCreator = (graph:Graph, editor:LGraph) => { - - let container = document.createElement('div'); - let nameInput = document.createElement('input'); - let propsContainer = document.createElement('div'); - let addButton = document.createElement('button'); - addButton.innerHTML = "Add Prop"; - let createButton = document.createElement('button'); - createButton.innerHTML = "Create Node"; - let clearButton = document.createElement('button'); - clearButton.innerHTML = "Clear Props"; - - container.insertAdjacentHTML('beforeend',`
    Name Node: `); - container.appendChild(nameInput); - container.insertAdjacentHTML('beforeend',` -
    Node Properties: {
    key : value
    - `); - container.appendChild(propsContainer); - container.appendChild(addButton); - container.insertAdjacentHTML('beforeend',` -
    }
    - `); - container.appendChild(clearButton); - container.appendChild(createButton); - - clearButton.onclick = () => { - propsContainer.innerHTML = ""; //clear options - } - - let addProp = () => { - let prop = document.createElement('div'); - let keyInput = document.createElement('input'); - keyInput.id = 'key'; - let propInput = document.createElement('input'); - let propInputType = document.createElement('select'); - let delProp = document.createElement('button'); - delProp.innerHTML = 'X'; - delProp.onclick = () => { - prop.remove(); - } - propInputType.id = 'ptype'; - Object.keys(inpTypes).forEach((t,i) => { - if(t !== 'functionSpreadArgs') - propInputType.insertAdjacentHTML('beforeend',``) - }); - propInput.id = 'value'; - prop.appendChild(keyInput); - prop.insertAdjacentHTML('beforeend',':'); - prop.appendChild(propInput); - prop.appendChild(propInputType); - prop.appendChild(delProp); - prop.insertAdjacentHTML('beforeend','
    '); - propsContainer.appendChild(prop); - } - - nameInput.value = `node${Math.floor(Math.random()*1000000000000000)}`; - - addButton.onclick = () => { - addProp(); - } - - createButton.onclick = () => { - let keys = Array.from(propsContainer.querySelectorAll('#key')) as any; - let values = Array.from(propsContainer.querySelectorAll('#value')) as any; - let types = Array.from(propsContainer.querySelectorAll('#ptype')) as any; - - let obj = {} as any; - - keys.forEach((k:any,i) => { - if(k.value) { - if((values[i]).value) { - inpTypes[types[i].value](obj, k.value, values[i].value); - } - } - }); - - let node = graph.add(obj); - addNodeToLGraph(node, graph, editor); - - nameInput.value = `node${Math.floor(Math.random()*1000000000000000)}`; - } - - addProp(); - - return container; - -} - - -export let makeNodeEditorMenu = (graph:Graph, editor?:LGraph) => { - - let container = document.createElement('div'); - let nameInput = document.createElement('input'); - let keydropdown = document.createElement('select'); - let constructorInput = document.createElement('input'); - let constructButton = document.createElement('button'); - constructButton.innerHTML = "Set"; - - let nodeEditorContainer = document.createElement('div'); - let propertydropdown = document.createElement('select'); - let propertyInput = document.createElement('input'); - let setProp = document.createElement('button'); - setProp.innerHTML = "Eval" - let propertyInputType = document.createElement('select'); - //let createProxy = document.createElement('button'); - //createProxy.innerHTML = "Create Node"; - - - Object.keys(inpTypes).forEach((t,i) => { - propertyInputType.insertAdjacentHTML('beforeend',``) - }); - - container.insertAdjacentHTML('beforeend',`
    Select existing node: `); - container.appendChild(keydropdown); - //nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Name Node: `); - //nodeEditorContainer.appendChild(nameInput); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Class Property: `); - nodeEditorContainer.appendChild(propertydropdown); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Property Type: `); - nodeEditorContainer.appendChild(propertyInputType); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Input: `); - nodeEditorContainer.appendChild(propertyInput); - nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Set: `); - nodeEditorContainer.appendChild(setProp); - // nodeEditorContainer.insertAdjacentHTML('beforeend',`
    Add to Graph: `); - // nodeEditorContainer.appendChild(createProxy); - nodeEditorContainer.style.display = "none"; - container.appendChild(nodeEditorContainer); - - - let keys = Array.from(graph.__node.nodes.keys()); - for(const key of keys) { - keydropdown.insertAdjacentHTML('beforeend',``); - } - keydropdown.value = ""; - - keydropdown.onchange = (ev) => { - let value = keydropdown.value; - //nodeEditorContainer.style.display = "none"; - //constructButton.onclick = () => { - let args = constructorInput.value as any; - let split = args.split(','); - split.forEach((s,i) => { - if(s.startsWith('function') || s.startsWith('(')) { - parsed[i] = parseFunctionFromText(s); - } - }); - let joined = `[${split.join(',')}]`; - joined = joined.replace(/'/g,'"'); - let parsed = JSON.parse(joined) as any[]; - - //let {proxy, keys} = instantiateProxy(value, parsed); - - let proxy = graph.get(value); - let pkeys = Object.keys(proxy); - - - - propertydropdown.innerHTML = ""; - pkeys.forEach((k) => { - propertydropdown.insertAdjacentHTML('beforeend',``); - }); - - - propertydropdown.onchange = (ev) => { - let t = typeof proxy[propertydropdown.value]; - propertyInputType.value = t === "undefined" ? "string" : t; - if(t !== 'function') { - propertyInput.value = proxy[propertydropdown.value]; - } else propertyInput.value = ""; - } - setProp.onclick = (ev) => { - if(inpTypes[propertyInputType.value]) - inpTypes[propertyInputType.value](proxy, propertydropdown.value, propertyInput.value) - } - // createProxy.onclick = (ev) => { - // let props = { - // __node:nameInput.value ? { - // tag:nameInput.value - // } : undefined, - // __props:proxy - // //todo: could instead list all the non-functional values from proxy here so they get set on the proxy when the node is created - // }; - // let node = graph.add(props); - // addNodeToLGraph(node, graph, editor); - // nameInput.value = `${value}${Math.floor(Math.random()*1000000000000000)}`; - // } - //} - - nodeEditorContainer.style.display = ""; - - } - - return container; - - -} \ No newline at end of file diff --git a/examples/editing/styles.css b/examples/editing/styles.css deleted file mode 100644 index fd5f015b..00000000 --- a/examples/editing/styles.css +++ /dev/null @@ -1,31 +0,0 @@ -body { - margin: 0; - font-family: Arial, sans-serif; - } - - #editor { - position: relative; - width: 100%; - height: 100vh; - background-color: #eee; - } - - .node { - position: absolute; - padding: 10px; - border: 1px solid #444; - background-color: #fff; - cursor: move; - } - - .connection { - position: absolute; - width: 100%; - height: 100%; - } - - .connection-path { - stroke: #555; - stroke-width: 2px; - fill: none; - } \ No newline at end of file diff --git a/examples/editing/worker.ts b/examples/editing/worker.ts deleted file mode 100644 index 2d624555..00000000 --- a/examples/editing/worker.ts +++ /dev/null @@ -1,29 +0,0 @@ - -//functionality -import { WorkerService, workerCanvasRoutes, remoteGraphRoutes } from '../../index'; - -//wonder if we can have a scheme to dynamic import within the services? e.g. to bring in node-only or browser-only services without additional workers - -declare var WorkerGlobalScope; - -if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { - (self as any).SERVICE = new WorkerService({ - roots:{ - ...workerCanvasRoutes, - ...remoteGraphRoutes, //allows dynamic route loading - console, - mul:function(a,b) { return a * b; }, - - __listeners:{ - console:{ - mul:{ - __callback:'console.log' - } - } - } - } - }); -} - -export default self as any; - diff --git a/examples/advanced/eegnfb/index.css b/examples/eegnfb/index.css similarity index 100% rename from examples/advanced/eegnfb/index.css rename to examples/eegnfb/index.css diff --git a/examples/basics/graph/index.html b/examples/eegnfb/index.html similarity index 100% rename from examples/basics/graph/index.html rename to examples/eegnfb/index.html diff --git a/examples/advanced/eegnfb/index.ts b/examples/eegnfb/index.ts similarity index 98% rename from examples/advanced/eegnfb/index.ts rename to examples/eegnfb/index.ts index 0bfe0778..35d8dcf5 100644 --- a/examples/advanced/eegnfb/index.ts +++ b/examples/eegnfb/index.ts @@ -1,23 +1,23 @@ //@ts-nocheck //resources -import { Service, WorkerCanvas, GraphNodeProperties, loaders, htmlloader, HTMLNodeProperties } from '../..//index'; +import { Service, WorkerCanvas, GraphNodeProperties, loaders, htmlloader, HTMLNodeProperties } from '../../index'; import { initDevice, workers, filterPresets, FilterSettings, chartSettings -} from '../../../device_debugger/src/device.frontend'// +} from 'device-decoder'//'../../../device_debugger/src/device.frontend'// -import { setSignalControls } from '../../src/extras/webgl-plot/webglplot.routes'//'graphscript-services'//'../../extras/webgl-plot/webglplot.routes' +import { setSignalControls } from '../../extras/webgl-plot/webglplot.routes'//'graphscript-services'//'../../extras/webgl-plot/webglplot.routes' -import gsworker from '../../../device_debugger/src/stream.big.worker' //device-decoder/stream.big.worker'; -import { Devices } from '../../../device_debugger/src/devices/third_party/index'// +import gsworker from 'device-decoder/stream.big.worker'//'../../../device_debugger/src/stream.big.worker' //device-decoder/stream.big.worker'; +import { Devices } from 'device-decoder.third-party' // '../../../device_debugger/src/devices/third_party/index'// import { Howl, Howler } from 'howler'; -import { visualizeDirectory } from '../../src/extras/build/storage/index.storage.services'//'graphscript-services/storage/BFS_CSV'; +import { visualizeDirectory } from '../../extras/index.storage.services'//'graphscript-services/storage/BFS_CSV'; import './index.css' @@ -190,7 +190,8 @@ const webappHtml = { //let recording = false; let info = await initDevice( - Devices[mode][selected], + mode as 'BLE'|'USB'|'BLE_OTHER'|'USB_OTHER'|'OTHER', + selected, { devices:Devices, workerUrl:gsworker, @@ -228,7 +229,7 @@ const webappHtml = { } }, - roots:{ //top level tree subscribe to device output thread directly (and workers in top level tree will not use main thread) + tree:{ //top level tree subscribe to device output thread directly (and workers in top level tree will not use main thread) renderer: { workerUrl:gsworker, callback:'updateCanvas', //will pipe data to the canvas animation living alone on this thread @@ -765,6 +766,6 @@ const webappHtml = { } as HTMLNodeProperties } -webapp.load(webappHtml); +webapp.setTree(webappHtml); diff --git a/examples/advanced/eegnfb/package-lock.json b/examples/eegnfb/package-lock.json similarity index 77% rename from examples/advanced/eegnfb/package-lock.json rename to examples/eegnfb/package-lock.json index f86a1b4a..3ac9c60b 100644 --- a/examples/advanced/eegnfb/package-lock.json +++ b/examples/eegnfb/package-lock.json @@ -7,12 +7,12 @@ "": { "name": "tinybuildapp6104", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "browserfs": "^1.4.3", - "device-decoder": "~0.3.3", - "device-decoder.third-party": "~0.1.24", - "graphscript": "~0.2.24", + "device-decoder": "~0.2.40", + "device-decoder.third-party": "~0.1.12", + "graphscript": "~0.2.6", "howler": "~2.2.3" } }, @@ -85,25 +85,25 @@ "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" }, "node_modules/device-decoder": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/device-decoder/-/device-decoder-0.3.3.tgz", - "integrity": "sha512-69MgzxkeCemOFqDIbzux7RuDGp08fcChMYAPaIdKBceO1S4RTEwtjrXwJqbRZIRMSXQBU1ZYsJtfGuXVjKRDZw==", + "version": "0.2.40", + "resolved": "https://registry.npmjs.org/device-decoder/-/device-decoder-0.2.40.tgz", + "integrity": "sha512-MwJtdo5j0sFXajpMSzeBkR3lo5eO4T52j/X8eT8eKEOcaOEd6J4Bqh65RdIULPkproVm1o+eslrvnPm7d1r+Og==", "dependencies": { "@capacitor-community/bluetooth-le": "~2.0.1", - "brainsatplay-math": "~0.1.0", - "graphscript": "~0.2.24", - "graphscript-services": "~0.2.25", - "graphscript-services.gpu": "~0.2.24", - "graphscript-services.storage": "~0.2.24", - "webgl-plot-utils": "~0.3.15" + "brainsatplay-math": "~0.0.25", + "graphscript": "~0.2.6", + "graphscript-services": "~0.2.6", + "graphscript-services.gpu": "~0.2.6", + "graphscript-services.storage": "~0.2.6", + "webgl-plot-utils": "~0.3.13" } }, "node_modules/device-decoder.third-party": { - "version": "0.1.24", - "resolved": "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.24.tgz", - "integrity": "sha512-KA3LY4KZeI3qh8hj0bkdnl316GZRF2rf82fcoa8rryqCpX19GUjDxzjbLwTxZwFMrIv/o6//XwpzBH6+wJzGSA==", + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.12.tgz", + "integrity": "sha512-aq4EAFuR5ELo+cTgS0lv9e5CJCziJPGkBM1EE6Qkk5CNw9H8FgZVz9BHELX3VyeaS1VQ7XIXtXTa5u2pGn+8jQ==", "dependencies": { - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "node_modules/gpujsutils": { @@ -112,52 +112,52 @@ "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" }, "node_modules/graphscript": { - "version": "0.2.24", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.24.tgz", - "integrity": "sha512-uyHUrEb5tobSq4t1kgeNn6f9UEoTSLCA9XHCWbl60A0o228MBb6KXowwN0ZD+Bj0cPbguxldih6aXvXhUvMpmw==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.6.tgz", + "integrity": "sha512-yAitsn3ZovSpqAOwDciCi4MJ3u4G7Z+MY0IZJv4CH4wugc5jmLxm1+FKa4JqeW246eS5hW94F0n3mSMzDQSXYg==", "dependencies": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.11.0" } }, "node_modules/graphscript-services": { - "version": "0.2.25", - "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.25.tgz", - "integrity": "sha512-ZEREWh0AUKbRdwCsvSgonRN3IhF5+x+oWFFHUwHUWFvu2vruI0xiJXXp7hfBIbgUMGpEy9h2OUU6Doe/AELV5w==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.6.tgz", + "integrity": "sha512-bynh8nH0DrJRd9gHLJXsG+JwDpN/Q+NpjOGsLMtegJfwal+aRLL2w6mT7lp4+HKxHoFCslFHcD5xIYhCFV/GbA==", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", "web-worker": "^1.2.0", - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "node_modules/graphscript-services.gpu": { - "version": "0.2.24", - "resolved": "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.24.tgz", - "integrity": "sha512-ktwiPDFgxc7eRRrBwCgaiBD29IvstQS41S4MpbmLLzDj2r1P+R9AUMaTGnBqmi/u1NEfY1+lIVU0mU6U4QYoUA==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.6.tgz", + "integrity": "sha512-3PXpKN1x2cnDBOylhyrEwzV6MF2C83kF37XhMdLMgBv6cGn08GOqSZeF7y5Lbcqf+nO5W3HxQbc4/k5WOCOv8Q==", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.3", "gpujsutils": "~1.0.12", - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "node_modules/graphscript-services.storage": { - "version": "0.2.24", - "resolved": "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.24.tgz", - "integrity": "sha512-qqyJUHDD52Y3uZCmXRGh/oCxLDDzElknK4DShJRmalqqI+ajy81DMGkWeJOqGW450k3IrQDlaD5naxNxGBKd9g==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.6.tgz", + "integrity": "sha512-2wqg9Fbs04IGgTQTrSJwTysD/S+flQE5gA5oRaDkNiWt21XbwEIo8979ipfaauVBIN+yv9DwAzPG8I9XKIW4/Q==", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "node_modules/howler": { @@ -197,9 +197,9 @@ "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" }, "node_modules/webgl-plot-utils": { - "version": "0.3.15", - "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", - "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz", + "integrity": "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==", "dependencies": { "webgl-plot": "~0.7.0" } @@ -282,25 +282,25 @@ "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" }, "device-decoder": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/device-decoder/-/device-decoder-0.3.3.tgz", - "integrity": "sha512-69MgzxkeCemOFqDIbzux7RuDGp08fcChMYAPaIdKBceO1S4RTEwtjrXwJqbRZIRMSXQBU1ZYsJtfGuXVjKRDZw==", + "version": "0.2.40", + "resolved": "https://registry.npmjs.org/device-decoder/-/device-decoder-0.2.40.tgz", + "integrity": "sha512-MwJtdo5j0sFXajpMSzeBkR3lo5eO4T52j/X8eT8eKEOcaOEd6J4Bqh65RdIULPkproVm1o+eslrvnPm7d1r+Og==", "requires": { "@capacitor-community/bluetooth-le": "~2.0.1", - "brainsatplay-math": "~0.1.0", - "graphscript": "~0.2.24", - "graphscript-services": "~0.2.25", - "graphscript-services.gpu": "~0.2.24", - "graphscript-services.storage": "~0.2.24", - "webgl-plot-utils": "~0.3.15" + "brainsatplay-math": "~0.0.25", + "graphscript": "~0.2.6", + "graphscript-services": "~0.2.6", + "graphscript-services.gpu": "~0.2.6", + "graphscript-services.storage": "~0.2.6", + "webgl-plot-utils": "~0.3.13" } }, "device-decoder.third-party": { - "version": "0.1.24", - "resolved": "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.24.tgz", - "integrity": "sha512-KA3LY4KZeI3qh8hj0bkdnl316GZRF2rf82fcoa8rryqCpX19GUjDxzjbLwTxZwFMrIv/o6//XwpzBH6+wJzGSA==", + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.12.tgz", + "integrity": "sha512-aq4EAFuR5ELo+cTgS0lv9e5CJCziJPGkBM1EE6Qkk5CNw9H8FgZVz9BHELX3VyeaS1VQ7XIXtXTa5u2pGn+8jQ==", "requires": { - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "gpujsutils": { @@ -309,52 +309,52 @@ "integrity": "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" }, "graphscript": { - "version": "0.2.24", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.24.tgz", - "integrity": "sha512-uyHUrEb5tobSq4t1kgeNn6f9UEoTSLCA9XHCWbl60A0o228MBb6KXowwN0ZD+Bj0cPbguxldih6aXvXhUvMpmw==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.6.tgz", + "integrity": "sha512-yAitsn3ZovSpqAOwDciCi4MJ3u4G7Z+MY0IZJv4CH4wugc5jmLxm1+FKa4JqeW246eS5hW94F0n3mSMzDQSXYg==", "requires": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.11.0" } }, "graphscript-services": { - "version": "0.2.25", - "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.25.tgz", - "integrity": "sha512-ZEREWh0AUKbRdwCsvSgonRN3IhF5+x+oWFFHUwHUWFvu2vruI0xiJXXp7hfBIbgUMGpEy9h2OUU6Doe/AELV5w==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.6.tgz", + "integrity": "sha512-bynh8nH0DrJRd9gHLJXsG+JwDpN/Q+NpjOGsLMtegJfwal+aRLL2w6mT7lp4+HKxHoFCslFHcD5xIYhCFV/GbA==", "requires": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", "web-worker": "^1.2.0", - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "graphscript-services.gpu": { - "version": "0.2.24", - "resolved": "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.24.tgz", - "integrity": "sha512-ktwiPDFgxc7eRRrBwCgaiBD29IvstQS41S4MpbmLLzDj2r1P+R9AUMaTGnBqmi/u1NEfY1+lIVU0mU6U4QYoUA==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.6.tgz", + "integrity": "sha512-3PXpKN1x2cnDBOylhyrEwzV6MF2C83kF37XhMdLMgBv6cGn08GOqSZeF7y5Lbcqf+nO5W3HxQbc4/k5WOCOv8Q==", "requires": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.3", "gpujsutils": "~1.0.12", - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "graphscript-services.storage": { - "version": "0.2.24", - "resolved": "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.24.tgz", - "integrity": "sha512-qqyJUHDD52Y3uZCmXRGh/oCxLDDzElknK4DShJRmalqqI+ajy81DMGkWeJOqGW450k3IrQDlaD5naxNxGBKd9g==", + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.6.tgz", + "integrity": "sha512-2wqg9Fbs04IGgTQTrSJwTysD/S+flQE5gA5oRaDkNiWt21XbwEIo8979ipfaauVBIN+yv9DwAzPG8I9XKIW4/Q==", "requires": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", "bson-objectid": "~2.0.4", "gpujsutils": "~1.0.12", - "webgl-plot-utils": "~0.3.15" + "webgl-plot-utils": "~0.3.13" } }, "howler": { @@ -394,9 +394,9 @@ "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" }, "webgl-plot-utils": { - "version": "0.3.15", - "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.15.tgz", - "integrity": "sha512-OXPhrDATC4VVHVA4ySnxmvoSenNz/GNeX1e0vqPVyYt9l9bCSeZOou8tfOIAh5NoJ8UXZoq1yBNShLzwYAi8BA==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz", + "integrity": "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==", "requires": { "webgl-plot": "~0.7.0" } diff --git a/examples/advanced/eegnfb/package.json b/examples/eegnfb/package.json similarity index 88% rename from examples/advanced/eegnfb/package.json rename to examples/eegnfb/package.json index acee93e6..c909f58d 100644 --- a/examples/advanced/eegnfb/package.json +++ b/examples/eegnfb/package.json @@ -20,12 +20,12 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "browserfs": "^1.4.3", - "device-decoder": "~0.4.3", - "device-decoder.third-party": "~0.2.2", - "graphscript": "~0.2.26", + "device-decoder": "~0.2.43", + "device-decoder.third-party": "~0.1.15", + "graphscript": "~0.2.19", "howler": "~2.2.3" }, "nodemonConfig": { diff --git a/examples/advanced/eegnfb/src/assets/kalimba.wav b/examples/eegnfb/src/assets/kalimba.wav similarity index 100% rename from examples/advanced/eegnfb/src/assets/kalimba.wav rename to examples/eegnfb/src/assets/kalimba.wav diff --git a/examples/advanced/eegnfb/src/assets/phonk.wav b/examples/eegnfb/src/assets/phonk.wav similarity index 100% rename from examples/advanced/eegnfb/src/assets/phonk.wav rename to examples/eegnfb/src/assets/phonk.wav diff --git a/examples/advanced/eegnfb/src/assets/synthflute.wav b/examples/eegnfb/src/assets/synthflute.wav similarity index 100% rename from examples/advanced/eegnfb/src/assets/synthflute.wav rename to examples/eegnfb/src/assets/synthflute.wav diff --git a/examples/advanced/eegnfb/tinybuild.config.js b/examples/eegnfb/tinybuild.config.js similarity index 100% rename from examples/advanced/eegnfb/tinybuild.config.js rename to examples/eegnfb/tinybuild.config.js diff --git a/examples/eegnfb/yarn.lock b/examples/eegnfb/yarn.lock new file mode 100644 index 00000000..f7f59116 --- /dev/null +++ b/examples/eegnfb/yarn.lock @@ -0,0 +1,178 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@capacitor-community/bluetooth-le@~2.0.1": + "integrity" "sha512-K8NOAvzHKdwy+Ql9Y8hvtZh5gj5pnleAD8Q89HM9FDMbTsZmyBID0FcPGJxAZVRAb9VuaID3YykluRM7Up27ew==" + "resolved" "https://registry.npmjs.org/@capacitor-community/bluetooth-le/-/bluetooth-le-2.0.1.tgz" + "version" "2.0.1" + dependencies: + "@types/web-bluetooth" "^0.0.15" + "throat" "^6.0.1" + +"@capacitor/core@^4.0.0": + "integrity" "sha512-zb225feaiHYcttHqw7SnKVj9gjOh3yoM2ol0Efky4kd80qZvqPHt7nRI1XZmGUKid5j3AVggULd5rRke5OEOXQ==" + "resolved" "https://registry.npmjs.org/@capacitor/core/-/core-4.3.0.tgz" + "version" "4.3.0" + dependencies: + "tslib" "^2.1.0" + +"@types/web-bluetooth@^0.0.15": + "integrity" "sha512-w7hEHXnPMEZ+4nGKl/KDRVpxkwYxYExuHOYXyzIzCDzEZ9ZCGMAewulr9IqJu2LR4N37fcnb1XVeuZ09qgOxhA==" + "resolved" "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.15.tgz" + "version" "0.0.15" + +"async@^2.1.4": + "integrity" "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==" + "resolved" "https://registry.npmjs.org/async/-/async-2.6.4.tgz" + "version" "2.6.4" + dependencies: + "lodash" "^4.17.14" + +"better-sse@~0.8.0": + "integrity" "sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA==" + "resolved" "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz" + "version" "0.8.0" + +"brainsatplay-math@~0.0.25": + "integrity" "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" + "resolved" "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz" + "version" "0.0.25" + +"browserfs@^1.4.3": + "integrity" "sha512-tz8HClVrzTJshcyIu8frE15cjqjcBIu15Bezxsvl/i+6f59iNCN3kznlWjz0FEb3DlnDx3gW5szxeT6D1x0s0w==" + "resolved" "https://registry.npmjs.org/browserfs/-/browserfs-1.4.3.tgz" + "version" "1.4.3" + dependencies: + "async" "^2.1.4" + "pako" "^1.0.4" + +"bson-objectid@~2.0.3", "bson-objectid@~2.0.4": + "integrity" "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + "resolved" "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz" + "version" "2.0.4" + +"device-decoder.third-party@~0.1.12": + "integrity" "sha512-aq4EAFuR5ELo+cTgS0lv9e5CJCziJPGkBM1EE6Qkk5CNw9H8FgZVz9BHELX3VyeaS1VQ7XIXtXTa5u2pGn+8jQ==" + "resolved" "https://registry.npmjs.org/device-decoder.third-party/-/device-decoder.third-party-0.1.12.tgz" + "version" "0.1.12" + dependencies: + "webgl-plot-utils" "~0.3.13" + +"device-decoder@~0.2.40": + "integrity" "sha512-MwJtdo5j0sFXajpMSzeBkR3lo5eO4T52j/X8eT8eKEOcaOEd6J4Bqh65RdIULPkproVm1o+eslrvnPm7d1r+Og==" + "resolved" "https://registry.npmjs.org/device-decoder/-/device-decoder-0.2.40.tgz" + "version" "0.2.40" + dependencies: + "@capacitor-community/bluetooth-le" "~2.0.1" + "brainsatplay-math" "~0.0.25" + "graphscript" "~0.2.6" + "graphscript-services" "~0.2.6" + "graphscript-services.gpu" "~0.2.6" + "graphscript-services.storage" "~0.2.6" + "webgl-plot-utils" "~0.3.13" + +"gpujsutils@~1.0.12": + "integrity" "sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q==" + "resolved" "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.12.tgz" + "version" "1.0.12" + +"graphscript-services.gpu@~0.2.6": + "integrity" "sha512-3PXpKN1x2cnDBOylhyrEwzV6MF2C83kF37XhMdLMgBv6cGn08GOqSZeF7y5Lbcqf+nO5W3HxQbc4/k5WOCOv8Q==" + "resolved" "https://registry.npmjs.org/graphscript-services.gpu/-/graphscript-services.gpu-0.2.6.tgz" + "version" "0.2.6" + dependencies: + "brainsatplay-math" "~0.0.25" + "browserfs" "^1.4.3" + "bson-objectid" "~2.0.3" + "gpujsutils" "~1.0.12" + "webgl-plot-utils" "~0.3.13" + +"graphscript-services.storage@~0.2.6": + "integrity" "sha512-2wqg9Fbs04IGgTQTrSJwTysD/S+flQE5gA5oRaDkNiWt21XbwEIo8979ipfaauVBIN+yv9DwAzPG8I9XKIW4/Q==" + "resolved" "https://registry.npmjs.org/graphscript-services.storage/-/graphscript-services.storage-0.2.6.tgz" + "version" "0.2.6" + dependencies: + "brainsatplay-math" "~0.0.25" + "browserfs" "^1.4.3" + "bson-objectid" "~2.0.4" + "gpujsutils" "~1.0.12" + "webgl-plot-utils" "~0.3.13" + +"graphscript-services@~0.2.6": + "integrity" "sha512-bynh8nH0DrJRd9gHLJXsG+JwDpN/Q+NpjOGsLMtegJfwal+aRLL2w6mT7lp4+HKxHoFCslFHcD5xIYhCFV/GbA==" + "resolved" "https://registry.npmjs.org/graphscript-services/-/graphscript-services-0.2.6.tgz" + "version" "0.2.6" + dependencies: + "brainsatplay-math" "~0.0.25" + "browserfs" "^1.4.3" + "bson-objectid" "~2.0.4" + "gpujsutils" "~1.0.12" + "web-worker" "^1.2.0" + "webgl-plot-utils" "~0.3.13" + +"graphscript@~0.2.6": + "integrity" "sha512-yAitsn3ZovSpqAOwDciCi4MJ3u4G7Z+MY0IZJv4CH4wugc5jmLxm1+FKa4JqeW246eS5hW94F0n3mSMzDQSXYg==" + "resolved" "https://registry.npmjs.org/graphscript/-/graphscript-0.2.6.tgz" + "version" "0.2.6" + dependencies: + "better-sse" "~0.8.0" + "brainsatplay-math" "~0.0.25" + "bson-objectid" "~2.0.3" + "web-worker" "~1.2.0" + "ws" "~8.11.0" + +"howler@~2.2.3": + "integrity" "sha512-QM0FFkw0LRX1PR8pNzJVAY25JhIWvbKMBFM4gqk+QdV+kPXOhleWGCB6AiAF/goGjIHK2e/nIElplvjQwhr0jg==" + "resolved" "https://registry.npmjs.org/howler/-/howler-2.2.3.tgz" + "version" "2.2.3" + +"lodash@^4.17.14": + "integrity" "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + "resolved" "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" + "version" "4.17.21" + +"pako@^1.0.4": + "integrity" "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" + "resolved" "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz" + "version" "1.0.11" + +"throat@^6.0.1": + "integrity" "sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==" + "resolved" "https://registry.npmjs.org/throat/-/throat-6.0.1.tgz" + "version" "6.0.1" + +"tinybuild@file:../../../../../AppData/Roaming/npm/node_modules/tinybuild": + "resolved" "file:../../../../../AppData/Roaming/npm/node_modules/tinybuild" + "version" "0.3.190" + dependencies: + "chokidar" "~3.5.3" + "esbuild" "~0.14.49" + "ws" "^8.5.0" + +"tslib@^2.1.0": + "integrity" "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" + "resolved" "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz" + "version" "2.4.0" + +"web-worker@^1.2.0", "web-worker@~1.2.0": + "integrity" "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" + "resolved" "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz" + "version" "1.2.0" + +"webgl-plot-utils@~0.3.13": + "integrity" "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==" + "resolved" "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz" + "version" "0.3.13" + dependencies: + "webgl-plot" "~0.7.0" + +"webgl-plot@~0.7.0": + "integrity" "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + "resolved" "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz" + "version" "0.7.0" + +"ws@~8.11.0": + "integrity" "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==" + "resolved" "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz" + "version" "8.11.0" diff --git a/examples/graph/components/nodeA.js b/examples/graph/components/nodeA.js new file mode 100644 index 00000000..9e0984f7 --- /dev/null +++ b/examples/graph/components/nodeA.js @@ -0,0 +1,3 @@ +export const x = 1 +export const y = 2 +export const jump = ()=>{console.log('jump!'); return 'jumped!'; } \ No newline at end of file diff --git a/examples/graph/components/nodeB.js b/examples/graph/components/nodeB.js new file mode 100644 index 00000000..b186caa0 --- /dev/null +++ b/examples/graph/components/nodeB.js @@ -0,0 +1,4 @@ +import * as nodeC from './nodeC.js' + +export const x = 3 +export const y = 4 \ No newline at end of file diff --git a/examples/graph/components/nodeC.js b/examples/graph/components/nodeC.js new file mode 100644 index 00000000..d1dbb271 --- /dev/null +++ b/examples/graph/components/nodeC.js @@ -0,0 +1 @@ +export const z = 4 \ No newline at end of file diff --git a/examples/graph/components/nodeD.js b/examples/graph/components/nodeD.js new file mode 100644 index 00000000..3cd6bcbc --- /dev/null +++ b/examples/graph/components/nodeD.js @@ -0,0 +1 @@ +export default (a,b,c)=>{ return a+b+c; } \ No newline at end of file diff --git a/examples/loaders/web_components/components/node/node.html b/examples/graph/components/nodeE.js similarity index 100% rename from examples/loaders/web_components/components/node/node.html rename to examples/graph/components/nodeE.js diff --git a/examples/graph/components/tree.js b/examples/graph/components/tree.js new file mode 100644 index 00000000..12147ed6 --- /dev/null +++ b/examples/graph/components/tree.js @@ -0,0 +1,33 @@ +import * as nodeA from './nodeA.js' +import * as nodeB from './nodeB.js' +import * as nodeC from './nodeC.js' +import * as nodeD from './nodeD.js' + +export const esDOM = { + nodeA, + nodeB: { + esCompose: nodeB, + esDOM: { + nodeC: { + esCompose: nodeC, + default: function(a) { this.z += a; console.log('nodeC z prop added to',this); return this.z; } + } + } + }, + + nodeD, + + nodeE: { + esAnimate: 1, + default: () => {console.log('looped!');} + } +} + +export const esListeners = { + '': { + 'nodeA.x':function(newX) { console.log('nodeA x prop updated', newX);}, + 'nodeA.jump':function(jump) { + console.log('nodeA ', jump); + } + } +} \ No newline at end of file diff --git a/examples/graph/index.html b/examples/graph/index.html new file mode 100644 index 00000000..8f21b3b1 --- /dev/null +++ b/examples/graph/index.html @@ -0,0 +1,40 @@ + + + + + + + +
      + + + + \ No newline at end of file diff --git a/examples/graph/index.js b/examples/graph/index.js new file mode 100644 index 00000000..5cbe5b46 --- /dev/null +++ b/examples/graph/index.js @@ -0,0 +1,157 @@ + +// import { Graph } from "../../core/Graph"; +import { Graph } from "../../core/Graph2"; +import { loaders } from "../../core/loaders"; +import list from "./list"; +import tree from './tree' + +const nodeAInstance = tree.nodeA + +let graph = new Graph({ + tree, + loaders:{ + ...loaders + } +}); + + +const commands = [ + { + name: 'graph.run("nodeG")', + function: () => { + graph.run('nodeG'); + }, + }, + { + name: 'nodeAInstance.x = 1', + function: () => { + nodeAInstance.x = 1; //should trigger nodeA.x listener on nodeC + }, + }, + { + name: `graph.get('nodeA').x = 2`, + function: () => { + graph.get('nodeA').x = 2; //same thing + }, + }, + { + name: `graph.get('nodeB').x += 1`, + function: () => { + graph.get('nodeB').x += 1; //should trigger nodeA listener jump() + + }, + }, + { + header: `Clear All Listeners`, + ignore: true, + function: () => { + graph.clear() // NEW FEATURE: Clear all listeners + } + }, + { + name: `graph.run('nodeB.nodeC', 4)`, + function: () => { + graph.run('nodeB.nodeC', 4); + }, + }, + { + name: `graph.get('nodeB.nodeC').z += 1`, + function: () => { + graph.get('nodeB.nodeC').z += 1; + }, + }, + { + name: `graph.get('nodeA').jump()`, + function: () => { + graph.get('nodeA').jump(); //should trigger nodeC listener + }, + }, + { + header: `Unsubscribe nodeB.nodeC from nodeA.jump`, + ignore: true, + function: () => { + // NEW FEATURE: Clearing nodeC listener from nodeA.jump + graph.unsubscribe('nodeB.nodeC', 'nodeA.jump') + // graph.clear('nodeA.jump') // Equivalent + } + }, + + { + name: `graph.run('nodeA.jump')`, + function: () => { + graph.run('nodeA.jump'); //same + } + }, + { + header: 'Use Graph2 (commented)', + function: () => { + + + let tree2 = { + graph + }; + + let graph2 = new Graph({tree:tree2}); + console.log('Got Graph 2', graph2) + + list.addHeader('Remove nodeB') + let popped = graph.remove('nodeB'); + // let popped = graph.get('nodeB'); + console.log(popped.__node.tag, 'popped') + + list.addCommand(`graph.get('nodeA').jump()`) + graph.get('nodeA').jump(); //should not trigger nodeC listener + + // // NOTE: Does nothing for now... + // graph2.add(popped); //reparent nodeB to the parent graph + // const secondMessage = 'nodeB + graph2' + // list.addHeader(secondMessage) + // console.log(secondMessage,popped,graph2); + + list.addCommand(`popped.x += 1`) + popped.x += 1; //should no longer trigger nodeA.x listener on nodeC NOR the nodeB.x listener on nodeA + + list.addCommand(`popped.__children.nodeC.__operator(1)`) + popped.__children.nodeC.__operator(1); + + list.addCommand(`graph.get('nodeA').jump()`) + graph.get('nodeA').jump(); //this should not trigger the nodeA.jump listener on nodeC now + + + } + } +] + +list.addHeader('Got Graph1') +console.log('graph',graph); + +const runCommand = (command = commands.shift()) => { + if (command) { + if (command.ignore) return runCommand() + else { + if (command.header) list.addHeader(command.header) + if (command.name) list.addCommand(command.name) + command.function() + } + } +} + +const runAll = () => { + const copy = [...commands] + copy.forEach(() => runCommand()) +} + +window.onkeydown = (ev) => { + const key = ev.key + if (key === 'Enter') runCommand() + else if (key === ' ') runAll() +} + +// Automatically run everything +runAll() + +// Stop animating after a few seconds +setTimeout(()=>{ + graph.remove('nodeE'); + list.addCommand('nodeE removed!') +},5500) diff --git a/examples/graph/list.js b/examples/graph/list.js new file mode 100644 index 00000000..3c027726 --- /dev/null +++ b/examples/graph/list.js @@ -0,0 +1,19 @@ +export default { + element: document.querySelector('ol'), + add: function (message) { + var li = document.createElement('li'); + li.innerText = message; + this.element.appendChild(li); + }, + addCommand: function (message) { + var li = document.createElement('div'); + li.innerText = message; + li.style.fontWeight = 'bold'; + this.element.appendChild(li); + }, + addHeader: function (message) { + var li = document.createElement('h3'); + li.innerText = message; + this.element.appendChild(li); + }, +} \ No newline at end of file diff --git a/examples/graph/nodes/nodeA.js b/examples/graph/nodes/nodeA.js new file mode 100644 index 00000000..0737e543 --- /dev/null +++ b/examples/graph/nodes/nodeA.js @@ -0,0 +1,37 @@ +import list from '../list' + + +export const x = 5 +export const y = 2 + +export const jump = ()=>{ + const message = `jump!` + list.add(message) + console.log(message); + return 'jumped!'; +} + +//listeners in a scope are bound to 'this' node +export const __listeners = { + 'nodeB.nodeC':function(op_result){ + const message = 'nodeA listener: nodeC operator returned:' + list.add(message) + console.log(message, op_result, this.__node.tag) + }, + 'nodeB.nodeC.z':function(newZ){ + const message = 'nodeA listener: nodeC z prop changed:' + list.add(message) + console.log(message, newZ, this.__node.tag) + }, + + // ---------- Equivalent Decarations ---------- + // From —> To + // 'nodeB.x':'jump', + // 'nodeE': 'jump', + + // To —> From + 'jump': { + 'nodeE': true, + 'nodeB.x': true + } +} \ No newline at end of file diff --git a/examples/basics/sync_async/package.json b/examples/graph/package.json similarity index 94% rename from examples/basics/sync_async/package.json rename to examples/graph/package.json index 77af2ce0..e4a6e7a7 100644 --- a/examples/basics/sync_async/package.json +++ b/examples/graph/package.json @@ -1,5 +1,5 @@ { - "name": "tinybuildapp442", + "name": "tinybuildapp1331", "version": "0.0.0", "description": "Barebones esbuild and test node server implementation. For building", "main": "index.js", @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": {}, "devDependencies": {}, "nodemonConfig": { diff --git a/examples/graph/tinybuild.config.js b/examples/graph/tinybuild.config.js new file mode 100644 index 00000000..fbba9740 --- /dev/null +++ b/examples/graph/tinybuild.config.js @@ -0,0 +1,36 @@ +const config = { + bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) + entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types + "index.js" + ], + outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags + //outdir:[] //exit point files, define for multiple bundle files + bundleBrowser: true, //create plain js build? Can include globals and init scripts + bundleESM: false, //create esm module js files + bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) + bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files + bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. + minify: false, + sourcemap: false + //globalThis:null //'mymodule' + //globals:{'index.js':['Graph']} + //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) + }, + server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) + debug: false, + protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well + host: "localhost", //'localhost' or '127.0.0.1' etc. + port: 8081, //e.g. port 80, 443, 8000 + startpage: "index.html", //home page + socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost + hotreload: 5001, //hotreload websocket server port + //watch: ['../'], //watch additional directories other than the current working directory + pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) + python: false,//7000, //quart server port (configured via the python server script file still) + python__node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) + errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. + certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions + keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions + } +} +export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/graph/tree.js b/examples/graph/tree.js new file mode 100644 index 00000000..fcdf4cfd --- /dev/null +++ b/examples/graph/tree.js @@ -0,0 +1,82 @@ +import * as nodeA from './nodes/nodeA.js' +import list from './list' + +const nodeAInstance = Object.assign({}, nodeA) + +class nodeClass { //treated as a class to instance rather than a function to set as __operator + __operator = () => { + const message = 'class instanced node called!' + list.add(message) + console.log(message); + } +} + +let tree = { + + nodeA: nodeAInstance, + + nodeB:{ + x:3, + y:4, + __children:{ + nodeC:{ + z:4, + __operator:function(a) { + this.z += a; + const message = 'nodeC operator: nodeC z prop added to' + list.add(message) + console.log(message, this.__node.tag); + return this.z; + }, + __listeners:{ + 'nodeA.x':function(newX) { + const message = 'nodeC listener: nodeA x prop updated' + list.add(message) + console.log(message, newX); + }, + 'nodeA.jump':function(jump) { + const message = 'nodeC listener: nodeA ' + list.add(message) + console.log(message, jump); + } + } + } + } + + }, + + nodeD:(a,b,c)=>{ return a+b+c; }, //becomes the .__operator prop and calling triggers setState for this tag (or nested tag if a child) + + + nodeE:{ + __operator:function (){ + const message = 'looped' + list.add(message) + console.log(message); + return true; + }, + __node:{ + loop:1000, + looping:true + } + }, + + nodeF:{ + __props:document.createElement('div'), //properties on the '__props' object will be proxied and mutatable as 'this' on the node. E.g. for representing HTML elements + __onconnected:function (node) { + this.innerHTML = 'Test'; + this.style.backgroundColor = 'green'; + document.body.appendChild(this.__props); + console.log(this,this.__props); + }, + __ondisconnected:function(node) { + document.body.removeChild(this.__props); + } + + }, + + nodeG: nodeClass + +}; + +export default tree \ No newline at end of file diff --git a/examples/basics/listeners/index.html b/examples/html/index.html similarity index 100% rename from examples/basics/listeners/index.html rename to examples/html/index.html diff --git a/examples/loaders/html/index.ts b/examples/html/index.ts similarity index 53% rename from examples/loaders/html/index.ts rename to examples/html/index.ts index c47c7984..7252095b 100644 --- a/examples/loaders/html/index.ts +++ b/examples/html/index.ts @@ -1,24 +1,7 @@ -import { - Graph, - wchtmlloader, //includes a web component library for custom html elements - htmlloader, //basic html elements - HTMLNodeProperties -} from '../../../index' +import { htmlloader, HTMLNodeProperties } from '../../core/loaders/html/html.loader'; +import { Graph } from '../../index.core' -let component = { - __template:`
      Hello world!
      `, - __element:'web-component', - __onrender:function (elm){ - console.log('rendered!'); - (document.getElementById('wcdiv') as HTMLElement).onclick = (ev) => { - if((ev.target as HTMLElement).style.backgroundColor !== 'red') - setTimeout(()=>{(ev.target as HTMLElement).style.backgroundColor = '';},1000); - (ev.target as HTMLElement).style.backgroundColor = 'red'; - } - } -} as HTMLNodeProperties - -let roots = { +let tree = { mainbody:{ __element:'div', @@ -42,15 +25,25 @@ let roots = { ev.target.innerHTML = 'Clicked!'; } } as HTMLNodeProperties, - component + component:{ + __template:`
      Hello world!
      `, + __element:'web-component', + __onrender:function (elm){ + console.log('rendered!'); + (document.getElementById('wcdiv') as HTMLElement).onclick = (ev) => { + if((ev.target as HTMLElement).style.backgroundColor !== 'red') + setTimeout(()=>{(ev.target as HTMLElement).style.backgroundColor = '';},1000); + (ev.target as HTMLElement).style.backgroundColor = 'red'; + } + } + } as HTMLNodeProperties } } as HTMLNodeProperties } let graph = new Graph({ - roots, + tree, loaders:{ - //htmlloader - wchtmlloader + htmlloader } }) \ No newline at end of file diff --git a/examples/loaders/html/package-lock.json b/examples/html/package-lock.json similarity index 91% rename from examples/loaders/html/package-lock.json rename to examples/html/package-lock.json index 8847d868..58a065cd 100644 --- a/examples/loaders/html/package-lock.json +++ b/examples/html/package-lock.json @@ -7,16 +7,15 @@ "": { "name": "tinybuildapp8682", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "web-worker": "^1.2.0" - }, - "devDependencies": {} + } }, "../../../../../AppData/Roaming/npm/node_modules/tinybuild": { "version": "0.3.190", "extraneous": true, - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "chokidar": "~3.5.3", "esbuild": "~0.14.49", diff --git a/examples/loaders/html/package.json b/examples/html/package.json similarity index 96% rename from examples/loaders/html/package.json rename to examples/html/package.json index fcbc11a2..865c9195 100644 --- a/examples/loaders/html/package.json +++ b/examples/html/package.json @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "web-worker": "^1.2.0" }, diff --git a/examples/basics/listeners/tinybuild.config.js b/examples/html/tinybuild.config.js similarity index 96% rename from examples/basics/listeners/tinybuild.config.js rename to examples/html/tinybuild.config.js index 749308ef..7b98c0a3 100644 --- a/examples/basics/listeners/tinybuild.config.js +++ b/examples/html/tinybuild.config.js @@ -20,10 +20,10 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8081, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port + hotreload: 5001, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) diff --git a/examples/services/http/backend.ts b/examples/httpserver/backend.ts similarity index 95% rename from examples/services/http/backend.ts rename to examples/httpserver/backend.ts index 77dbf649..105e0394 100644 --- a/examples/services/http/backend.ts +++ b/examples/httpserver/backend.ts @@ -1,5 +1,5 @@ -import { HTTPbackend, ServerProps, ServerInfo, SSEbackend, SSEProps, WSSbackend, SocketServerProps } from "../../../index.node"//"graphscript-node"; -import { Router } from '../../../src/services/router/Router'; +import { HTTPbackend, ServerProps, ServerInfo, SSEbackend, SSEProps, WSSbackend, SocketServerProps } from "../../index.node"//"graphscript-node"; +import { Router } from '../../services/router/Router'; function exitHandler(options, exitCode) { @@ -30,7 +30,7 @@ let server = router.run( host:'localhost', port:8080, pages:{ - '/*':{ + '/':{ template:`
      Nice...
      `, onrequest:(self,node,req,res)=>{ node.get = `

      Hello World!! The Time: ${new Date(Date.now()).toISOString()}

      ` diff --git a/examples/httpserver/dist/backend.node.js b/examples/httpserver/dist/backend.node.js new file mode 100644 index 00000000..42f0c1e1 --- /dev/null +++ b/examples/httpserver/dist/backend.node.js @@ -0,0 +1,7779 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// ../../services/e2ee/sjcl.js +var require_sjcl = __commonJS({ + "../../services/e2ee/sjcl.js"(exports, module2) { + "use strict"; + var sjcl2 = { cipher: {}, hash: {}, keyexchange: {}, mode: {}, misc: {}, codec: {}, exception: { corrupt: function(a) { + this.toString = function() { + return "CORRUPT: " + this.message; + }; + this.message = a; + }, invalid: function(a) { + this.toString = function() { + return "INVALID: " + this.message; + }; + this.message = a; + }, bug: function(a) { + this.toString = function() { + return "BUG: " + this.message; + }; + this.message = a; + }, notReady: function(a) { + this.toString = function() { + return "NOT READY: " + this.message; + }; + this.message = a; + } } }; + sjcl2.cipher.aes = function(a) { + this.s[0][0][0] || this.O(); + var b, c, d, e, f = this.s[0][4], g = this.s[1]; + b = a.length; + var h = 1; + if (4 !== b && 6 !== b && 8 !== b) + throw new sjcl2.exception.invalid("invalid aes key size"); + this.b = [d = a.slice(0), e = []]; + for (a = b; a < 4 * b + 28; a++) { + c = d[a - 1]; + if (0 === a % b || 8 === b && 4 === a % b) + c = f[c >>> 24] << 24 ^ f[c >> 16 & 255] << 16 ^ f[c >> 8 & 255] << 8 ^ f[c & 255], 0 === a % b && (c = c << 8 ^ c >>> 24 ^ h << 24, h = h << 1 ^ 283 * (h >> 7)); + d[a] = d[a - b] ^ c; + } + for (b = 0; a; b++, a--) + c = d[b & 3 ? a : a - 4], e[b] = 4 >= a || 4 > b ? c : g[0][f[c >>> 24]] ^ g[1][f[c >> 16 & 255]] ^ g[2][f[c >> 8 & 255]] ^ g[3][f[c & 255]]; + }; + sjcl2.cipher.aes.prototype = { encrypt: function(a) { + return t(this, a, 0); + }, decrypt: function(a) { + return t(this, a, 1); + }, s: [[[], [], [], [], []], [[], [], [], [], []]], O: function() { + var a = this.s[0], b = this.s[1], c = a[4], d = b[4], e, f, g, h = [], k = [], l, n, m, p; + for (e = 0; 256 > e; e++) + k[(h[e] = e << 1 ^ 283 * (e >> 7)) ^ e] = e; + for (f = g = 0; !c[f]; f ^= l || 1, g = k[g] || 1) + for (m = g ^ g << 1 ^ g << 2 ^ g << 3 ^ g << 4, m = m >> 8 ^ m & 255 ^ 99, c[f] = m, d[m] = f, n = h[e = h[l = h[f]]], p = 16843009 * n ^ 65537 * e ^ 257 * l ^ 16843008 * f, n = 257 * h[m] ^ 16843008 * m, e = 0; 4 > e; e++) + a[e][f] = n = n << 24 ^ n >>> 8, b[e][m] = p = p << 24 ^ p >>> 8; + for (e = 0; 5 > e; e++) + a[e] = a[e].slice(0), b[e] = b[e].slice(0); + } }; + function t(a, b, c) { + if (4 !== b.length) + throw new sjcl2.exception.invalid("invalid aes block size"); + var d = a.b[c], e = b[0] ^ d[0], f = b[c ? 3 : 1] ^ d[1], g = b[2] ^ d[2]; + b = b[c ? 1 : 3] ^ d[3]; + var h, k, l, n = d.length / 4 - 2, m, p = 4, r = [0, 0, 0, 0]; + h = a.s[c]; + a = h[0]; + var q = h[1], v = h[2], w = h[3], x = h[4]; + for (m = 0; m < n; m++) + h = a[e >>> 24] ^ q[f >> 16 & 255] ^ v[g >> 8 & 255] ^ w[b & 255] ^ d[p], k = a[f >>> 24] ^ q[g >> 16 & 255] ^ v[b >> 8 & 255] ^ w[e & 255] ^ d[p + 1], l = a[g >>> 24] ^ q[b >> 16 & 255] ^ v[e >> 8 & 255] ^ w[f & 255] ^ d[p + 2], b = a[b >>> 24] ^ q[e >> 16 & 255] ^ v[f >> 8 & 255] ^ w[g & 255] ^ d[p + 3], p += 4, e = h, f = k, g = l; + for (m = 0; 4 > m; m++) + r[c ? 3 & -m : m] = x[e >>> 24] << 24 ^ x[f >> 16 & 255] << 16 ^ x[g >> 8 & 255] << 8 ^ x[b & 255] ^ d[p++], h = e, e = f, f = g, g = b, b = h; + return r; + } + sjcl2.bitArray = { bitSlice: function(a, b, c) { + a = sjcl2.bitArray.$(a.slice(b / 32), 32 - (b & 31)).slice(1); + return void 0 === c ? a : sjcl2.bitArray.clamp(a, c - b); + }, extract: function(a, b, c) { + var d = Math.floor(-b - c & 31); + return ((b + c - 1 ^ b) & -32 ? a[b / 32 | 0] << 32 - d ^ a[b / 32 + 1 | 0] >>> d : a[b / 32 | 0] >>> d) & (1 << c) - 1; + }, concat: function(a, b) { + if (0 === a.length || 0 === b.length) + return a.concat(b); + var c = a[a.length - 1], d = sjcl2.bitArray.getPartial(c); + return 32 === d ? a.concat(b) : sjcl2.bitArray.$(b, d, c | 0, a.slice(0, a.length - 1)); + }, bitLength: function(a) { + var b = a.length; + return 0 === b ? 0 : 32 * (b - 1) + sjcl2.bitArray.getPartial(a[b - 1]); + }, clamp: function(a, b) { + if (32 * a.length < b) + return a; + a = a.slice(0, Math.ceil(b / 32)); + var c = a.length; + b = b & 31; + 0 < c && b && (a[c - 1] = sjcl2.bitArray.partial(b, a[c - 1] & 2147483648 >> b - 1, 1)); + return a; + }, partial: function(a, b, c) { + return 32 === a ? b : (c ? b | 0 : b << 32 - a) + 1099511627776 * a; + }, getPartial: function(a) { + return Math.round(a / 1099511627776) || 32; + }, equal: function(a, b) { + if (sjcl2.bitArray.bitLength(a) !== sjcl2.bitArray.bitLength(b)) + return false; + var c = 0, d; + for (d = 0; d < a.length; d++) + c |= a[d] ^ b[d]; + return 0 === c; + }, $: function(a, b, c, d) { + var e; + e = 0; + for (void 0 === d && (d = []); 32 <= b; b -= 32) + d.push(c), c = 0; + if (0 === b) + return d.concat(a); + for (e = 0; e < a.length; e++) + d.push(c | a[e] >>> b), c = a[e] << 32 - b; + e = a.length ? a[a.length - 1] : 0; + a = sjcl2.bitArray.getPartial(e); + d.push(sjcl2.bitArray.partial(b + a & 31, 32 < b + a ? c : d.pop(), 1)); + return d; + }, i: function(a, b) { + return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; + }, byteswapM: function(a) { + var b, c; + for (b = 0; b < a.length; ++b) + c = a[b], a[b] = c >>> 24 | c >>> 8 & 65280 | (c & 65280) << 8 | c << 24; + return a; + } }; + sjcl2.codec.utf8String = { fromBits: function(a) { + var b = "", c = sjcl2.bitArray.bitLength(a), d, e; + for (d = 0; d < c / 8; d++) + 0 === (d & 3) && (e = a[d / 4]), b += String.fromCharCode(e >>> 8 >>> 8 >>> 8), e <<= 8; + return decodeURIComponent(escape(b)); + }, toBits: function(a) { + a = unescape(encodeURIComponent(a)); + var b = [], c, d = 0; + for (c = 0; c < a.length; c++) + d = d << 8 | a.charCodeAt(c), 3 === (c & 3) && (b.push(d), d = 0); + c & 3 && b.push(sjcl2.bitArray.partial(8 * (c & 3), d)); + return b; + } }; + sjcl2.codec.hex = { fromBits: function(a) { + var b = "", c; + for (c = 0; c < a.length; c++) + b += ((a[c] | 0) + 263882790666240).toString(16).substr(4); + return b.substr(0, sjcl2.bitArray.bitLength(a) / 4); + }, toBits: function(a) { + var b, c = [], d; + a = a.replace(/\s|0x/g, ""); + d = a.length; + a = a + "00000000"; + for (b = 0; b < a.length; b += 8) + c.push(parseInt(a.substr(b, 8), 16) ^ 0); + return sjcl2.bitArray.clamp(c, 4 * d); + } }; + sjcl2.codec.base32 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", X: "0123456789ABCDEFGHIJKLMNOPQRSTUV", BITS: 32, BASE: 5, REMAINING: 27, fromBits: function(a, b, c) { + var d = sjcl2.codec.base32.BASE, e = sjcl2.codec.base32.REMAINING, f = "", g = 0, h = sjcl2.codec.base32.B, k = 0, l = sjcl2.bitArray.bitLength(a); + c && (h = sjcl2.codec.base32.X); + for (c = 0; f.length * d < l; ) + f += h.charAt((k ^ a[c] >>> g) >>> e), g < d ? (k = a[c] << d - g, g += e, c++) : (k <<= d, g -= d); + for (; f.length & 7 && !b; ) + f += "="; + return f; + }, toBits: function(a, b) { + a = a.replace(/\s|=/g, "").toUpperCase(); + var c = sjcl2.codec.base32.BITS, d = sjcl2.codec.base32.BASE, e = sjcl2.codec.base32.REMAINING, f = [], g, h = 0, k = sjcl2.codec.base32.B, l = 0, n, m = "base32"; + b && (k = sjcl2.codec.base32.X, m = "base32hex"); + for (g = 0; g < a.length; g++) { + n = k.indexOf(a.charAt(g)); + if (0 > n) { + if (!b) + try { + return sjcl2.codec.base32hex.toBits(a); + } catch (p) { + } + throw new sjcl2.exception.invalid("this isn't " + m + "!"); + } + h > e ? (h -= e, f.push(l ^ n >>> h), l = n << c - h) : (h += d, l ^= n << c - h); + } + h & 56 && f.push(sjcl2.bitArray.partial(h & 56, l, 1)); + return f; + } }; + sjcl2.codec.base32hex = { fromBits: function(a, b) { + return sjcl2.codec.base32.fromBits(a, b, 1); + }, toBits: function(a) { + return sjcl2.codec.base32.toBits(a, 1); + } }; + sjcl2.codec.base64 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fromBits: function(a, b, c) { + var d = "", e = 0, f = sjcl2.codec.base64.B, g = 0, h = sjcl2.bitArray.bitLength(a); + c && (f = f.substr(0, 62) + "-_"); + for (c = 0; 6 * d.length < h; ) + d += f.charAt((g ^ a[c] >>> e) >>> 26), 6 > e ? (g = a[c] << 6 - e, e += 26, c++) : (g <<= 6, e -= 6); + for (; d.length & 3 && !b; ) + d += "="; + return d; + }, toBits: function(a, b) { + a = a.replace(/\s|=/g, ""); + var c = [], d, e = 0, f = sjcl2.codec.base64.B, g = 0, h; + b && (f = f.substr(0, 62) + "-_"); + for (d = 0; d < a.length; d++) { + h = f.indexOf(a.charAt(d)); + if (0 > h) + throw new sjcl2.exception.invalid("this isn't base64!"); + 26 < e ? (e -= 26, c.push(g ^ h >>> e), g = h << 32 - e) : (e += 6, g ^= h << 32 - e); + } + e & 56 && c.push(sjcl2.bitArray.partial(e & 56, g, 1)); + return c; + } }; + sjcl2.codec.base64url = { fromBits: function(a) { + return sjcl2.codec.base64.fromBits(a, 1, 1); + }, toBits: function(a) { + return sjcl2.codec.base64.toBits(a, 1); + } }; + sjcl2.hash.sha256 = function(a) { + this.b[0] || this.O(); + a ? (this.F = a.F.slice(0), this.A = a.A.slice(0), this.l = a.l) : this.reset(); + }; + sjcl2.hash.sha256.hash = function(a) { + return new sjcl2.hash.sha256().update(a).finalize(); + }; + sjcl2.hash.sha256.prototype = { blockSize: 512, reset: function() { + this.F = this.Y.slice(0); + this.A = []; + this.l = 0; + return this; + }, update: function(a) { + "string" === typeof a && (a = sjcl2.codec.utf8String.toBits(a)); + var b, c = this.A = sjcl2.bitArray.concat(this.A, a); + b = this.l; + a = this.l = b + sjcl2.bitArray.bitLength(a); + if (9007199254740991 < a) + throw new sjcl2.exception.invalid("Cannot hash more than 2^53 - 1 bits"); + if ("undefined" !== typeof Uint32Array) { + var d = new Uint32Array(c), e = 0; + for (b = 512 + b - (512 + b & 511); b <= a; b += 512) + u(this, d.subarray( + 16 * e, + 16 * (e + 1) + )), e += 1; + c.splice(0, 16 * e); + } else + for (b = 512 + b - (512 + b & 511); b <= a; b += 512) + u(this, c.splice(0, 16)); + return this; + }, finalize: function() { + var a, b = this.A, c = this.F, b = sjcl2.bitArray.concat(b, [sjcl2.bitArray.partial(1, 1)]); + for (a = b.length + 2; a & 15; a++) + b.push(0); + b.push(Math.floor(this.l / 4294967296)); + for (b.push(this.l | 0); b.length; ) + u(this, b.splice(0, 16)); + this.reset(); + return c; + }, Y: [], b: [], O: function() { + function a(a2) { + return 4294967296 * (a2 - Math.floor(a2)) | 0; + } + for (var b = 0, c = 2, d, e; 64 > b; c++) { + e = true; + for (d = 2; d * d <= c; d++) + if (0 === c % d) { + e = false; + break; + } + e && (8 > b && (this.Y[b] = a(Math.pow(c, 0.5))), this.b[b] = a(Math.pow(c, 1 / 3)), b++); + } + } }; + function u(a, b) { + var c, d, e, f = a.F, g = a.b, h = f[0], k = f[1], l = f[2], n = f[3], m = f[4], p = f[5], r = f[6], q = f[7]; + for (c = 0; 64 > c; c++) + 16 > c ? d = b[c] : (d = b[c + 1 & 15], e = b[c + 14 & 15], d = b[c & 15] = (d >>> 7 ^ d >>> 18 ^ d >>> 3 ^ d << 25 ^ d << 14) + (e >>> 17 ^ e >>> 19 ^ e >>> 10 ^ e << 15 ^ e << 13) + b[c & 15] + b[c + 9 & 15] | 0), d = d + q + (m >>> 6 ^ m >>> 11 ^ m >>> 25 ^ m << 26 ^ m << 21 ^ m << 7) + (r ^ m & (p ^ r)) + g[c], q = r, r = p, p = m, m = n + d | 0, n = l, l = k, k = h, h = d + (k & l ^ n & (k ^ l)) + (k >>> 2 ^ k >>> 13 ^ k >>> 22 ^ k << 30 ^ k << 19 ^ k << 10) | 0; + f[0] = f[0] + h | 0; + f[1] = f[1] + k | 0; + f[2] = f[2] + l | 0; + f[3] = f[3] + n | 0; + f[4] = f[4] + m | 0; + f[5] = f[5] + p | 0; + f[6] = f[6] + r | 0; + f[7] = f[7] + q | 0; + } + sjcl2.mode.ccm = { name: "ccm", G: [], listenProgress: function(a) { + sjcl2.mode.ccm.G.push(a); + }, unListenProgress: function(a) { + a = sjcl2.mode.ccm.G.indexOf(a); + -1 < a && sjcl2.mode.ccm.G.splice(a, 1); + }, fa: function(a) { + var b = sjcl2.mode.ccm.G.slice(), c; + for (c = 0; c < b.length; c += 1) + b[c](a); + }, encrypt: function(a, b, c, d, e) { + var f, g = b.slice(0), h = sjcl2.bitArray, k = h.bitLength(c) / 8, l = h.bitLength(g) / 8; + e = e || 64; + d = d || []; + if (7 > k) + throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes"); + for (f = 2; 4 > f && l >>> 8 * f; f++) + ; + f < 15 - k && (f = 15 - k); + c = h.clamp( + c, + 8 * (15 - f) + ); + b = sjcl2.mode.ccm.V(a, b, c, d, e, f); + g = sjcl2.mode.ccm.C(a, g, c, b, e, f); + return h.concat(g.data, g.tag); + }, decrypt: function(a, b, c, d, e) { + e = e || 64; + d = d || []; + var f = sjcl2.bitArray, g = f.bitLength(c) / 8, h = f.bitLength(b), k = f.clamp(b, h - e), l = f.bitSlice(b, h - e), h = (h - e) / 8; + if (7 > g) + throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes"); + for (b = 2; 4 > b && h >>> 8 * b; b++) + ; + b < 15 - g && (b = 15 - g); + c = f.clamp(c, 8 * (15 - b)); + k = sjcl2.mode.ccm.C(a, k, c, l, e, b); + a = sjcl2.mode.ccm.V(a, k.data, c, d, e, b); + if (!f.equal(k.tag, a)) + throw new sjcl2.exception.corrupt("ccm: tag doesn't match"); + return k.data; + }, na: function(a, b, c, d, e, f) { + var g = [], h = sjcl2.bitArray, k = h.i; + d = [h.partial(8, (b.length ? 64 : 0) | d - 2 << 2 | f - 1)]; + d = h.concat(d, c); + d[3] |= e; + d = a.encrypt(d); + if (b.length) + for (c = h.bitLength(b) / 8, 65279 >= c ? g = [h.partial(16, c)] : 4294967295 >= c && (g = h.concat([h.partial(16, 65534)], [c])), g = h.concat(g, b), b = 0; b < g.length; b += 4) + d = a.encrypt(k(d, g.slice(b, b + 4).concat([0, 0, 0]))); + return d; + }, V: function(a, b, c, d, e, f) { + var g = sjcl2.bitArray, h = g.i; + e /= 8; + if (e % 2 || 4 > e || 16 < e) + throw new sjcl2.exception.invalid("ccm: invalid tag length"); + if (4294967295 < d.length || 4294967295 < b.length) + throw new sjcl2.exception.bug("ccm: can't deal with 4GiB or more data"); + c = sjcl2.mode.ccm.na(a, d, c, e, g.bitLength(b) / 8, f); + for (d = 0; d < b.length; d += 4) + c = a.encrypt(h(c, b.slice(d, d + 4).concat([0, 0, 0]))); + return g.clamp(c, 8 * e); + }, C: function(a, b, c, d, e, f) { + var g, h = sjcl2.bitArray; + g = h.i; + var k = b.length, l = h.bitLength(b), n = k / 50, m = n; + c = h.concat([h.partial(8, f - 1)], c).concat([0, 0, 0]).slice(0, 4); + d = h.bitSlice(g(d, a.encrypt(c)), 0, e); + if (!k) + return { tag: d, data: [] }; + for (g = 0; g < k; g += 4) + g > n && (sjcl2.mode.ccm.fa(g / k), n += m), c[3]++, e = a.encrypt(c), b[g] ^= e[0], b[g + 1] ^= e[1], b[g + 2] ^= e[2], b[g + 3] ^= e[3]; + return { tag: d, data: h.clamp(b, l) }; + } }; + sjcl2.mode.ocb2 = { name: "ocb2", encrypt: function(a, b, c, d, e, f) { + if (128 !== sjcl2.bitArray.bitLength(c)) + throw new sjcl2.exception.invalid("ocb iv must be 128 bits"); + var g, h = sjcl2.mode.ocb2.S, k = sjcl2.bitArray, l = k.i, n = [0, 0, 0, 0]; + c = h(a.encrypt(c)); + var m, p = []; + d = d || []; + e = e || 64; + for (g = 0; g + 4 < b.length; g += 4) + m = b.slice(g, g + 4), n = l(n, m), p = p.concat(l(c, a.encrypt(l(c, m)))), c = h(c); + m = b.slice(g); + b = k.bitLength(m); + g = a.encrypt(l(c, [0, 0, 0, b])); + m = k.clamp(l(m.concat([0, 0, 0]), g), b); + n = l(n, l(m.concat([0, 0, 0]), g)); + n = a.encrypt(l(n, l(c, h(c)))); + d.length && (n = l(n, f ? d : sjcl2.mode.ocb2.pmac(a, d))); + return p.concat(k.concat(m, k.clamp(n, e))); + }, decrypt: function(a, b, c, d, e, f) { + if (128 !== sjcl2.bitArray.bitLength(c)) + throw new sjcl2.exception.invalid("ocb iv must be 128 bits"); + e = e || 64; + var g = sjcl2.mode.ocb2.S, h = sjcl2.bitArray, k = h.i, l = [0, 0, 0, 0], n = g(a.encrypt(c)), m, p, r = sjcl2.bitArray.bitLength(b) - e, q = []; + d = d || []; + for (c = 0; c + 4 < r / 32; c += 4) + m = k(n, a.decrypt(k(n, b.slice(c, c + 4)))), l = k(l, m), q = q.concat(m), n = g(n); + p = r - 32 * c; + m = a.encrypt(k(n, [0, 0, 0, p])); + m = k(m, h.clamp(b.slice(c), p).concat([ + 0, + 0, + 0 + ])); + l = k(l, m); + l = a.encrypt(k(l, k(n, g(n)))); + d.length && (l = k(l, f ? d : sjcl2.mode.ocb2.pmac(a, d))); + if (!h.equal(h.clamp(l, e), h.bitSlice(b, r))) + throw new sjcl2.exception.corrupt("ocb: tag doesn't match"); + return q.concat(h.clamp(m, p)); + }, pmac: function(a, b) { + var c, d = sjcl2.mode.ocb2.S, e = sjcl2.bitArray, f = e.i, g = [0, 0, 0, 0], h = a.encrypt([0, 0, 0, 0]), h = f(h, d(d(h))); + for (c = 0; c + 4 < b.length; c += 4) + h = d(h), g = f(g, a.encrypt(f(h, b.slice(c, c + 4)))); + c = b.slice(c); + 128 > e.bitLength(c) && (h = f(h, d(h)), c = e.concat(c, [-2147483648, 0, 0, 0])); + g = f(g, c); + return a.encrypt(f(d(f(h, d(h))), g)); + }, S: function(a) { + return [a[0] << 1 ^ a[1] >>> 31, a[1] << 1 ^ a[2] >>> 31, a[2] << 1 ^ a[3] >>> 31, a[3] << 1 ^ 135 * (a[0] >>> 31)]; + } }; + sjcl2.mode.gcm = { name: "gcm", encrypt: function(a, b, c, d, e) { + var f = b.slice(0); + b = sjcl2.bitArray; + d = d || []; + a = sjcl2.mode.gcm.C(true, a, f, d, c, e || 128); + return b.concat(a.data, a.tag); + }, decrypt: function(a, b, c, d, e) { + var f = b.slice(0), g = sjcl2.bitArray, h = g.bitLength(f); + e = e || 128; + d = d || []; + e <= h ? (b = g.bitSlice(f, h - e), f = g.bitSlice(f, 0, h - e)) : (b = f, f = []); + a = sjcl2.mode.gcm.C(false, a, f, d, c, e); + if (!g.equal(a.tag, b)) + throw new sjcl2.exception.corrupt("gcm: tag doesn't match"); + return a.data; + }, ka: function(a, b) { + var c, d, e, f, g, h = sjcl2.bitArray.i; + e = [ + 0, + 0, + 0, + 0 + ]; + f = b.slice(0); + for (c = 0; 128 > c; c++) { + (d = 0 !== (a[Math.floor(c / 32)] & 1 << 31 - c % 32)) && (e = h(e, f)); + g = 0 !== (f[3] & 1); + for (d = 3; 0 < d; d--) + f[d] = f[d] >>> 1 | (f[d - 1] & 1) << 31; + f[0] >>>= 1; + g && (f[0] ^= -520093696); + } + return e; + }, j: function(a, b, c) { + var d, e = c.length; + b = b.slice(0); + for (d = 0; d < e; d += 4) + b[0] ^= 4294967295 & c[d], b[1] ^= 4294967295 & c[d + 1], b[2] ^= 4294967295 & c[d + 2], b[3] ^= 4294967295 & c[d + 3], b = sjcl2.mode.gcm.ka(b, a); + return b; + }, C: function(a, b, c, d, e, f) { + var g, h, k, l, n, m, p, r, q = sjcl2.bitArray; + m = c.length; + p = q.bitLength(c); + r = q.bitLength(d); + h = q.bitLength(e); + g = b.encrypt([0, 0, 0, 0]); + 96 === h ? (e = e.slice(0), e = q.concat(e, [1])) : (e = sjcl2.mode.gcm.j(g, [0, 0, 0, 0], e), e = sjcl2.mode.gcm.j(g, e, [0, 0, Math.floor(h / 4294967296), h & 4294967295])); + h = sjcl2.mode.gcm.j(g, [0, 0, 0, 0], d); + n = e.slice(0); + d = h.slice(0); + a || (d = sjcl2.mode.gcm.j(g, h, c)); + for (l = 0; l < m; l += 4) + n[3]++, k = b.encrypt(n), c[l] ^= k[0], c[l + 1] ^= k[1], c[l + 2] ^= k[2], c[l + 3] ^= k[3]; + c = q.clamp(c, p); + a && (d = sjcl2.mode.gcm.j(g, h, c)); + a = [Math.floor(r / 4294967296), r & 4294967295, Math.floor(p / 4294967296), p & 4294967295]; + d = sjcl2.mode.gcm.j(g, d, a); + k = b.encrypt(e); + d[0] ^= k[0]; + d[1] ^= k[1]; + d[2] ^= k[2]; + d[3] ^= k[3]; + return { tag: q.bitSlice(d, 0, f), data: c }; + } }; + sjcl2.misc.hmac = function(a, b) { + this.W = b = b || sjcl2.hash.sha256; + var c = [[], []], d, e = b.prototype.blockSize / 32; + this.w = [new b(), new b()]; + a.length > e && (a = b.hash(a)); + for (d = 0; d < e; d++) + c[0][d] = a[d] ^ 909522486, c[1][d] = a[d] ^ 1549556828; + this.w[0].update(c[0]); + this.w[1].update(c[1]); + this.R = new b(this.w[0]); + }; + sjcl2.misc.hmac.prototype.encrypt = sjcl2.misc.hmac.prototype.mac = function(a) { + if (this.aa) + throw new sjcl2.exception.invalid("encrypt on already updated hmac called!"); + this.update(a); + return this.digest(a); + }; + sjcl2.misc.hmac.prototype.reset = function() { + this.R = new this.W(this.w[0]); + this.aa = false; + }; + sjcl2.misc.hmac.prototype.update = function(a) { + this.aa = true; + this.R.update(a); + }; + sjcl2.misc.hmac.prototype.digest = function() { + var a = this.R.finalize(), a = new this.W(this.w[1]).update(a).finalize(); + this.reset(); + return a; + }; + sjcl2.misc.pbkdf2 = function(a, b, c, d, e) { + c = c || 1e4; + if (0 > d || 0 > c) + throw new sjcl2.exception.invalid("invalid params to pbkdf2"); + "string" === typeof a && (a = sjcl2.codec.utf8String.toBits(a)); + "string" === typeof b && (b = sjcl2.codec.utf8String.toBits(b)); + e = e || sjcl2.misc.hmac; + a = new e(a); + var f, g, h, k, l = [], n = sjcl2.bitArray; + for (k = 1; 32 * l.length < (d || 1); k++) { + e = f = a.encrypt(n.concat(b, [k])); + for (g = 1; g < c; g++) + for (f = a.encrypt(f), h = 0; h < f.length; h++) + e[h] ^= f[h]; + l = l.concat(e); + } + d && (l = n.clamp(l, d)); + return l; + }; + sjcl2.prng = function(a) { + this.c = [new sjcl2.hash.sha256()]; + this.m = [0]; + this.P = 0; + this.H = {}; + this.N = 0; + this.U = {}; + this.Z = this.f = this.o = this.ha = 0; + this.b = [0, 0, 0, 0, 0, 0, 0, 0]; + this.h = [0, 0, 0, 0]; + this.L = void 0; + this.M = a; + this.D = false; + this.K = { progress: {}, seeded: {} }; + this.u = this.ga = 0; + this.I = 1; + this.J = 2; + this.ca = 65536; + this.T = [0, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024]; + this.da = 3e4; + this.ba = 80; + }; + sjcl2.prng.prototype = { + randomWords: function(a, b) { + var c = [], d; + d = this.isReady(b); + var e; + if (d === this.u) + throw new sjcl2.exception.notReady("generator isn't seeded"); + if (d & this.J) { + d = !(d & this.I); + e = []; + var f = 0, g; + this.Z = e[0] = new Date().valueOf() + this.da; + for (g = 0; 16 > g; g++) + e.push(4294967296 * Math.random() | 0); + for (g = 0; g < this.c.length && (e = e.concat(this.c[g].finalize()), f += this.m[g], this.m[g] = 0, d || !(this.P & 1 << g)); g++) + ; + this.P >= 1 << this.c.length && (this.c.push(new sjcl2.hash.sha256()), this.m.push(0)); + this.f -= f; + f > this.o && (this.o = f); + this.P++; + this.b = sjcl2.hash.sha256.hash(this.b.concat(e)); + this.L = new sjcl2.cipher.aes(this.b); + for (d = 0; 4 > d && (this.h[d] = this.h[d] + 1 | 0, !this.h[d]); d++) + ; + } + for (d = 0; d < a; d += 4) + 0 === (d + 1) % this.ca && y(this), e = z(this), c.push(e[0], e[1], e[2], e[3]); + y(this); + return c.slice(0, a); + }, + setDefaultParanoia: function(a, b) { + if (0 === a && "Setting paranoia=0 will ruin your security; use it only for testing" !== b) + throw new sjcl2.exception.invalid("Setting paranoia=0 will ruin your security; use it only for testing"); + this.M = a; + }, + addEntropy: function(a, b, c) { + c = c || "user"; + var d, e, f = new Date().valueOf(), g = this.H[c], h = this.isReady(), k = 0; + d = this.U[c]; + void 0 === d && (d = this.U[c] = this.ha++); + void 0 === g && (g = this.H[c] = 0); + this.H[c] = (this.H[c] + 1) % this.c.length; + switch (typeof a) { + case "number": + void 0 === b && (b = 1); + this.c[g].update([d, this.N++, 1, b, f, 1, a | 0]); + break; + case "object": + c = Object.prototype.toString.call(a); + if ("[object Uint32Array]" === c) { + e = []; + for (c = 0; c < a.length; c++) + e.push(a[c]); + a = e; + } else + for ("[object Array]" !== c && (k = 1), c = 0; c < a.length && !k; c++) + "number" !== typeof a[c] && (k = 1); + if (!k) { + if (void 0 === b) + for (c = b = 0; c < a.length; c++) + for (e = a[c]; 0 < e; ) + b++, e = e >>> 1; + this.c[g].update([d, this.N++, 2, b, f, a.length].concat(a)); + } + break; + case "string": + void 0 === b && (b = a.length); + this.c[g].update([d, this.N++, 3, b, f, a.length]); + this.c[g].update(a); + break; + default: + k = 1; + } + if (k) + throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string"); + this.m[g] += b; + this.f += b; + h === this.u && (this.isReady() !== this.u && A("seeded", Math.max(this.o, this.f)), A("progress", this.getProgress())); + }, + isReady: function(a) { + a = this.T[void 0 !== a ? a : this.M]; + return this.o && this.o >= a ? this.m[0] > this.ba && new Date().valueOf() > this.Z ? this.J | this.I : this.I : this.f >= a ? this.J | this.u : this.u; + }, + getProgress: function(a) { + a = this.T[a ? a : this.M]; + return this.o >= a ? 1 : this.f > a ? 1 : this.f / a; + }, + startCollectors: function() { + if (!this.D) { + this.a = { loadTimeCollector: B(this, this.ma), mouseCollector: B(this, this.oa), keyboardCollector: B(this, this.la), accelerometerCollector: B(this, this.ea), touchCollector: B(this, this.qa) }; + if (window.addEventListener) + window.addEventListener( + "load", + this.a.loadTimeCollector, + false + ), window.addEventListener("mousemove", this.a.mouseCollector, false), window.addEventListener("keypress", this.a.keyboardCollector, false), window.addEventListener("devicemotion", this.a.accelerometerCollector, false), window.addEventListener("touchmove", this.a.touchCollector, false); + else if (document.attachEvent) + document.attachEvent("onload", this.a.loadTimeCollector), document.attachEvent("onmousemove", this.a.mouseCollector), document.attachEvent("keypress", this.a.keyboardCollector); + else + throw new sjcl2.exception.bug("can't attach event"); + this.D = true; + } + }, + stopCollectors: function() { + this.D && (window.removeEventListener ? (window.removeEventListener("load", this.a.loadTimeCollector, false), window.removeEventListener("mousemove", this.a.mouseCollector, false), window.removeEventListener("keypress", this.a.keyboardCollector, false), window.removeEventListener("devicemotion", this.a.accelerometerCollector, false), window.removeEventListener("touchmove", this.a.touchCollector, false)) : document.detachEvent && (document.detachEvent("onload", this.a.loadTimeCollector), document.detachEvent( + "onmousemove", + this.a.mouseCollector + ), document.detachEvent("keypress", this.a.keyboardCollector)), this.D = false); + }, + addEventListener: function(a, b) { + this.K[a][this.ga++] = b; + }, + removeEventListener: function(a, b) { + var c, d, e = this.K[a], f = []; + for (d in e) + e.hasOwnProperty(d) && e[d] === b && f.push(d); + for (c = 0; c < f.length; c++) + d = f[c], delete e[d]; + }, + la: function() { + C(this, 1); + }, + oa: function(a) { + var b, c; + try { + b = a.x || a.clientX || a.offsetX || 0, c = a.y || a.clientY || a.offsetY || 0; + } catch (d) { + c = b = 0; + } + 0 != b && 0 != c && this.addEntropy([b, c], 2, "mouse"); + C(this, 0); + }, + qa: function(a) { + a = a.touches[0] || a.changedTouches[0]; + this.addEntropy([a.pageX || a.clientX, a.pageY || a.clientY], 1, "touch"); + C(this, 0); + }, + ma: function() { + C(this, 2); + }, + ea: function(a) { + a = a.accelerationIncludingGravity.x || a.accelerationIncludingGravity.y || a.accelerationIncludingGravity.z; + if (window.orientation) { + var b = window.orientation; + "number" === typeof b && this.addEntropy(b, 1, "accelerometer"); + } + a && this.addEntropy(a, 2, "accelerometer"); + C(this, 0); + } + }; + function A(a, b) { + var c, d = sjcl2.random.K[a], e = []; + for (c in d) + d.hasOwnProperty(c) && e.push(d[c]); + for (c = 0; c < e.length; c++) + e[c](b); + } + function C(a, b) { + "undefined" !== typeof window && window.performance && "function" === typeof window.performance.now ? a.addEntropy(window.performance.now(), b, "loadtime") : a.addEntropy(new Date().valueOf(), b, "loadtime"); + } + function y(a) { + a.b = z(a).concat(z(a)); + a.L = new sjcl2.cipher.aes(a.b); + } + function z(a) { + for (var b = 0; 4 > b && (a.h[b] = a.h[b] + 1 | 0, !a.h[b]); b++) + ; + return a.L.encrypt(a.h); + } + function B(a, b) { + return function() { + b.apply(a, arguments); + }; + } + sjcl2.random = new sjcl2.prng(6); + a: + try { + if (G = "undefined" !== typeof module2 && module2.exports) { + try { + H = require("crypto"); + } catch (a) { + H = null; + } + G = E = H; + } + if (G && E.randomBytes) + D = E.randomBytes(128), D = new Uint32Array(new Uint8Array(D).buffer), sjcl2.random.addEntropy(D, 1024, "crypto['randomBytes']"); + else if ("undefined" !== typeof window && "undefined" !== typeof Uint32Array) { + F = new Uint32Array(32); + if (window.crypto && window.crypto.getRandomValues) + window.crypto.getRandomValues(F); + else if (window.msCrypto && window.msCrypto.getRandomValues) + window.msCrypto.getRandomValues(F); + else + break a; + sjcl2.random.addEntropy(F, 1024, "crypto['getRandomValues']"); + } + } catch (a) { + "undefined" !== typeof window && window.console && (console.log("There was an error collecting entropy from the browser:"), console.log(a)); + } + var D; + var E; + var F; + var G; + var H; + sjcl2.json = { defaults: { v: 1, iter: 1e4, ks: 128, ts: 64, mode: "ccm", adata: "", cipher: "aes" }, ja: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl2.json, f = e.g({ iv: sjcl2.random.randomWords(4, 0) }, e.defaults), g; + e.g(f, c); + c = f.adata; + "string" === typeof f.salt && (f.salt = sjcl2.codec.base64.toBits(f.salt)); + "string" === typeof f.iv && (f.iv = sjcl2.codec.base64.toBits(f.iv)); + if (!sjcl2.mode[f.mode] || !sjcl2.cipher[f.cipher] || "string" === typeof a && 100 >= f.iter || 64 !== f.ts && 96 !== f.ts && 128 !== f.ts || 128 !== f.ks && 192 !== f.ks && 256 !== f.ks || 2 > f.iv.length || 4 < f.iv.length) + throw new sjcl2.exception.invalid("json encrypt: invalid parameters"); + "string" === typeof a ? (g = sjcl2.misc.cachedPbkdf2(a, f), a = g.key.slice(0, f.ks / 32), f.salt = g.salt) : sjcl2.ecc && a instanceof sjcl2.ecc.elGamal.publicKey && (g = a.kem(), f.kemtag = g.tag, a = g.key.slice(0, f.ks / 32)); + "string" === typeof b && (b = sjcl2.codec.utf8String.toBits(b)); + "string" === typeof c && (f.adata = c = sjcl2.codec.utf8String.toBits(c)); + g = new sjcl2.cipher[f.cipher](a); + e.g(d, f); + d.key = a; + f.ct = "ccm" === f.mode && sjcl2.arrayBuffer && sjcl2.arrayBuffer.ccm && b instanceof ArrayBuffer ? sjcl2.arrayBuffer.ccm.encrypt(g, b, f.iv, c, f.ts) : sjcl2.mode[f.mode].encrypt(g, b, f.iv, c, f.ts); + return f; + }, encrypt: function(a, b, c, d) { + var e = sjcl2.json, f = e.ja.apply(e, arguments); + return e.encode(f); + }, ia: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl2.json; + b = e.g(e.g(e.g({}, e.defaults), b), c, true); + var f, g; + f = b.adata; + "string" === typeof b.salt && (b.salt = sjcl2.codec.base64.toBits(b.salt)); + "string" === typeof b.iv && (b.iv = sjcl2.codec.base64.toBits(b.iv)); + if (!sjcl2.mode[b.mode] || !sjcl2.cipher[b.cipher] || "string" === typeof a && 100 >= b.iter || 64 !== b.ts && 96 !== b.ts && 128 !== b.ts || 128 !== b.ks && 192 !== b.ks && 256 !== b.ks || !b.iv || 2 > b.iv.length || 4 < b.iv.length) + throw new sjcl2.exception.invalid("json decrypt: invalid parameters"); + "string" === typeof a ? (g = sjcl2.misc.cachedPbkdf2(a, b), a = g.key.slice(0, b.ks / 32), b.salt = g.salt) : sjcl2.ecc && a instanceof sjcl2.ecc.elGamal.secretKey && (a = a.unkem(sjcl2.codec.base64.toBits(b.kemtag)).slice(0, b.ks / 32)); + "string" === typeof f && (f = sjcl2.codec.utf8String.toBits(f)); + g = new sjcl2.cipher[b.cipher](a); + f = "ccm" === b.mode && sjcl2.arrayBuffer && sjcl2.arrayBuffer.ccm && b.ct instanceof ArrayBuffer ? sjcl2.arrayBuffer.ccm.decrypt(g, b.ct, b.iv, b.tag, f, b.ts) : sjcl2.mode[b.mode].decrypt(g, b.ct, b.iv, f, b.ts); + e.g(d, b); + d.key = a; + return 1 === c.raw ? f : sjcl2.codec.utf8String.fromBits(f); + }, decrypt: function(a, b, c, d) { + var e = sjcl2.json; + return e.ia(a, e.decode(b), c, d); + }, encode: function(a) { + var b, c = "{", d = ""; + for (b in a) + if (a.hasOwnProperty(b)) { + if (!b.match(/^[a-z0-9]+$/i)) + throw new sjcl2.exception.invalid("json encode: invalid property name"); + c += d + '"' + b + '":'; + d = ","; + switch (typeof a[b]) { + case "number": + case "boolean": + c += a[b]; + break; + case "string": + c += '"' + escape(a[b]) + '"'; + break; + case "object": + c += '"' + sjcl2.codec.base64.fromBits(a[b], 0) + '"'; + break; + default: + throw new sjcl2.exception.bug("json encode: unsupported type"); + } + } + return c + "}"; + }, decode: function(a) { + a = a.replace(/\s/g, ""); + if (!a.match(/^\{.*\}$/)) + throw new sjcl2.exception.invalid("json decode: this isn't json!"); + a = a.replace(/^\{|\}$/g, "").split(/,/); + var b = {}, c, d; + for (c = 0; c < a.length; c++) { + if (!(d = a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i))) + throw new sjcl2.exception.invalid("json decode: this isn't json!"); + null != d[3] ? b[d[2]] = parseInt(d[3], 10) : null != d[4] ? b[d[2]] = d[2].match(/^(ct|adata|salt|iv)$/) ? sjcl2.codec.base64.toBits(d[4]) : unescape(d[4]) : null != d[5] && (b[d[2]] = "true" === d[5]); + } + return b; + }, g: function(a, b, c) { + void 0 === a && (a = {}); + if (void 0 === b) + return a; + for (var d in b) + if (b.hasOwnProperty(d)) { + if (c && void 0 !== a[d] && a[d] !== b[d]) + throw new sjcl2.exception.invalid("required parameter overridden"); + a[d] = b[d]; + } + return a; + }, sa: function(a, b) { + var c = {}, d; + for (d in a) + a.hasOwnProperty(d) && a[d] !== b[d] && (c[d] = a[d]); + return c; + }, ra: function(a, b) { + var c = {}, d; + for (d = 0; d < b.length; d++) + void 0 !== a[b[d]] && (c[b[d]] = a[b[d]]); + return c; + } }; + sjcl2.encrypt = sjcl2.json.encrypt; + sjcl2.decrypt = sjcl2.json.decrypt; + sjcl2.misc.pa = {}; + sjcl2.misc.cachedPbkdf2 = function(a, b) { + var c = sjcl2.misc.pa, d; + b = b || {}; + d = b.iter || 1e3; + c = c[a] = c[a] || {}; + d = c[d] = c[d] || { firstSalt: b.salt && b.salt.length ? b.salt.slice(0) : sjcl2.random.randomWords(2, 0) }; + c = void 0 === b.salt ? d.firstSalt : b.salt; + d[c] = d[c] || sjcl2.misc.pbkdf2(a, c, b.iter); + return { key: d[c].slice(0), salt: c.slice(0) }; + }; + "undefined" !== typeof module2 && module2.exports && (module2.exports = sjcl2); + "function" === typeof define && define([], function() { + return sjcl2; + }); + } +}); + +// ../../node_modules/better-sse/build/index.js +var require_build = __commonJS({ + "../../node_modules/better-sse/build/index.js"(exports, module2) { + !function(e, t) { + if ("object" == typeof exports && "object" == typeof module2) + module2.exports = t(); + else if ("function" == typeof define && define.amd) + define([], t); + else { + var s = t(); + for (var i in s) + ("object" == typeof exports ? exports : e)[i] = s[i]; + } + }(global, () => (() => { + "use strict"; + var e = { n: (t2) => { + var s2 = t2 && t2.__esModule ? () => t2.default : () => t2; + return e.d(s2, { a: s2 }), s2; + }, d: (t2, s2) => { + for (var i2 in s2) + e.o(s2, i2) && !e.o(t2, i2) && Object.defineProperty(t2, i2, { enumerable: true, get: s2[i2] }); + }, o: (e2, t2) => Object.prototype.hasOwnProperty.call(e2, t2), r: (e2) => { + "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true }); + } }, t = {}; + e.r(t), e.d(t, { Channel: () => f, Session: () => u, createChannel: () => v, createSession: () => p }); + const s = require("http"), i = require("events"); + var r = e.n(i); + class n extends r() { + addListener(e2, t2) { + return super.addListener(e2, t2); + } + prependListener(e2, t2) { + return super.prependListener(e2, t2); + } + prependOnceListener(e2, t2) { + return super.prependOnceListener(e2, t2); + } + on(e2, t2) { + return super.on(e2, t2); + } + once(e2, t2) { + return super.once(e2, t2); + } + emit(e2, ...t2) { + return super.emit(e2, ...t2); + } + off(e2, t2) { + return super.off(e2, t2); + } + removeListener(e2, t2) { + return super.removeListener(e2, t2); + } + } + const o = (e2) => JSON.stringify(e2), a = /(\r\n|\r|\n)/g, h = /\n+$/g, l = (e2) => { + let t2 = e2; + return t2 = t2.replace(a, "\n"), t2 = t2.replace(h, ""), t2; + }, d = require("crypto"); + let c; + c = d.randomUUID ? () => (0, d.randomUUID)() : () => (0, d.randomBytes)(4).toString("hex"); + class u extends n { + constructor(e2, t2, i2 = {}) { + var r2, n2, a2, h2, d2, u2, p2; + super(), this.lastId = "", this.isConnected = false, this.state = {}, this.buffer = "", this.initialize = () => { + var e3, t3, i3; + const r3 = `http://${this.req.headers.host}${this.req.url}`, n3 = new URL(r3).searchParams; + if (this.trustClientEventId) { + const s2 = null !== (i3 = null !== (t3 = null !== (e3 = this.req.headers["last-event-id"]) && void 0 !== e3 ? e3 : n3.get("lastEventId")) && void 0 !== t3 ? t3 : n3.get("evs_last_event_id")) && void 0 !== i3 ? i3 : ""; + this.lastId = s2; + } + const o2 = {}; + this.res instanceof s.ServerResponse ? (o2["Content-Type"] = "text/event-stream", o2["Cache-Control"] = "private, no-cache, no-store, no-transform, must-revalidate, max-age=0", o2.Connection = "keep-alive", o2.Pragma = "no-cache", o2["X-Accel-Buffering"] = "no") : (o2["content-type"] = "text/event-stream", o2["cache-control"] = "private, no-cache, no-store, no-transform, must-revalidate, max-age=0", o2.pragma = "no-cache", o2["x-accel-buffering"] = "no"); + for (const [e4, t4] of Object.entries(this.headers)) + o2[e4] = null != t4 ? t4 : ""; + this.res.writeHead(this.statusCode, o2), n3.has("padding") && this.comment(" ".repeat(2049)).dispatch(), n3.has("evs_preamble") && this.comment(" ".repeat(2056)).dispatch(), null !== this.initialRetry && this.retry(this.initialRetry).dispatch(), this.flush(), null !== this.keepAliveInterval && (this.keepAliveTimer = setInterval(this.keepAlive, this.keepAliveInterval)), this.isConnected = true, this.emit("connected"); + }, this.onDisconnected = () => { + this.keepAliveTimer && clearInterval(this.keepAliveTimer), this.isConnected = false, this.emit("disconnected"); + }, this.writeField = (e3, t3) => { + const s2 = this.sanitize(t3); + return this.buffer += e3 + ":" + s2 + "\n", this; + }, this.keepAlive = () => { + this.comment().dispatch().flush(); + }, this.data = (e3) => { + const t3 = this.serialize(e3); + return this.writeField("data", t3), this; + }, this.id = (e3 = "") => (this.writeField("id", e3), this.lastId = e3, this), this.retry = (e3) => { + const t3 = e3.toString(); + return this.writeField("retry", t3), this; + }, this.comment = (e3 = "") => (this.writeField("", e3), this), this.dispatch = () => (this.buffer += "\n", this), this.flush = () => (this.res.write(this.buffer), this.buffer = "", this), this.push = (e3, t3 = "message", s2 = c()) => (this.event(t3).id(s2).data(e3).dispatch().flush(), this.emit("push", e3, t3, s2), this), this.stream = async (e3, t3 = {}) => { + const { eventName: s2 = "stream" } = t3; + return new Promise((t4, i3) => { + e3.on("data", (e4) => { + let t5; + t5 = Buffer.isBuffer(e4) ? e4.toString() : e4, this.push(t5, s2); + }), e3.once("end", () => t4(true)), e3.once("close", () => t4(true)), e3.once("error", (e4) => i3(e4)); + }); + }, this.iterate = async (e3, t3 = {}) => { + const { eventName: s2 = "iteration" } = t3; + for await (const t4 of e3) + this.push(t4, s2); + }, this.req = e2, this.res = t2, this.serialize = null !== (r2 = i2.serializer) && void 0 !== r2 ? r2 : o, this.sanitize = null !== (n2 = i2.sanitizer) && void 0 !== n2 ? n2 : l, this.trustClientEventId = null === (a2 = i2.trustClientEventId) || void 0 === a2 || a2, this.initialRetry = null === i2.retry ? null : null !== (h2 = i2.retry) && void 0 !== h2 ? h2 : 2e3, this.keepAliveInterval = null === i2.keepAlive ? null : null !== (d2 = i2.keepAlive) && void 0 !== d2 ? d2 : 1e4, this.statusCode = null !== (u2 = i2.statusCode) && void 0 !== u2 ? u2 : 200, this.headers = null !== (p2 = i2.headers) && void 0 !== p2 ? p2 : {}, this.req.once("close", this.onDisconnected), setImmediate(this.initialize); + } + event(e2) { + return this.writeField("event", e2), this; + } + } + const p = (...e2) => new Promise((t2) => { + const s2 = new u(...e2); + s2.once("connected", () => { + t2(s2); + }); + }); + class f extends n { + constructor() { + super(), this.state = {}, this.sessions = /* @__PURE__ */ new Set(), this.broadcast = (e2, t2 = "message", s2 = {}) => { + const i2 = c(); + let r2; + r2 = s2.filter ? Array.from(this.sessions).filter(s2.filter) : this.sessions; + for (const s3 of r2) + s3.push(e2, t2, i2); + return this.emit("broadcast", e2, t2, i2), this; + }; + } + get activeSessions() { + return Array.from(this.sessions); + } + get sessionCount() { + return this.sessions.size; + } + register(e2) { + if (this.sessions.has(e2)) + return this; + if (!e2.isConnected) + throw new Error("Cannot register a non-active session."); + return e2.once("disconnected", () => { + this.emit("session-disconnected", e2), this.deregister(e2); + }), this.sessions.add(e2), this.emit("session-registered", e2), this; + } + deregister(e2) { + return this.sessions.has(e2) ? (this.sessions.delete(e2), this.emit("session-deregistered", e2), this) : this; + } + } + const v = (...e2) => new f(...e2); + return t; + })()); + } +}); + +// ../../node_modules/ws/lib/stream.js +var require_stream = __commonJS({ + "../../node_modules/ws/lib/stream.js"(exports, module2) { + "use strict"; + var { Duplex } = require("stream"); + function emitClose(stream) { + stream.emit("close"); + } + function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } + } + function duplexOnError(err) { + this.removeListener("error", duplexOnError); + this.destroy(); + if (this.listenerCount("error") === 0) { + this.emit("error", err); + } + } + function createWebSocketStream2(ws, options) { + let terminateOnDestroy = true; + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + ws.on("message", function message(msg, isBinary) { + const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + if (!duplex.push(data)) + ws.pause(); + }); + ws.once("error", function error(err) { + if (duplex.destroyed) + return; + terminateOnDestroy = false; + duplex.destroy(err); + }); + ws.once("close", function close() { + if (duplex.destroyed) + return; + duplex.push(null); + }); + duplex._destroy = function(err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + let called = false; + ws.once("error", function error(err2) { + called = true; + callback(err2); + }); + ws.once("close", function close() { + if (!called) + callback(err); + process.nextTick(emitClose, duplex); + }); + if (terminateOnDestroy) + ws.terminate(); + }; + duplex._final = function(callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open() { + duplex._final(callback); + }); + return; + } + if (ws._socket === null) + return; + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) + duplex.destroy(); + } else { + ws._socket.once("finish", function finish() { + callback(); + }); + ws.close(); + } + }; + duplex._read = function() { + if (ws.isPaused) + ws.resume(); + }; + duplex._write = function(chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + ws.send(chunk, callback); + }; + duplex.on("end", duplexOnEnd); + duplex.on("error", duplexOnError); + return duplex; + } + module2.exports = createWebSocketStream2; + } +}); + +// ../../node_modules/ws/lib/constants.js +var require_constants = __commonJS({ + "../../node_modules/ws/lib/constants.js"(exports, module2) { + "use strict"; + module2.exports = { + BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), + kListener: Symbol("kListener"), + kStatusCode: Symbol("status-code"), + kWebSocket: Symbol("websocket"), + NOOP: () => { + } + }; + } +}); + +// ../../node_modules/ws/lib/buffer-util.js +var require_buffer_util = __commonJS({ + "../../node_modules/ws/lib/buffer-util.js"(exports, module2) { + "use strict"; + var { EMPTY_BUFFER } = require_constants(); + function concat(list, totalLength) { + if (list.length === 0) + return EMPTY_BUFFER; + if (list.length === 1) + return list[0]; + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + if (offset < totalLength) + return target.slice(0, offset); + return target; + } + function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } + } + function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } + } + function toArrayBuffer(buf) { + if (buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + } + function toBuffer(data) { + toBuffer.readOnly = true; + if (Buffer.isBuffer(data)) + return data; + let buf; + if (data instanceof ArrayBuffer) { + buf = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + return buf; + } + module2.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask + }; + if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require("bufferutil"); + module2.exports.mask = function(source, mask, output, offset, length) { + if (length < 48) + _mask(source, mask, output, offset, length); + else + bufferUtil.mask(source, mask, output, offset, length); + }; + module2.exports.unmask = function(buffer, mask) { + if (buffer.length < 32) + _unmask(buffer, mask); + else + bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + } + } + } +}); + +// ../../node_modules/ws/lib/limiter.js +var require_limiter = __commonJS({ + "../../node_modules/ws/lib/limiter.js"(exports, module2) { + "use strict"; + var kDone = Symbol("kDone"); + var kRun = Symbol("kRun"); + var Limiter = class { + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + add(job) { + this.jobs.push(job); + this[kRun](); + } + [kRun]() { + if (this.pending === this.concurrency) + return; + if (this.jobs.length) { + const job = this.jobs.shift(); + this.pending++; + job(this[kDone]); + } + } + }; + module2.exports = Limiter; + } +}); + +// ../../node_modules/ws/lib/permessage-deflate.js +var require_permessage_deflate = __commonJS({ + "../../node_modules/ws/lib/permessage-deflate.js"(exports, module2) { + "use strict"; + var zlib = require("zlib"); + var bufferUtil = require_buffer_util(); + var Limiter = require_limiter(); + var { kStatusCode } = require_constants(); + var TRAILER = Buffer.from([0, 0, 255, 255]); + var kPerMessageDeflate = Symbol("permessage-deflate"); + var kTotalLength = Symbol("total-length"); + var kCallback = Symbol("callback"); + var kBuffers = Symbol("buffers"); + var kError = Symbol("error"); + var zlibLimiter; + var PerMessageDeflate = class { + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + this.params = null; + if (!zlibLimiter) { + const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; + zlibLimiter = new Limiter(concurrency); + } + } + static get extensionName() { + return "permessage-deflate"; + } + offer() { + const params = {}; + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + return params; + } + accept(configurations) { + configurations = this.normalizeParams(configurations); + this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); + return this.params; + } + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + if (this._deflate) { + const callback = this._deflate[kCallback]; + this._deflate.close(); + this._deflate = null; + if (callback) { + callback( + new Error( + "The deflate stream was closed while data was being processed" + ) + ); + } + } + } + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { + return false; + } + return true; + }); + if (!accepted) { + throw new Error("None of the extension offers can be accepted"); + } + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === "number") { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === "number") { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { + delete accepted.client_max_window_bits; + } + return accepted; + } + acceptAsClient(response) { + const params = response[0]; + if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === "number") { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + return params; + } + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + value = value[0]; + if (key === "client_max_window_bits") { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === "server_max_window_bits") { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + params[key] = value; + }); + }); + return configurations; + } + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + _decompress(data, fin, callback) { + const endpoint = this._isServer ? "client" : "server"; + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on("error", inflateOnError); + this._inflate.on("data", inflateOnData); + } + this._inflate[kCallback] = callback; + this._inflate.write(data); + if (fin) + this._inflate.write(TRAILER); + this._inflate.flush(() => { + const err = this._inflate[kError]; + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + const data2 = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + callback(null, data2); + }); + } + _compress(data, fin, callback) { + const endpoint = this._isServer ? "server" : "client"; + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + this._deflate.on("data", deflateOnData); + } + this._deflate[kCallback] = callback; + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + return; + } + let data2 = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + if (fin) + data2 = data2.slice(0, data2.length - 4); + this._deflate[kCallback] = null; + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + callback(null, data2); + }); + } + }; + module2.exports = PerMessageDeflate; + function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; + } + function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { + this[kBuffers].push(chunk); + return; + } + this[kError] = new RangeError("Max payload size exceeded"); + this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; + this[kError][kStatusCode] = 1009; + this.removeListener("data", inflateOnData); + this.reset(); + } + function inflateOnError(err) { + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); + } + } +}); + +// ../../node_modules/ws/lib/validation.js +var require_validation = __commonJS({ + "../../node_modules/ws/lib/validation.js"(exports, module2) { + "use strict"; + var tokenChars = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0 + ]; + function isValidStatusCode(code) { + return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; + } + function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + while (i < len) { + if ((buf[i] & 128) === 0) { + i++; + } else if ((buf[i] & 224) === 192) { + if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { + return false; + } + i += 2; + } else if ((buf[i] & 240) === 224) { + if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) { + return false; + } + i += 3; + } else if ((buf[i] & 248) === 240) { + if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { + return false; + } + i += 4; + } else { + return false; + } + } + return true; + } + module2.exports = { + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars + }; + if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require("utf-8-validate"); + module2.exports.isValidUTF8 = function(buf) { + return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + } + } + } +}); + +// ../../node_modules/ws/lib/receiver.js +var require_receiver = __commonJS({ + "../../node_modules/ws/lib/receiver.js"(exports, module2) { + "use strict"; + var { Writable } = require("stream"); + var PerMessageDeflate = require_permessage_deflate(); + var { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket + } = require_constants(); + var { concat, toArrayBuffer, unmask } = require_buffer_util(); + var { isValidStatusCode, isValidUTF8 } = require_validation(); + var GET_INFO = 0; + var GET_PAYLOAD_LENGTH_16 = 1; + var GET_PAYLOAD_LENGTH_64 = 2; + var GET_MASK = 3; + var GET_DATA = 4; + var INFLATING = 5; + var Receiver2 = class extends Writable { + constructor(options = {}) { + super(); + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = void 0; + this._bufferedBytes = 0; + this._buffers = []; + this._compressed = false; + this._payloadLength = 0; + this._mask = void 0; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + this._state = GET_INFO; + this._loop = false; + } + _write(chunk, encoding, cb) { + if (this._opcode === 8 && this._state == GET_INFO) + return cb(); + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + consume(n) { + this._bufferedBytes -= n; + if (n === this._buffers[0].length) + return this._buffers.shift(); + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = buf.slice(n); + return buf.slice(0, n); + } + const dst = Buffer.allocUnsafe(n); + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = buf.slice(n); + } + n -= buf.length; + } while (n > 0); + return dst; + } + startLoop(cb) { + let err; + this._loop = true; + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: + this._loop = false; + return; + } + } while (this._loop); + cb(err); + } + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + const buf = this.consume(2); + if ((buf[0] & 48) !== 0) { + this._loop = false; + return error( + RangeError, + "RSV2 and RSV3 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_2_3" + ); + } + const compressed = (buf[0] & 64) === 64; + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + } + this._fin = (buf[0] & 128) === 128; + this._opcode = buf[0] & 15; + this._payloadLength = buf[1] & 127; + if (this._opcode === 0) { + if (compressed) { + this._loop = false; + return error( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + } + if (!this._fragmented) { + this._loop = false; + return error( + RangeError, + "invalid opcode 0", + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + } + this._opcode = this._fragmented; + } else if (this._opcode === 1 || this._opcode === 2) { + if (this._fragmented) { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + } + this._compressed = compressed; + } else if (this._opcode > 7 && this._opcode < 11) { + if (!this._fin) { + this._loop = false; + return error( + RangeError, + "FIN must be set", + true, + 1002, + "WS_ERR_EXPECTED_FIN" + ); + } + if (compressed) { + this._loop = false; + return error( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + } + if (this._payloadLength > 125) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" + ); + } + } else { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + } + if (!this._fin && !this._fragmented) + this._fragmented = this._opcode; + this._masked = (buf[1] & 128) === 128; + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error( + RangeError, + "MASK must be set", + true, + 1002, + "WS_ERR_EXPECTED_MASK" + ); + } + } else if (this._masked) { + this._loop = false; + return error( + RangeError, + "MASK must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_MASK" + ); + } + if (this._payloadLength === 126) + this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) + this._state = GET_PAYLOAD_LENGTH_64; + else + return this.haveLength(); + } + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + "Unsupported WebSocket frame: payload length > 2^53 - 1", + false, + 1009, + "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" + ); + } + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + haveLength() { + if (this._payloadLength && this._opcode < 8) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error( + RangeError, + "Max payload size exceeded", + false, + 1009, + "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" + ); + } + } + if (this._masked) + this._state = GET_MASK; + else + this._state = GET_DATA; + } + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + this._mask = this.consume(4); + this._state = GET_DATA; + } + getData(cb) { + let data = EMPTY_BUFFER; + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + data = this.consume(this._payloadLength); + if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { + unmask(data, this._mask); + } + } + if (this._opcode > 7) + return this.controlMessage(data); + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + if (data.length) { + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + return this.dataMessage(); + } + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) + return cb(err); + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error( + RangeError, + "Max payload size exceeded", + false, + 1009, + "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" + ) + ); + } + this._fragments.push(buf); + } + const er = this.dataMessage(); + if (er) + return cb(er); + this.startLoop(cb); + }); + } + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + if (this._opcode === 2) { + let data; + if (this._binaryType === "nodebuffer") { + data = concat(fragments, messageLength); + } else if (this._binaryType === "arraybuffer") { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + this.emit("message", data, true); + } else { + const buf = concat(fragments, messageLength); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error( + Error, + "invalid UTF-8 sequence", + true, + 1007, + "WS_ERR_INVALID_UTF8" + ); + } + this.emit("message", buf, false); + } + } + this._state = GET_INFO; + } + controlMessage(data) { + if (this._opcode === 8) { + this._loop = false; + if (data.length === 0) { + this.emit("conclude", 1005, EMPTY_BUFFER); + this.end(); + } else if (data.length === 1) { + return error( + RangeError, + "invalid payload length 1", + true, + 1002, + "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" + ); + } else { + const code = data.readUInt16BE(0); + if (!isValidStatusCode(code)) { + return error( + RangeError, + `invalid status code ${code}`, + true, + 1002, + "WS_ERR_INVALID_CLOSE_CODE" + ); + } + const buf = data.slice(2); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error( + Error, + "invalid UTF-8 sequence", + true, + 1007, + "WS_ERR_INVALID_UTF8" + ); + } + this.emit("conclude", code, buf); + this.end(); + } + } else if (this._opcode === 9) { + this.emit("ping", data); + } else { + this.emit("pong", data); + } + this._state = GET_INFO; + } + }; + module2.exports = Receiver2; + function error(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + Error.captureStackTrace(err, error); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } + } +}); + +// ../../node_modules/ws/lib/sender.js +var require_sender = __commonJS({ + "../../node_modules/ws/lib/sender.js"(exports, module2) { + "use strict"; + var net = require("net"); + var tls = require("tls"); + var { randomFillSync } = require("crypto"); + var PerMessageDeflate = require_permessage_deflate(); + var { EMPTY_BUFFER } = require_constants(); + var { isValidStatusCode } = require_validation(); + var { mask: applyMask, toBuffer } = require_buffer_util(); + var kByteLength = Symbol("kByteLength"); + var maskBuffer = Buffer.alloc(4); + var Sender2 = class { + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + this._socket = socket; + this._firstFragment = true; + this._compress = false; + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + let dataLength; + if (typeof data === "string") { + if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + let payloadLength = dataLength; + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + target[0] = options.fin ? options.opcode | 128 : options.opcode; + if (options.rsv1) + target[0] |= 64; + target[1] = payloadLength; + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + if (!options.mask) + return [target, data]; + target[1] |= 128; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + if (skipMasking) + return [target, data]; + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + close(code, data, mask, cb) { + let buf; + if (code === void 0) { + buf = EMPTY_BUFFER; + } else if (typeof code !== "number" || !isValidStatusCode(code)) { + throw new TypeError("First argument must be a valid error code number"); + } else if (data === void 0 || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + if (length > 123) { + throw new RangeError("The message must not be greater than 123 bytes"); + } + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + if (typeof data === "string") { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 8, + readOnly: false, + rsv1: false + }; + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender2.frame(buf, options), cb); + } + } + ping(data, mask, cb) { + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 9, + readOnly, + rsv1: false + }; + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender2.frame(data, options), cb); + } + } + pong(data, mask, cb) { + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 10, + readOnly, + rsv1: false + }; + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender2.frame(data, options), cb); + } + } + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + if (options.fin) + this._firstFragment = true; + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender2.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender2.frame(data, options), cb); + return; + } + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + "The socket was closed while data was being compressed" + ); + if (typeof cb === "function") + cb(err); + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + if (typeof callback === "function") + callback(err); + } + return; + } + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender2.frame(buf, options), cb); + this.dequeue(); + }); + } + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } + }; + module2.exports = Sender2; + } +}); + +// ../../node_modules/ws/lib/event-target.js +var require_event_target = __commonJS({ + "../../node_modules/ws/lib/event-target.js"(exports, module2) { + "use strict"; + var { kForOnEventAttribute, kListener } = require_constants(); + var kCode = Symbol("kCode"); + var kData = Symbol("kData"); + var kError = Symbol("kError"); + var kMessage = Symbol("kMessage"); + var kReason = Symbol("kReason"); + var kTarget = Symbol("kTarget"); + var kType = Symbol("kType"); + var kWasClean = Symbol("kWasClean"); + var Event = class { + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + get target() { + return this[kTarget]; + } + get type() { + return this[kType]; + } + }; + Object.defineProperty(Event.prototype, "target", { enumerable: true }); + Object.defineProperty(Event.prototype, "type", { enumerable: true }); + var CloseEvent = class extends Event { + constructor(type, options = {}) { + super(type); + this[kCode] = options.code === void 0 ? 0 : options.code; + this[kReason] = options.reason === void 0 ? "" : options.reason; + this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; + } + get code() { + return this[kCode]; + } + get reason() { + return this[kReason]; + } + get wasClean() { + return this[kWasClean]; + } + }; + Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); + var ErrorEvent = class extends Event { + constructor(type, options = {}) { + super(type); + this[kError] = options.error === void 0 ? null : options.error; + this[kMessage] = options.message === void 0 ? "" : options.message; + } + get error() { + return this[kError]; + } + get message() { + return this[kMessage]; + } + }; + Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); + Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); + var MessageEvent = class extends Event { + constructor(type, options = {}) { + super(type); + this[kData] = options.data === void 0 ? null : options.data; + } + get data() { + return this[kData]; + } + }; + Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); + var EventTarget = { + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { + return; + } + } + let wrapper; + if (type === "message") { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent("message", { + data: isBinary ? data : data.toString() + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "close") { + wrapper = function onClose(code, message) { + const event = new CloseEvent("close", { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "error") { + wrapper = function onError(error) { + const event = new ErrorEvent("error", { + error, + message: error.message + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "open") { + wrapper = function onOpen() { + const event = new Event("open"); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } + }; + module2.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent + }; + function callListener(listener, thisArg, event) { + if (typeof listener === "object" && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } + } + } +}); + +// ../../node_modules/ws/lib/extension.js +var require_extension = __commonJS({ + "../../node_modules/ws/lib/extension.js"(exports, module2) { + "use strict"; + var { tokenChars } = require_validation(); + function push(dest, name, elem) { + if (dest[name] === void 0) + dest[name] = [elem]; + else + dest[name].push(elem); + } + function parse(header) { + const offers = /* @__PURE__ */ Object.create(null); + let params = /* @__PURE__ */ Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + for (; i < header.length; i++) { + code = header.charCodeAt(i); + if (extensionName === void 0) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (i !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) + end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + const name = header.slice(start, end); + if (code === 44) { + push(offers, name, params); + params = /* @__PURE__ */ Object.create(null); + } else { + extensionName = name; + } + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === void 0) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (code === 32 || code === 9) { + if (end === -1 && start !== -1) + end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + push(params, header.slice(start, end), true); + if (code === 44) { + push(offers, extensionName, params); + params = /* @__PURE__ */ Object.create(null); + extensionName = void 0; + } + start = end = -1; + } else if (code === 61 && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) + start = i; + else if (!mustUnescape) + mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (code === 34 && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 92) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 34 && header.charCodeAt(i - 1) === 61) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (start !== -1 && (code === 32 || code === 9)) { + if (end === -1) + end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ""); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 44) { + push(offers, extensionName, params); + params = /* @__PURE__ */ Object.create(null); + extensionName = void 0; + } + paramName = void 0; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + if (start === -1 || inQuotes || code === 32 || code === 9) { + throw new SyntaxError("Unexpected end of input"); + } + if (end === -1) + end = i; + const token = header.slice(start, end); + if (extensionName === void 0) { + push(offers, token, params); + } else { + if (paramName === void 0) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, "")); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + return offers; + } + function format(extensions) { + return Object.keys(extensions).map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) + configurations = [configurations]; + return configurations.map((params) => { + return [extension].concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) + values = [values]; + return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); + }) + ).join("; "); + }).join(", "); + }).join(", "); + } + module2.exports = { format, parse }; + } +}); + +// ../../node_modules/ws/lib/websocket.js +var require_websocket = __commonJS({ + "../../node_modules/ws/lib/websocket.js"(exports, module2) { + "use strict"; + var EventEmitter = require("events"); + var https2 = require("https"); + var http2 = require("http"); + var net = require("net"); + var tls = require("tls"); + var { randomBytes, createHash } = require("crypto"); + var { Readable } = require("stream"); + var { URL: URL2 } = require("url"); + var PerMessageDeflate = require_permessage_deflate(); + var Receiver2 = require_receiver(); + var Sender2 = require_sender(); + var { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP + } = require_constants(); + var { + EventTarget: { addEventListener, removeEventListener } + } = require_event_target(); + var { format, parse } = require_extension(); + var { toBuffer } = require_buffer_util(); + var closeTimeout = 30 * 1e3; + var kAborted = Symbol("kAborted"); + var protocolVersions = [8, 13]; + var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; + var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + var WebSocket3 = class extends EventEmitter { + constructor(address, protocols, options) { + super(); + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ""; + this._readyState = WebSocket3.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + if (protocols === void 0) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === "object" && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + get binaryType() { + return this._binaryType; + } + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) + return; + this._binaryType = type; + if (this._receiver) + this._receiver._binaryType = type; + } + get bufferedAmount() { + if (!this._socket) + return this._bufferedAmount; + return this._socket._writableState.length + this._sender._bufferedBytes; + } + get extensions() { + return Object.keys(this._extensions).join(); + } + get isPaused() { + return this._paused; + } + get onclose() { + return null; + } + get onerror() { + return null; + } + get onopen() { + return null; + } + get onmessage() { + return null; + } + get protocol() { + return this._protocol; + } + get readyState() { + return this._readyState; + } + get url() { + return this._url; + } + setSocket(socket, head, options) { + const receiver = new Receiver2({ + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + this._sender = new Sender2(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + receiver.on("conclude", receiverOnConclude); + receiver.on("drain", receiverOnDrain); + receiver.on("error", receiverOnError); + receiver.on("message", receiverOnMessage); + receiver.on("ping", receiverOnPing); + receiver.on("pong", receiverOnPong); + socket.setTimeout(0); + socket.setNoDelay(); + if (head.length > 0) + socket.unshift(head); + socket.on("close", socketOnClose); + socket.on("data", socketOnData); + socket.on("end", socketOnEnd); + socket.on("error", socketOnError); + this._readyState = WebSocket3.OPEN; + this.emit("open"); + } + emitClose() { + if (!this._socket) { + this._readyState = WebSocket3.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + return; + } + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + this._receiver.removeAllListeners(); + this._readyState = WebSocket3.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + } + close(code, data) { + if (this.readyState === WebSocket3.CLOSED) + return; + if (this.readyState === WebSocket3.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + return abortHandshake(this, this._req, msg); + } + if (this.readyState === WebSocket3.CLOSING) { + if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { + this._socket.end(); + } + return; + } + this._readyState = WebSocket3.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + if (err) + return; + this._closeFrameSent = true; + if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { + this._socket.end(); + } + }); + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + pause() { + if (this.readyState === WebSocket3.CONNECTING || this.readyState === WebSocket3.CLOSED) { + return; + } + this._paused = true; + this._socket.pause(); + } + ping(data, mask, cb) { + if (this.readyState === WebSocket3.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof data === "function") { + cb = data; + data = mask = void 0; + } else if (typeof mask === "function") { + cb = mask; + mask = void 0; + } + if (typeof data === "number") + data = data.toString(); + if (this.readyState !== WebSocket3.OPEN) { + sendAfterClose(this, data, cb); + return; + } + if (mask === void 0) + mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + pong(data, mask, cb) { + if (this.readyState === WebSocket3.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof data === "function") { + cb = data; + data = mask = void 0; + } else if (typeof mask === "function") { + cb = mask; + mask = void 0; + } + if (typeof data === "number") + data = data.toString(); + if (this.readyState !== WebSocket3.OPEN) { + sendAfterClose(this, data, cb); + return; + } + if (mask === void 0) + mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + resume() { + if (this.readyState === WebSocket3.CONNECTING || this.readyState === WebSocket3.CLOSED) { + return; + } + this._paused = false; + if (!this._receiver._writableState.needDrain) + this._socket.resume(); + } + send(data, options, cb) { + if (this.readyState === WebSocket3.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof options === "function") { + cb = options; + options = {}; + } + if (typeof data === "number") + data = data.toString(); + if (this.readyState !== WebSocket3.OPEN) { + sendAfterClose(this, data, cb); + return; + } + const opts = { + binary: typeof data !== "string", + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + terminate() { + if (this.readyState === WebSocket3.CLOSED) + return; + if (this.readyState === WebSocket3.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + return abortHandshake(this, this._req, msg); + } + if (this._socket) { + this._readyState = WebSocket3.CLOSING; + this._socket.destroy(); + } + } + }; + Object.defineProperty(WebSocket3, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket3.prototype, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket3, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket3.prototype, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket3, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket3.prototype, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket3, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + Object.defineProperty(WebSocket3.prototype, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + [ + "binaryType", + "bufferedAmount", + "extensions", + "isPaused", + "protocol", + "readyState", + "url" + ].forEach((property) => { + Object.defineProperty(WebSocket3.prototype, property, { enumerable: true }); + }); + ["open", "error", "close", "message"].forEach((method) => { + Object.defineProperty(WebSocket3.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) + return listener[kListener]; + } + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + if (typeof handler !== "function") + return; + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); + }); + WebSocket3.prototype.addEventListener = addEventListener; + WebSocket3.prototype.removeEventListener = removeEventListener; + module2.exports = WebSocket3; + function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: void 0, + socketPath: void 0, + hostname: void 0, + protocol: void 0, + timeout: void 0, + method: "GET", + host: void 0, + path: void 0, + port: void 0 + }; + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` + ); + } + let parsedUrl; + if (address instanceof URL2) { + parsedUrl = address; + websocket._url = address.href; + } else { + try { + parsedUrl = new URL2(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + websocket._url = address; + } + const isSecure = parsedUrl.protocol === "wss:"; + const isIpcUrl = parsedUrl.protocol === "ws+unix:"; + let invalidUrlMessage; + if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { + invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"`; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = "The URL contains a fragment identifier"; + } + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString("base64"); + const request = isSecure ? https2.request : http2.request; + const protocolSet = /* @__PURE__ */ new Set(); + let perMessageDeflate; + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + "Sec-WebSocket-Version": opts.protocolVersion, + "Sec-WebSocket-Key": key, + Connection: "Upgrade", + Upgrade: "websocket" + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers["Sec-WebSocket-Extensions"] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { + throw new SyntaxError( + "An invalid or duplicated subprotocol was specified" + ); + } + protocolSet.add(protocol); + } + opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers["Sec-WebSocket-Origin"] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + if (isIpcUrl) { + const parts = opts.path.split(":"); + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + let req; + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; + const headers = options && options.headers; + options = { ...options, headers: {} }; + if (headers) { + for (const [key2, value] of Object.entries(headers)) { + options.headers[key2.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount("redirect") === 0) { + const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; + if (!isSameHost || websocket._originalSecure && !isSecure) { + delete opts.headers.authorization; + delete opts.headers.cookie; + if (!isSameHost) + delete opts.headers.host; + opts.auth = void 0; + } + } + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); + } + req = websocket._req = request(opts); + if (websocket._redirects) { + websocket.emit("redirect", websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + if (opts.timeout) { + req.on("timeout", () => { + abortHandshake(websocket, req, "Opening handshake has timed out"); + }); + } + req.on("error", (err) => { + if (req === null || req[kAborted]) + return; + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + req.on("response", (res) => { + const location2 = res.headers.location; + const statusCode = res.statusCode; + if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, "Maximum redirects exceeded"); + return; + } + req.abort(); + let addr; + try { + addr = new URL2(location2, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location2}`); + emitErrorAndClose(websocket, err); + return; + } + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit("unexpected-response", req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + req.on("upgrade", (res, socket, head) => { + websocket.emit("upgrade", res); + if (websocket.readyState !== WebSocket3.CONNECTING) + return; + req = websocket._req = null; + if (res.headers.upgrade.toLowerCase() !== "websocket") { + abortHandshake(websocket, socket, "Invalid Upgrade header"); + return; + } + const digest = createHash("sha1").update(key + GUID).digest("base64"); + if (res.headers["sec-websocket-accept"] !== digest) { + abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); + return; + } + const serverProt = res.headers["sec-websocket-protocol"]; + let protError; + if (serverProt !== void 0) { + if (!protocolSet.size) { + protError = "Server sent a subprotocol but none was requested"; + } else if (!protocolSet.has(serverProt)) { + protError = "Server sent an invalid subprotocol"; + } + } else if (protocolSet.size) { + protError = "Server sent no subprotocol"; + } + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + if (serverProt) + websocket._protocol = serverProt; + const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; + if (secWebSocketExtensions !== void 0) { + if (!perMessageDeflate) { + const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; + abortHandshake(websocket, socket, message); + return; + } + let extensions; + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message); + return; + } + const extensionNames = Object.keys(extensions); + if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { + const message = "Server indicated an extension that was not requested"; + abortHandshake(websocket, socket, message); + return; + } + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message); + return; + } + websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + websocket.setSocket(socket, head, { + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + req.end(); + } + function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket3.CLOSING; + websocket.emit("error", err); + websocket.emitClose(); + } + function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); + } + function tlsConnect(options) { + options.path = void 0; + if (!options.servername && options.servername !== "") { + options.servername = net.isIP(options.host) ? "" : options.host; + } + return tls.connect(options); + } + function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket3.CLOSING; + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + if (stream.socket && !stream.socket.destroyed) { + stream.socket.destroy(); + } + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once("error", websocket.emit.bind(websocket, "error")); + stream.once("close", websocket.emitClose.bind(websocket)); + } + } + function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + if (websocket._socket) + websocket._sender._bufferedBytes += length; + else + websocket._bufferedAmount += length; + } + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` + ); + cb(err); + } + } + function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + if (websocket._socket[kWebSocket] === void 0) + return; + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + if (code === 1005) + websocket.close(); + else + websocket.close(code, reason); + } + function receiverOnDrain() { + const websocket = this[kWebSocket]; + if (!websocket.isPaused) + websocket._socket.resume(); + } + function receiverOnError(err) { + const websocket = this[kWebSocket]; + if (websocket._socket[kWebSocket] !== void 0) { + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + websocket.close(err[kStatusCode]); + } + websocket.emit("error", err); + } + function receiverOnFinish() { + this[kWebSocket].emitClose(); + } + function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit("message", data, isBinary); + } + function receiverOnPing(data) { + const websocket = this[kWebSocket]; + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit("ping", data); + } + function receiverOnPong(data) { + this[kWebSocket].emit("pong", data); + } + function resume(stream) { + stream.resume(); + } + function socketOnClose() { + const websocket = this[kWebSocket]; + this.removeListener("close", socketOnClose); + this.removeListener("data", socketOnData); + this.removeListener("end", socketOnEnd); + websocket._readyState = WebSocket3.CLOSING; + let chunk; + if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) { + websocket._receiver.write(chunk); + } + websocket._receiver.end(); + this[kWebSocket] = void 0; + clearTimeout(websocket._closeTimer); + if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { + websocket.emitClose(); + } else { + websocket._receiver.on("error", receiverOnFinish); + websocket._receiver.on("finish", receiverOnFinish); + } + } + function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } + } + function socketOnEnd() { + const websocket = this[kWebSocket]; + websocket._readyState = WebSocket3.CLOSING; + websocket._receiver.end(); + this.end(); + } + function socketOnError() { + const websocket = this[kWebSocket]; + this.removeListener("error", socketOnError); + this.on("error", NOOP); + if (websocket) { + websocket._readyState = WebSocket3.CLOSING; + this.destroy(); + } + } + } +}); + +// ../../node_modules/ws/lib/subprotocol.js +var require_subprotocol = __commonJS({ + "../../node_modules/ws/lib/subprotocol.js"(exports, module2) { + "use strict"; + var { tokenChars } = require_validation(); + function parse(header) { + const protocols = /* @__PURE__ */ new Set(); + let start = -1; + let end = -1; + let i = 0; + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (i !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) + end = i; + } else if (code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + const protocol2 = header.slice(start, end); + if (protocols.has(protocol2)) { + throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); + } + protocols.add(protocol2); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + if (start === -1 || end !== -1) { + throw new SyntaxError("Unexpected end of input"); + } + const protocol = header.slice(start, i); + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + protocols.add(protocol); + return protocols; + } + module2.exports = { parse }; + } +}); + +// ../../node_modules/ws/lib/websocket-server.js +var require_websocket_server = __commonJS({ + "../../node_modules/ws/lib/websocket-server.js"(exports, module2) { + "use strict"; + var EventEmitter = require("events"); + var http2 = require("http"); + var https2 = require("https"); + var net = require("net"); + var tls = require("tls"); + var { createHash } = require("crypto"); + var extension = require_extension(); + var PerMessageDeflate = require_permessage_deflate(); + var subprotocol = require_subprotocol(); + var WebSocket3 = require_websocket(); + var { GUID, kWebSocket } = require_constants(); + var keyRegex = /^[+/0-9A-Za-z]{22}==$/; + var RUNNING = 0; + var CLOSING = 1; + var CLOSED = 2; + var WebSocketServer2 = class extends EventEmitter { + constructor(options, callback) { + super(); + options = { + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, + server: null, + host: null, + path: null, + port: null, + WebSocket: WebSocket3, + ...options + }; + if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options must be specified' + ); + } + if (options.port != null) { + this._server = http2.createServer((req, res) => { + const body = http2.STATUS_CODES[426]; + res.writeHead(426, { + "Content-Length": body.length, + "Content-Type": "text/plain" + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + if (this._server) { + const emitConnection = this.emit.bind(this, "connection"); + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, "listening"), + error: this.emit.bind(this, "error"), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + if (options.perMessageDeflate === true) + options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = /* @__PURE__ */ new Set(); + this._shouldEmitClose = false; + } + this.options = options; + this._state = RUNNING; + } + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + if (!this._server) + return null; + return this._server.address(); + } + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once("close", () => { + cb(new Error("The server is not running")); + }); + } + process.nextTick(emitClose, this); + return; + } + if (cb) + this.once("close", cb); + if (this._state === CLOSING) + return; + this._state = CLOSING; + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server2 = this._server; + this._removeListeners(); + this._removeListeners = this._server = null; + server2.close(() => { + emitClose(this); + }); + } + } + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf("?"); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + if (pathname !== this.options.path) + return false; + } + return true; + } + handleUpgrade(req, socket, head, cb) { + socket.on("error", socketOnError); + const key = req.headers["sec-websocket-key"]; + const version = +req.headers["sec-websocket-version"]; + if (req.method !== "GET") { + const message = "Invalid HTTP method"; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + if (req.headers.upgrade.toLowerCase() !== "websocket") { + const message = "Invalid Upgrade header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + if (!key || !keyRegex.test(key)) { + const message = "Missing or invalid Sec-WebSocket-Key header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + if (version !== 8 && version !== 13) { + const message = "Missing or invalid Sec-WebSocket-Version header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; + let protocols = /* @__PURE__ */ new Set(); + if (secWebSocketProtocol !== void 0) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = "Invalid Sec-WebSocket-Protocol header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; + const extensions = {}; + if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + try { + const offers = extension.parse(secWebSocketExtensions); + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + if (this.options.verifyClient) { + const info = { + origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + if (!this.options.verifyClient(info)) + return abortHandshake(socket, 401); + } + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + if (!socket.readable || !socket.writable) + return socket.destroy(); + if (socket[kWebSocket]) { + throw new Error( + "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" + ); + } + if (this._state > RUNNING) + return abortHandshake(socket, 503); + const digest = createHash("sha1").update(key + GUID).digest("base64"); + const headers = [ + "HTTP/1.1 101 Switching Protocols", + "Upgrade: websocket", + "Connection: Upgrade", + `Sec-WebSocket-Accept: ${digest}` + ]; + const ws = new this.options.WebSocket(null); + if (protocols.size) { + const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + this.emit("headers", headers, req); + socket.write(headers.concat("\r\n").join("\r\n")); + socket.removeListener("error", socketOnError); + ws.setSocket(socket, head, { + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + if (this.clients) { + this.clients.add(ws); + ws.on("close", () => { + this.clients.delete(ws); + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + cb(ws, req); + } + }; + module2.exports = WebSocketServer2; + function addListeners(server2, map) { + for (const event of Object.keys(map)) + server2.on(event, map[event]); + return function removeListeners() { + for (const event of Object.keys(map)) { + server2.removeListener(event, map[event]); + } + }; + } + function emitClose(server2) { + server2._state = CLOSED; + server2.emit("close"); + } + function socketOnError() { + this.destroy(); + } + function abortHandshake(socket, code, message, headers) { + message = message || http2.STATUS_CODES[code]; + headers = { + Connection: "close", + "Content-Type": "text/html", + "Content-Length": Buffer.byteLength(message), + ...headers + }; + socket.once("finish", socket.destroy); + socket.end( + `HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r +` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message + ); + } + function abortHandshakeOrEmitwsClientError(server2, req, socket, code, message) { + if (server2.listenerCount("wsClientError")) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + server2.emit("wsClientError", err, socket, req); + } else { + abortHandshake(socket, code, message); + } + } + } +}); + +// ../../services/EventHandler.ts +var EventHandler = class { + constructor(data) { + this.pushToState = {}; + this.data = {}; + this.triggers = {}; + this.setState = (updateObj) => { + Object.assign(this.data, updateObj); + for (const prop of Object.getOwnPropertyNames(updateObj)) { + if (this.triggers[prop]) + this.triggers[prop].forEach((obj) => obj.onchange(this.data[prop])); + } + return this.data; + }; + this.setValue = (key, value) => { + this.data[key] = value; + if (this.triggers[key]) + this.triggers[key].forEach((obj) => obj.onchange(this.data[key])); + }; + this.subscribeTrigger = (key, onchange) => { + if (key) { + if (!this.triggers[key]) { + this.triggers[key] = []; + } + let l = this.triggers[key].length; + this.triggers[key].push({ sub: l, onchange }); + return this.triggers[key].length - 1; + } else + return void 0; + }; + this.unsubscribeTrigger = (key, sub) => { + let triggers = this.triggers[key]; + if (triggers) { + if (!sub) + delete this.triggers[key]; + else { + let sub2 = void 0; + let obj = triggers.find((o, i) => { + if (o.sub === sub2) { + sub2 = i; + return true; + } + }); + if (obj) + triggers.splice(sub2, 1); + if (this.onRemoved) + this.onRemoved(obj); + return true; + } + } + }; + this.subscribeTriggerOnce = (key, onchange) => { + let sub; + let changed = (value) => { + onchange(value); + this.unsubscribeTrigger(key, sub); + }; + sub = this.subscribeTrigger(key, changed); + }; + this.getTrigger = (key, sub) => { + for (const s in this.triggers[key]) { + if (this.triggers[key][s].sub === sub) + return this.triggers[key][s]; + } + }; + if (typeof data === "object") + this.data = data; + } +}; + +// ../../Graph.ts +var state = new EventHandler(); +var GraphNode = class { + constructor(properties, parent, graph) { + this.__node = { + tag: `node${Math.floor(Math.random() * 1e15)}`, + unique: `${Math.random()}`, + state + }; + this.__subscribe = (callback, key, subInput, bound, target) => { + const subscribeToFunction = (k, setTarget = (callback2, target2) => callback2, triggerCallback = callback) => { + let sub = this.__node.state.subscribeTrigger(k, triggerCallback); + let trigger = this.__node.state.getTrigger(k, sub); + trigger.source = this.__node.tag; + if (key) + trigger.key = key; + trigger.target = setTarget(callback); + if (bound) + trigger.bound = bound; + return sub; + }; + const subscribeToGraph = (callback2) => { + let fn = this.__node.graph.get(callback2); + if (!fn && callback2.includes(".")) { + let n = this.__node.graph.get(callback2.substring(0, callback2.lastIndexOf("."))); + let key2 = callback2.substring(callback2.lastIndexOf(".") + 1); + if (n && typeof n[key2] === "function") + callback2 = (...args) => { + return n[key2](...args); + }; + } + }; + if (key) { + if (!this.__node.localState) { + this.__addLocalState(this); + } + if (typeof callback === "string") { + if (typeof this[callback] === "function") + callback = this[callback]; + else if (this.__node.graph) + subscribeToGraph(callback); + } + let sub; + let k = subInput ? this.__node.unique + "." + key + "input" : this.__node.unique + "." + key; + if (typeof callback === "function") + sub = subscribeToFunction(k); + else if (callback?.__node) + sub = subscribeToFunction( + k, + (callback2, target2) => target2 ? target2 : callback2.__node.unique, + (state2) => { + if (callback.__operator) + callback.__operator(state2); + } + ); + return sub; + } else { + if (typeof callback === "string") { + if (this.__node.graph) + callback = this.__node.graph.get(callback); + else + callback = this.__node.graph.nodes.get(callback); + } + let sub; + let k = subInput ? this.__node.unique + "input" : this.__node.unique; + if (typeof callback === "function") + sub = subscribeToFunction(k); + else if (callback?.__node) + sub = subscribeToFunction( + k, + (callback2, target2) => target2 ? target2 : callback2.__node.unique, + (state2) => { + if (callback.__operator) + callback.__operator(state2); + } + ); + return sub; + } + }; + this.__unsubscribe = (sub, key, subInput) => { + if (key) { + return this.__node.state.unsubscribeTrigger(subInput ? this.__node.unique + "." + key + "input" : this.__node.unique + "." + key, sub); + } else + return this.__node.state.unsubscribeTrigger(subInput ? this.__node.unique + "input" : this.__node.unique, sub); + }; + this.__setOperator = (fn) => { + fn = fn.bind(this); + this.__operator = (...args) => { + if (this.__node.inputState) + this.__node.state.setValue(this.__node.unique + "input", args); + let result = fn(...args); + if (typeof result?.then === "function") { + result.then((res) => { + if (res !== void 0) + this.__node.state.setValue(this.__node.unique, res); + }).catch(console.error); + } else if (result !== void 0) + this.__node.state.setValue(this.__node.unique, result); + return result; + }; + return this.__operator; + }; + this.__proxyObject = (obj) => { + let allProps = getAllProperties(obj); + for (const k of allProps) { + if (typeof this[k] === "undefined") { + if (typeof obj[k] === "function") { + this[k] = (...args) => { + if (this.__node.inputState) + this.__node.state.setValue(this.__node.unique + "." + k + "input", args); + let result = obj[k](...args); + if (this.__node.state.triggers[this.__node.unique + "." + k]) { + if (typeof result?.then === "function") { + result.then((res) => { + this.__node.state.setValue(this.__node.unique + "." + k, res); + }).catch(console.error); + } else + this.__node.state.setValue(this.__node.unique + "." + k, result); + } + return result; + }; + } else { + let definition = { + get: () => { + return obj[k]; + }, + set: (value) => { + obj[k] = value; + if (this.__node.state.triggers[this.__node.unique + "." + k]) + this.__node.state.setValue(this.__node.unique + "." + k, value); + }, + enumerable: true, + configurable: true + }; + Object.defineProperty(this, k, definition); + } + } + } + }; + let orig = properties; + if (typeof properties === "function") { + properties = { + __operator: properties, + __node: { + forward: true, + tag: properties.name + } + }; + } else if (typeof properties === "string") { + if (graph?.get(properties)) { + properties = graph.get(properties); + } + } + if (!properties.__node.initial) + properties.__node.initial = orig; + if (typeof properties === "object") { + if (properties.__props) { + if (typeof properties.__props === "function") + properties.__props = new properties.__props(); + if (typeof properties.__props === "object") { + this.__proxyObject(properties.__props); + } + } + if (typeof properties.__node === "string") { + if (graph?.get(properties.__node.tag)) { + properties = graph.get(properties.__node.tag); + } else + properties.__node = {}; + } else if (!properties.__node) + properties.__node = {}; + if (!properties.__parent && parent) + properties.__parent = parent; + if (graph) { + properties.__node.graph = graph; + } + if (properties.__operator) { + if (typeof properties.__operator === "string") { + if (graph) { + let n = graph.get(properties.__operator); + if (n) + properties.__operator = n.__operator; + if (!properties.__node.tag && properties.__operator.name) + properties.__node.tag = properties.__operator.name; + } + } + if (typeof properties.__operator === "function") + properties.__operator = this.__setOperator(properties.__operator); + } + if (!properties.__node.tag) { + if (properties.__operator?.name) + properties.__node.tag = properties.__operator.name; + else + properties.__node.tag = `node${Math.floor(Math.random() * 1e15)}`; + } + if (parent?.__node && !(parent instanceof Graph || properties instanceof Graph)) + properties.__node.tag = parent.__node.tag + "." + properties.__node.tag; + if (parent instanceof Graph && properties instanceof Graph) { + if (properties.__node.loaders) + Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); + if (parent.__node.mapGraphs) { + properties.__node.nodes.forEach((n) => { + parent.set(properties.__node.tag + "." + n.__node.tag, n); + }); + let ondelete = () => { + properties.__node.nodes.forEach((n) => { + parent.__node.nodes.delete(properties.__node.tag + "." + n.__node.tag); + }); + }; + this.__addDisconnected(ondelete); + } + } + properties.__node = Object.assign(this.__node, properties.__node); + let keys = Object.getOwnPropertyNames(properties); + for (const key of keys) { + this[key] = properties[key]; + } + if (properties.__operator && parent instanceof GraphNode && parent.__operator) { + let sub = parent.__subscribe(this); + let ondelete = () => { + parent?.__unsubscribe(sub); + }; + this.__addDisconnected(ondelete); + } else if (typeof properties.default === "function" && !properties.__operator) { + let fn = properties.default.bind(this); + this.default = (...args) => { + if (this.__node.inputState) + this.__node.state.setValue(this.__node.unique + "input", args); + let result = fn(...args); + if (typeof result?.then === "function") { + result.then((res) => { + if (res !== void 0) + this.__node.state.setValue(this.__node.unique, res); + }).catch(console.error); + } else if (result !== void 0) + this.__node.state.setValue(this.__node.unique, result); + return result; + }; + properties.default = this.default; + } + if (properties instanceof Graph) + this.__node.source = properties; + } + } + __addLocalState(props) { + if (!props) + return; + if (!this.__node.localState) { + this.__node.localState = {}; + } + let localState = this.__node.localState; + for (let k in props) { + if (this.__props && this.__props[k]) + continue; + if (typeof props[k] === "function") { + if (!k.startsWith("_")) { + let fn = props[k].bind(this); + props[k] = (...args) => { + if (this.__node.inputState) + this.__node.state.setValue(this.__node.unique + "." + k + "input", args); + let result = fn(...args); + if (typeof result?.then === "function") { + if (this.__node.state.triggers[this.__node.unique + "." + k]) + result.then((res) => { + this.__node.state.setValue(this.__node.unique + "." + k, res); + }).catch(console.error); + } else if (this.__node.state.triggers[this.__node.unique + "." + k]) + this.__node.state.setValue(this.__node.unique + "." + k, result); + return result; + }; + this[k] = props[k]; + } + } else { + localState[k] = props[k]; + let definition = { + get: () => { + return localState[k]; + }, + set: (v) => { + localState[k] = v; + if (this.__node.state.triggers[this.__node.unique + "." + k]) + this.__node.state.setValue(this.__node.unique + "." + k, v); + }, + enumerable: true, + configurable: true + }; + Object.defineProperty(this, k, definition); + if (typeof this.__node.initial === "object") { + let dec = Object.getOwnPropertyDescriptor(this.__node.initial, k); + if (dec === void 0 || dec?.configurable) { + Object.defineProperty(this.__node.initial, k, definition); + } + } + } + } + } + __addOnconnected(callback) { + if (Array.isArray(this.__ondisconnected)) { + this.__onconnected.push(callback); + } else if (typeof this.__onconnected === "function") { + this.__onconnected = [callback, this.__onconnected]; + } else + this.__onconnected = callback; + } + __addDisconnected(callback) { + if (Array.isArray(this.__ondisconnected)) { + this.__ondisconnected.push(callback); + } else if (typeof this.__ondisconnected === "function") { + this.__ondisconnected = [callback, this.__ondisconnected]; + } else + this.__ondisconnected = callback; + } + __callConnected(node = this) { + if (typeof this.__onconnected === "function") { + this.__onconnected(this); + } else if (Array.isArray(this.__onconnected)) { + this.__onconnected.forEach((o) => { + o(this); + }); + } + } + __callDisconnected(node = this) { + if (typeof this.__ondisconnected === "function") + this.__ondisconnected(this); + else if (Array.isArray(this.__ondisconnected)) { + this.__ondisconnected.forEach((o) => { + o(this); + }); + } + } +}; +var Graph = class { + constructor(options) { + this.__node = { + tag: `graph${Math.floor(Math.random() * 1e15)}`, + nodes: /* @__PURE__ */ new Map(), + state + }; + this.init = (options) => { + if (options) { + recursivelyAssign(this.__node, options); + if (options.tree) + this.setTree(options.tree); + } + }; + this.setTree = (tree) => { + this.__node.tree = Object.assign(this.__node.tree ? this.__node.tree : {}, tree); + let cpy = Object.assign({}, tree); + delete cpy.__node; + let listeners = this.recursiveSet(cpy, this); + if (tree.__node) { + if (!tree.__node.tag) + tree.__node._tag = `tree${Math.floor(Math.random() * 1e15)}`; + else if (!this.get(tree.__node.tag)) { + let node = new GraphNode(tree, this, this); + for (const l in this.__node.loaders) { + this.__node.loaders[l](node, this, this, tree, tree); + } + this.set(node.__node.tag, node); + if (node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } + } + } + this.setListeners(listeners); + return cpy; + }; + this.setLoaders = (loaders2, replace) => { + if (replace) + this.__node.loaders = loaders2; + else + Object.assign(this.__node.loaders, loaders2); + return this.__node.loaders; + }; + this.add = (properties, parent) => { + let listeners = {}; + if (typeof parent === "string") + parent = this.get(parent); + if (typeof properties === "function") + properties = { __operator: properties }; + else if (typeof properties === "string") + properties = this.__node.tree[properties]; + let p = Object.assign({}, properties); + if (!p.__node) + p.__node = {}; + p.__node.initial = properties; + if (typeof properties === "object" && (!p?.__node?.tag || !this.get(p.__node.tag))) { + let node = new GraphNode(p, parent, this); + for (const l in this.__node.loaders) { + this.__node.loaders[l](node, parent, this, this.__node.tree, properties); + } + this.set(node.__node.tag, node); + this.__node.tree[node.__node.tag] = properties; + if (node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } + if (node.__children) { + node.__children = Object.assign({}, node.__children); + this.recursiveSet(node.__children, node, listeners); + } + this.setListeners(listeners); + node.__callConnected(); + return node; + } + return; + }; + this.recursiveSet = (t, parent, listeners = {}) => { + let keys = Object.getOwnPropertyNames(t); + for (const key of keys) { + let p = t[key]; + if (Array.isArray(p)) + continue; + if (typeof p === "function") + p = { __operator: p }; + else if (typeof p === "string") + p = this.__node.tree[p]; + else if (typeof p === "boolean") + p = this.__node.tree[key]; + if (typeof p === "object") { + p = Object.assign({}, p); + if (!p.__node) + p.__node = {}; + if (!p.__node.tag) + p.__node.tag = key; + p.__node.initial = t[key]; + if (this.get(p.__node.tag) && !(parent?.__node && this.get(parent.__node.tag + "." + p.__node.tag)) || parent?.__node && this.get(parent.__node.tag + "." + p.__node.tag)) + continue; + let node = new GraphNode(p, parent, this); + for (const l in this.__node.loaders) { + this.__node.loaders[l](node, parent, this, t, t[key]); + } + t[key] = node; + this.__node.tree[node.__node.tag] = p; + this.set(node.__node.tag, node); + if (node.__listeners) { + listeners[node.__node.tag] = node.__listeners; + } else if (node.__children) { + node.__children = Object.assign({}, node.__children); + this.recursiveSet(node.__children, node, listeners); + } + node.__callConnected(); + } + } + return listeners; + }; + this.remove = (node, clearListeners = true) => { + this.unsubscribe(node); + if (typeof node === "string") + node = this.get(node); + if (node instanceof GraphNode) { + this.delete(node.__node.tag); + delete this.__node.tree[node.__node.tag]; + if (clearListeners) { + this.clearListeners(node); + } + node.__callDisconnected(); + const recursiveRemove = (t) => { + for (const key in t) { + this.unsubscribe(t[key]); + this.delete(t[key].__node.tag); + delete this.__node.tree[t[key].__node.tag]; + this.delete(key); + delete this.__node.tree[key]; + t[key].__node.tag = t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".") + 1); + if (clearListeners) { + this.clearListeners(t[key]); + } + t[key].__callDisconnected(); + if (t[key].__children) { + recursiveRemove(t[key].__children); + } + } + }; + if (node.__children) { + recursiveRemove(node.__children); + } + } + if (node?.__node.tag && node?.__parent) { + delete node?.__parent; + node.__node.tag = node.__node.tag.substring(node.__node.tag.indexOf(".") + 1); + } + return node; + }; + this.run = (node, ...args) => { + if (typeof node === "string") { + let nd = this.get(node); + if (!nd && node.includes(".")) { + nd = this.get(node.substring(0, node.lastIndexOf("."))); + if (typeof nd?.[node.substring(node.lastIndexOf(".") + 1)] === "function") + return nd[node.substring(node.lastIndexOf(".") + 1)](...args); + } else if (nd?.__operator) + return nd.__operator(...args); + } + if (node?.__operator) { + return node?.__operator(...args); + } + }; + this.setListeners = (listeners) => { + for (const key in listeners) { + let node = this.get(key); + if (typeof listeners[key] === "object") { + for (const k in listeners[key]) { + let n = this.get(k); + let sub; + if (typeof listeners[key][k] !== "object") + listeners[key][k] = { callback: listeners[key][k] }; + if (typeof listeners[key][k].callback === "function") + listeners[key][k].callback = listeners[key][k].callback.bind(node); + if (typeof node.__listeners !== "object") + node.__listeners = {}; + if (!n) { + let tag = k.substring(0, k.lastIndexOf(".")); + n = this.get(tag); + if (n) { + sub = this.subscribe(n, listeners[key][k].callback, k.substring(k.lastIndexOf(".") + 1), listeners[key][k].inputState, key, k); + if (typeof node.__listeners[k] !== "object") + node.__listeners[k] = { callback: listeners[key][k].callback, inputState: listeners[key][k]?.inputState }; + node.__listeners[k].sub = sub; + } + } else { + sub = this.subscribe(n, listeners[key][k].callback, void 0, listeners[key][k].inputState, key, k); + if (typeof node.__listeners[k] !== "object") + node.__listeners[k] = { callback: listeners[key][k].callback, inputState: listeners[key][k]?.inputState }; + node.__listeners[k].sub = sub; + } + } + } + } + }; + this.clearListeners = (node, listener) => { + if (typeof node === "string") + node = this.get(node); + if (node?.__listeners) { + for (const key in node.__listeners) { + if (listener && key !== listener) + continue; + if (typeof node.__listeners[key].sub !== "number") + continue; + let n = this.get(key); + if (!n) { + n = this.get(key.substring(0, key.lastIndexOf("."))); + if (n) + this.unsubscribe(n, node.__listeners[key].sub, key.substring(key.lastIndexOf(".") + 1), node.__listeners[key].inputState); + } else { + this.unsubscribe(n, node.__listeners[key].sub, void 0, node.__listeners[key].inputState); + } + delete node.__listeners[key]; + } + } + }; + this.get = (tag) => { + return this.__node.nodes.get(tag); + }; + this.set = (tag, node) => { + return this.__node.nodes.set(tag, node); + }; + this.delete = (tag) => { + return this.__node.nodes.delete(tag); + }; + this.getProps = (node, getInitial) => { + if (typeof node === "string") + node = this.get(node); + if (node instanceof GraphNode) { + let cpy; + if (getInitial) + cpy = Object.assign({}, this.__node.tree[node.__node.tag]); + else { + cpy = Object.assign({}, node); + delete cpy.__unsubscribe; + delete cpy.__setOperator; + delete cpy.__node; + delete cpy.__subscribeState; + delete cpy.__subscribe; + } + } + }; + this.subscribe = (node, callback, key, subInput, target, bound) => { + let nd = node; + if (!(node instanceof GraphNode)) + nd = this.get(node); + let sub; + if (typeof callback === "string") { + if (target) { + let method = this.get(target)?.[callback]; + if (typeof method === "function") + callback = method; + } else + callback = this.get(callback)?.__operator; + } + if (nd instanceof GraphNode) { + sub = nd.__subscribe(callback, key, subInput, target, bound); + let ondelete = () => { + nd.__unsubscribe(sub, key, subInput); + }; + nd.__addDisconnected(ondelete); + } else if (typeof node === "string") { + if (this.get(node)) { + if (callback instanceof GraphNode && callback.__operator) { + sub = this.get(node).__subscribe(callback.__operator, key, subInput, target, bound); + let ondelete = () => { + this.get(node).__unsubscribe(sub); + }; + callback.__addDisconnected(ondelete); + } else if (typeof callback === "function" || typeof callback === "string") { + sub = this.get(node).__subscribe(callback, key, subInput, target, bound); + this.__node.state.getTrigger(this.get(node).__node.unique, sub).source = node; + } + } else { + if (typeof callback === "string") + callback = this.__node.nodes.get(callback).__operator; + if (typeof callback === "function") + sub = this.__node.state.subscribeTrigger(node, callback); + } + } + return sub; + }; + this.unsubscribe = (node, sub, key, subInput) => { + if (node instanceof GraphNode) { + return node.__unsubscribe(sub, key, subInput); + } else + return this.get(node)?.__unsubscribe(sub, key, subInput); + }; + this.setState = (update) => { + this.__node.state.setState(update); + }; + this.init(options); + } +}; +function recursivelyAssign(target, obj) { + for (const key in obj) { + if (obj[key]?.constructor.name === "Object" && !Array.isArray(obj[key])) { + if (target[key]?.constructor.name === "Object" && !Array.isArray(target[key])) + recursivelyAssign(target[key], obj[key]); + else + target[key] = recursivelyAssign({}, obj[key]); + } else { + target[key] = obj[key]; + } + } + return target; +} +function getAllProperties(obj) { + var allProps = [], curr = obj; + do { + var props = Object.getOwnPropertyNames(curr); + props.forEach(function(prop) { + if (allProps.indexOf(prop) === -1) + allProps.push(prop); + }); + } while (curr = Object.getPrototypeOf(curr)); + return allProps; +} + +// ../../Loaders.ts +var backprop = (node, parent, graph) => { + if (node.__node.backward && parent instanceof GraphNode) { + graph.setListeners({ + [parent.__node.tag]: { + [node.__node.tag]: parent + } + }); + } +}; +var loop = (node, parent, graph) => { + if (node.__operator && !node.__node.looperSet) { + node.__node.looperSet = true; + if (typeof node.__node.delay === "number") { + let fn = node.__operator; + node.__operator = (...args) => { + return new Promise((res, rej) => { + setTimeout(async () => { + res(await fn(...args)); + }, node.__node.delay); + }); + }; + } else if (node.__node.frame === true) { + let fn = node.__operator; + node.__operator = (...args) => { + return new Promise((res, rej) => { + requestAnimationFrame(async () => { + res(await fn(...args)); + }); + }); + }; + } + if (typeof node.__node.repeat === "number" || typeof node.__node.recursive === "number") { + let fn = node.__operator; + node.__operator = async (...args) => { + let i = node.__node.repeat ? node.__node.repeat : node.__node.recursive; + let result; + let repeater = async (tick, ...inp) => { + while (tick > 0) { + if (node.__node.delay || node.__node.frame) { + fn(...inp).then(async (res) => { + if (node.__node.recursive) { + await repeater(tick, res); + } else + await repeater(tick, ...inp); + }); + break; + } else + result = await fn(...args); + tick--; + } + }; + await repeater(i, ...args); + return result; + }; + } + if (node.__node.loop && typeof node.__node.loop === "number") { + let fn = node.__operator; + node.__operator = (...args) => { + if (!("looping" in node.__node)) + node.__node.looping = true; + if (node.__node.looping) { + fn(...args); + setTimeout(() => { + node.__operator(...args); + }, node.__node.loop); + } + }; + if (node.__node.looping) + node.__operator(); + let ondelete = (node2) => { + if (node2.__node.looping) + node2.__node.looping = false; + }; + node.__addDisconnected(ondelete); + } + } +}; +var animate = (node, parent, graph) => { + if (node.__node.animate === true || node.__node.animation) { + if (typeof node.__node.animate === "function") + node.__node.animate = node.__node.animate.bind(node); + let anim = (node2) => { + let fn = node2.__operator; + node2.__operator = (...args) => { + if (!("animating" in node2.__node)) + node2.__node.animating = true; + if (node2.__node.animating) { + if (typeof node2.__node.animate === "function") + node2.__node.animate(...args); + else + fn(...args); + requestAnimationFrame(() => { + node2.__operator(...args); + }); + } + }; + if (node2.__node.animating) + node2.__node.animation(); + }; + requestAnimationFrame(anim); + let ondelete = (node2) => { + if (node2.__node.animating) + node2.__node.animating = false; + }; + node.__addDisconnected(ondelete); + } +}; +var branching = (node, parent, graph) => { + if (typeof node.__node.branch === "object" && node.__operator && !node.__node.branchApplied) { + let fn = node.__operator; + node.__node.branchApplied = true; + node.__operator = (...args) => { + let result = fn(...args); + for (const key in node.__node.branch) { + let triggered = () => { + if (typeof node.__node.branch[key].then === "function") { + node.__node.branch[key].then(result); + } else if (node.__node.branch[key].then instanceof GraphNode && node.__node.branch[key].then.__operator) { + node.__node.branch[key].then.__operator(result); + } else + result = node.__node.branch[key].then; + }; + if (typeof node.__node.branch[key].if === "function") { + if (node.__node.branch[key].if(result)) { + triggered(); + } + } else if (node.__node.branch[key].if === result) { + triggered(); + } + } + return result; + }; + } + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (node.__listeners[key].branch && !node.__listeners[key].branchApplied) { + let fn = node.__listeners[key].callback; + node.__listeners[key].branchApplied = true; + node.__listeners.callback = (ret) => { + let triggered = () => { + if (typeof node.__listeners[key].branch.then === "function") { + ret = node.__listeners[key].branch.then(ret); + } else if (node.__listeners[key].branch.then instanceof GraphNode && node.__listeners[key].branch.then.__operator) { + ret = node.__listeners[key].branch.then.__operator(ret); + } else + ret = node.__listeners[key].branch.then; + }; + if (typeof node.__listeners[key].branch.if === "function") { + if (node.__listeners[key].branch.if(ret)) { + triggered(); + } + } else if (node.__listeners[key].branch.if === ret) { + triggered(); + } + return fn(ret); + }; + } + } + } + } +}; +var triggerListenerOncreate = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (node.__listeners[key].oncreate) { + node.__listeners[key].callback(node.__listeners[key].oncreate); + } + } + } + } +}; +var bindListener = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (typeof node.__listeners[key].binding === "object") { + node.__listeners.callback = node.__listeners.callback.bind(node.__listeners[key].binding); + } + } + } + } +}; +var transformListenerResult = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (typeof node.__listeners[key].transform === "function" && !node.__listeners[key].transformApplied) { + let fn = node.__listeners[key].callback; + node.__listeners[key].transformApplied = true; + node.__listeners.callback = (ret) => { + ret = node.__listeners[key].transform(ret); + return fn(ret); + }; + } + } + } + } +}; +var substitute__operator = (node, parent, graph) => { + if (node.post && !node.__operator) { + node.__setOperator(node.post); + } else if (!node.__operator && typeof node.get == "function") { + node.__setOperator(node.get); + } + if (!node.get && node.__operator) { + node.get = node.__operator; + } + if (node.aliases) { + node.aliases.forEach((a) => { + graph.set(a, node); + let ondelete = (node2) => { + graph.__node.nodes.delete(a); + }; + node.__addDisconnected(ondelete); + }); + } + if (typeof graph.__node.tree[node.__node.tag] === "object" && node.get) + graph.__node.tree[node.__node.tag].get = node.get; +}; +var loaders = { + backprop, + loop, + animate, + branching, + triggerListenerOncreate, + bindListener, + transformListenerResult, + substitute__operator +}; + +// ../../services/Service.ts +var Service = class extends Graph { + constructor(options) { + super({ + ...options, + loaders: options?.loaders ? Object.assign({ ...loaders }, options.loaders) : { ...loaders } + }); + this.name = `service${Math.floor(Math.random() * 1e15)}`; + this.addServices = (services) => { + for (const s in services) { + if (typeof services[s] === "function") + services[s] = new services[s](); + if (services[s]?.__node?.loaders) + Object.assign(this.__node.loaders, services[s].__node.loaders); + if (services[s]?.__node?.nodes) { + services[s].__node.nodes.forEach((n, tag) => { + if (!this.get(tag)) { + this.set(tag, n); + } else + this.set(s + "." + tag, n); + }); + this.__node.nodes.forEach((n, k) => { + if (!services[s].__node.nodes.get(k)) + services[s].__node.nodes.set(k, n); + }); + let set = this.set; + this.set = (tag, node) => { + services[s].set(tag, node); + return set(tag, node); + }; + let del = this.delete; + this.delete = (tag) => { + services[s].delete(tag); + return del(tag); + }; + } else if (typeof services[s] === "object") { + this.setTree(services[s]); + } + } + }; + this.handleMethod = (route, method, args) => { + let m = method.toLowerCase(); + let src = this.__node.nodes.get(route); + if (!src) { + src = this.__node.tree[route]; + } + if (src?.[m]) { + if (!(src[m] instanceof Function)) { + if (args) + src[m] = args; + return src[m]; + } else + return src[m](args); + } else + return this.handleServiceMessage({ route, args, method }); + }; + this.transmit = (...args) => { + if (typeof args[0] === "object") { + if (args[0].method) { + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if (args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node) { + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if (this.__node.keepState) { + if (args[0].route) + this.setState({ [args[0].route]: args[0].args }); + if (args[0].node) + this.setState({ [args[0].node]: args[0].args }); + } + return args; + } else + return args; + }; + this.receive = (...args) => { + if (args[0]) { + if (typeof args[0] === "string") { + let substr = args[0].substring(0, 8); + if (substr.includes("{") || substr.includes("[")) { + if (substr.includes("\\")) + args[0] = args[0].replace(/\\/g, ""); + if (args[0][0] === '"') { + args[0] = args[0].substring(1, args[0].length - 1); + } + ; + args[0] = JSON.parse(args[0]); + } + } + } + if (typeof args[0] === "object") { + if (args[0].method) { + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if (args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node) { + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if (this.__node.keepState) { + if (args[0].route) + this.setState({ [args[0].route]: args[0].args }); + if (args[0].node) + this.setState({ [args[0].node]: args[0].args }); + } + return args; + } else + return args; + }; + this.pipe = (source, destination, endpoint, method, callback) => { + if (source instanceof GraphNode) { + if (callback) + return this.subscribe(source, (res) => { + let mod = callback(res); + if (mod !== void 0) + this.transmit({ route: destination, args: mod, method }); + else + this.transmit({ route: destination, args: res, method }, endpoint); + }); + else + return this.subscribe(source, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + } else if (typeof source === "string") + return this.subscribe(source, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + }; + this.pipeOnce = (source, destination, endpoint, method, callback) => { + if (source instanceof GraphNode) { + if (callback) + return source.__node.state.subscribeTriggerOnce(source.__node.unique, (res) => { + let mod = callback(res); + if (mod !== void 0) + this.transmit({ route: destination, args: mod, method }); + else + this.transmit({ route: destination, args: res, method }, endpoint); + }); + else + return this.__node.state.subscribeTriggerOnce(source.__node.unique, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + } else if (typeof source === "string") + return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + }; + this.terminate = (...args) => { + }; + this.isTypedArray = isTypedArray; + this.recursivelyAssign = recursivelyAssign2; + this.spliceTypedArray = spliceTypedArray; + this.ping = () => { + console.log("pinged!"); + return "pong"; + }; + this.echo = (...args) => { + this.transmit(...args); + return args; + }; + if (options?.services) + this.addServices(options.services); + this.setTree(this); + } + handleServiceMessage(message) { + let call; + if (typeof message === "object") { + if (message.route) + call = message.route; + else if (message.node) + call = message.node; + } + if (call) { + if (Array.isArray(message.args)) + return this.run(call, ...message.args); + else + return this.run(call, message.args); + } else + return message; + } + handleGraphNodeCall(route, args) { + if (!route) + return args; + if (args?.args) { + this.handleServiceMessage(args); + } else if (Array.isArray(args)) + return this.run(route, ...args); + else + return this.run(route, args); + } +}; +function isTypedArray(x) { + return ArrayBuffer.isView(x) && Object.prototype.toString.call(x) !== "[object DataView]"; +} +var recursivelyAssign2 = (target, obj) => { + for (const key in obj) { + if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { + if (typeof target[key] === "object" && !Array.isArray(target[key])) + recursivelyAssign2(target[key], obj[key]); + else + target[key] = recursivelyAssign2({}, obj[key]); + } else + target[key] = obj[key]; + } + return target; +}; +function spliceTypedArray(arr, start, end) { + let s = arr.subarray(0, start); + let e; + if (end) { + e = arr.subarray(end + 1); + } + let ta; + if (s.length > 0 || e?.length > 0) + ta = new arr.constructor(s.length + e.length); + if (ta) { + if (s.length > 0) + ta.set(s); + if (e && e.length > 0) + ta.set(e, s.length); + } + return ta; +} + +// ../../services/utils.ts +var stringifyWithCircularRefs = function() { + const refs = /* @__PURE__ */ new Map(); + const parents = []; + const path2 = ["this"]; + function clear() { + refs.clear(); + parents.length = 0; + path2.length = 1; + } + function updateParents(key, value) { + var idx = parents.length - 1; + var prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value || idx === 0) { + path2.push(key); + parents.push(value.pushed); + } else { + while (idx-- >= 0) { + prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value) { + idx += 2; + parents.length = idx; + path2.length = idx; + --idx; + parents[idx] = value; + path2[idx] = key; + break; + } + } + idx--; + } + } + } + } + function checkCircular(key, value) { + if (value != null) { + if (typeof value === "object") { + if (key) { + updateParents(key, value); + } + let other = refs.get(value); + if (other) { + return "[Circular Reference]" + other; + } else { + refs.set(value, path2.join(".")); + } + } + } + return value; + } + return function stringifyWithCircularRefs2(obj, space) { + try { + parents.push(obj); + return JSON.stringify(obj, checkCircular, space); + } finally { + clear(); + } + }; +}(); +if (JSON.stringifyWithCircularRefs === void 0) { + JSON.stringifyWithCircularRefs = stringifyWithCircularRefs; +} +var stringifyFast = function() { + const refs = /* @__PURE__ */ new Map(); + const parents = []; + const path2 = ["this"]; + function clear() { + refs.clear(); + parents.length = 0; + path2.length = 1; + } + function updateParents(key, value) { + var idx = parents.length - 1; + if (parents[idx]) { + var prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value || idx === 0) { + path2.push(key); + parents.push(value.pushed); + } else { + while (idx-- >= 0) { + prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value) { + idx += 2; + parents.length = idx; + path2.length = idx; + --idx; + parents[idx] = value; + path2[idx] = key; + break; + } + } + idx++; + } + } + } + } + } + function checkValues(key, value) { + let val; + if (value != null) { + if (typeof value === "object") { + let c = value.constructor.name; + if (key && c === "Object") { + updateParents(key, value); + } + let other = refs.get(value); + if (other) { + return "[Circular Reference]" + other; + } else { + refs.set(value, path2.join(".")); + } + if (c === "Array") { + if (value.length > 20) { + val = value.slice(value.length - 20); + } else + val = value; + } else if (c.includes("Set")) { + val = Array.from(value); + } else if (c !== "Object" && c !== "Number" && c !== "String" && c !== "Boolean") { + val = "instanceof_" + c; + } else if (c === "Object") { + let obj = {}; + for (const prop in value) { + if (value[prop] == null) { + obj[prop] = value[prop]; + } else if (Array.isArray(value[prop])) { + if (value[prop].length > 20) + obj[prop] = value[prop].slice(value[prop].length - 20); + else + obj[prop] = value[prop]; + } else if (value[prop].constructor.name === "Object") { + obj[prop] = {}; + for (const p in value[prop]) { + if (Array.isArray(value[prop][p])) { + if (value[prop][p].length > 20) + obj[prop][p] = value[prop][p].slice(value[prop][p].length - 20); + else + obj[prop][p] = value[prop][p]; + } else { + if (value[prop][p] != null) { + let con = value[prop][p].constructor.name; + if (con.includes("Set")) { + obj[prop][p] = Array.from(value[prop][p]); + } else if (con !== "Number" && con !== "String" && con !== "Boolean") { + obj[prop][p] = "instanceof_" + con; + } else { + obj[prop][p] = value[prop][p]; + } + } else { + obj[prop][p] = value[prop][p]; + } + } + } + } else { + let con = value[prop].constructor.name; + if (con.includes("Set")) { + obj[prop] = Array.from(value[prop]); + } else if (con !== "Number" && con !== "String" && con !== "Boolean") { + obj[prop] = "instanceof_" + con; + } else { + obj[prop] = value[prop]; + } + } + } + val = obj; + } else { + val = value; + } + } else { + val = value; + } + } + return val; + } + return function stringifyFast2(obj, space) { + parents.push(obj); + let res = JSON.stringify(obj, checkValues, space); + clear(); + return res; + }; +}(); +if (JSON.stringifyFast === void 0) { + JSON.stringifyFast = stringifyFast; +} + +// ../../services/e2ee/E2EE.service.ts +var import_sjcl = __toESM(require_sjcl()); + +// ../../services/http/HTTP.node.ts +var http = __toESM(require("http")); +var https = __toESM(require("https")); +var fs = __toESM(require("fs")); +var path = __toESM(require("path")); +var HTTPbackend = class extends Service { + constructor(options, settings) { + super(options); + this.name = "http"; + this.debug = false; + this.servers = {}; + this.mimeTypes = { + ".html": "text/html", + ".htm": "text/html", + ".js": "text/javascript", + ".css": "text/css", + ".json": "application/json", + ".txt": "text/plain", + ".png": "image/png", + ".jpg": "image/jpg", + ".jpeg": "image/jpg", + ".gif": "image/gif", + ".svg": "image/svg+xml", + ".xhtml": "application/xhtml+xml", + ".bmp": "image/bmp", + ".wav": "audio/wav", + ".mp3": "audio/mpeg", + ".mp4": "video/mp4", + ".xml": "application/xml", + ".webm": "video/webm", + ".webp": "image/webp", + ".weba": "audio/webm", + ".woff": "font/woff", + "woff2": "font/woff2", + ".ttf": "application/font-ttf", + ".eot": "application/vnd.ms-fontobject", + ".otf": "application/font-otf", + ".wasm": "application/wasm", + ".zip": "application/zip", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".tif": "image/tiff", + ".sh": "application/x-sh", + ".csh": "application/x-csh", + ".rar": "application/vnd.rar", + ".ppt": "application/vnd.ms-powerpoint", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".odt": "application/vnd.oasis.opendocument.text", + ".ods": "application/vnd.oasis.opendocument.spreadsheet", + ".odp": "application/vnd.oasis.opendocument.presentation", + ".mpeg": "video/mpeg", + ".mjs": "text/javascript", + ".cjs": "text/javascript", + ".jsonld": "application/ld+json", + ".jar": "application/java-archive", + ".ico": "image/vnd.microsoft.icon", + ".gz": "application/gzip", + "epub": "application/epub+zip", + ".doc": "application/msword", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".csv": "text/csv", + ".avi": "video/x-msvideo", + ".aac": "audio/aac", + ".mpkg": "application/vnd.apple.installer+xml", + ".oga": "audio/ogg", + ".ogv": "video/ogg", + "ogx": "application/ogg", + ".php": "application/x-httpd-php", + ".rtf": "application/rtf", + ".swf": "application/x-shockwave-flash", + ".7z": "application/x-7z-compressed", + ".3gp": "video/3gpp" + }; + this.onStarted = (protocol, host, port) => { + console.log( + `\u{1F431} Node server running at + ${protocol}://${host}:${port}/` + ); + }; + this.setupServer = (options = { + protocol: "http", + host: "localhost", + port: 8080, + startpage: "index.html" + }, requestListener, onStarted) => { + if (options.pages) { + for (const key in options.pages) { + if (typeof options.pages[key] === "string") { + this.addPage(`${options.port}/${key}`, options.pages[key]); + } else if (typeof options.pages[key] === "object") { + if (options.pages[key].template) { + options.pages[key].get = options.pages[key].template; + } + if (key !== "_all") + this.setTree({ [`${options.port}/${key}`]: options.pages[key] }); + } + } + } + if (options.protocol === "https") { + return this.setupHTTPSserver(options, requestListener, onStarted); + } else + return this.setupHTTPserver(options, requestListener, onStarted); + }; + this.open = this.setupServer; + this.setupHTTPserver = (options = { + host: "localhost", + port: 8080, + startpage: "index.html", + errpage: void 0 + }, requestListener, onStarted = () => { + this.onStarted("http", options.host, options.port); + }) => { + const host = options.host; + const port = options.port; + options.protocol = "http"; + if (!host || !port) + return; + const address = `${host}:${port}`; + if (this.servers[address]) + this.terminate(this.servers[address]); + if (!("keepState" in options)) + options.keepState = true; + const served = { + server: void 0, + type: "httpserver", + address, + ...options + }; + if (!requestListener) + requestListener = (request, response) => { + let received = { + args: { request, response }, + method: request.method, + served + }; + let url = request.url.slice(1); + if (!url) + url = "/"; + if (options.pages) { + if (typeof options.pages[url] === "object") { + if (options.pages[url].onrequest) { + if (typeof options.pages[url].onrequest === "string") { + options.pages[url].onrequest = this.__node.nodes.get(url.onrequest); + } + if (typeof options.pages[url].onrequest === "object") { + if (options.pages[url].onrequest.__operator) { + options.pages[url].onrequest.__operator(options.pages[url], request, response); + } + } else if (typeof options.pages[url].onrequest === "function") { + options.pages[url].onrequest(this, this.__node.nodes.get(options.port + "/" + url), request, response); + } + } + if (options.pages[url].redirect) { + url = options.pages[url].redirect; + received.redirect = url; + } + } + } + received.route = url; + this.receive(received); + }; + const server2 = http.createServer( + requestListener + ); + served.server = server2; + served.terminate = () => { + this.terminate(served); + }; + served.service = this; + this.servers[address] = served; + served._id = options._id ? options._id : address; + return new Promise((resolve, reject) => { + server2.on("error", (err) => { + console.error("Server error:", err.toString()); + reject(err); + }); + server2.listen( + port, + host, + () => { + onStarted(); + if (served.onopen) + served.onopen(served); + resolve(served); + } + ); + }); + }; + this.setupHTTPSserver = (options = { + host: "localhost", + port: 8080, + startpage: "index.html", + certpath: "cert.pem", + keypath: "key.pem", + passphrase: "encryption", + errpage: void 0 + }, requestListener, onStarted = () => { + this.onStarted("https", options.host, options.port); + }) => { + const host = options.host; + const port = options.port; + options.protocol = "https"; + if (!host || !port || !options.certpath || !options.keypath) + return; + if (this.servers[`${host}:${port}`]) + this.terminate(this.servers[`${host}:${port}`]); + var opts = { + key: fs.readFileSync(options.keypath), + cert: fs.readFileSync(options.certpath), + passphrase: options.passphrase + }; + if (!("keepState" in options)) + options.keepState = true; + const address = `${host}:${port}`; + const served = { + server: void 0, + type: "httpserver", + address, + ...options + }; + if (!requestListener) + requestListener = (request, response) => { + let received = { + args: { request, response }, + method: request.method, + served + }; + let url = request.url.slice(1); + if (!url) + url = "/"; + if (options.pages) { + if (typeof options.pages[url] === "object") { + if (options.pages[url].redirect) { + url = options.pages[url].redirect; + received.redirect = url; + } + if (options.pages[url].onrequest) { + if (typeof options.pages[url].onrequest === "string") { + options.pages[url].onrequest = this.__node.nodes.get(options.pages[url].onrequest); + } + if (typeof options.pages[url].onrequest === "object") { + if (options.pages[url].onrequest.__operator) { + options.pages[url].onrequest.__operator(options.pages[url], request, response); + } + } else if (typeof options.pages[url].onrequest === "function") { + options.pages[url].onrequest(this, options.pages[url], request, response); + } + } + } + } + received.route = url; + this.receive(received); + }; + const server2 = https.createServer( + opts, + requestListener + ); + served.server = server2; + served.terminate = () => { + this.terminate(served); + }; + served.service = this; + this.servers[address] = served; + served._id = options._id ? options._id : address; + return new Promise((resolve, reject) => { + server2.on("error", (err) => { + console.error("Server error:", err.toString()); + reject(err); + }); + server2.listen( + port, + host, + () => { + onStarted(); + if (served.onopen) + served.onopen(served); + resolve(served); + } + ); + }); + }; + this.transmit = (message, options, ondata, onend) => { + let input = message; + if (typeof input === "object") + input = JSON.stringify(input); + if (typeof options === "string" && message) + return this.POST(options, message); + else if (typeof options === "string") + return this.GET(options); + if (!options) { + let server2 = this.servers[Object.keys(this.servers)[0]]; + options = { + protocol: server2.protocol, + host: server2.host, + port: server2.port, + method: "POST", + path: message.route, + headers: { + "Content-Type": "application/json", + "Content-Length": input.length + } + }; + } else if (!options.headers) { + options.headers = { + "Content-Type": "application/json", + "Content-Length": input.length + }; + } + return this.request(options, input, ondata, onend); + }; + this.withResult = (response, result, message) => { + if (result && !response.writableEnded && !response.destroyed) { + let mimeType = "text/plain"; + if (typeof result === "string") { + let extname2 = path.extname(result); + if (extname2 && fs.existsSync(path.join(process.cwd(), result))) { + mimeType = this.mimeTypes[extname2] || "application/octet-stream"; + result = fs.readFileSync(path.join(process.cwd(), result)); + if (mimeType === "text/html" && (message.served?.pages?._all || message.served?.pages?.[message.route])) { + result = this.injectPageCode(result.toString(), message.route, message.served); + } + } + if (typeof result === "string" && result.includes("<") && result.includes(">") && result.indexOf("<") < result.indexOf(">")) { + if (message?.served?.pages?._all || message?.served?.pages?.[message.route]) { + result = this.injectPageCode(result, message.route, message.served); + } + response.writeHead(200, { "Content-Type": "text/html" }); + response.end(result, "utf-8"); + return; + } + } else if (typeof result === "object") { + result = JSON.stringify(result); + mimeType = "application/json"; + } + response.writeHead(200, { "Content-Type": mimeType }); + response.end(result, "utf-8"); + } + }; + this.injectPageCode = (templateString, url, served) => { + if (served?.pages?.[url]?.inject) { + if (typeof served.pages[url].inject === "object") + templateString = this.buildPage(served.pages[url].inject, templateString); + else if (typeof served.pages[url].inject === "function") + templateString += served.pages[url].inject(); + else if (typeof served.pages[url].inject === "string" || typeof served.pages[url].inject === "number") + templateString += served.pages[url].inject; + } + if (served?.pages?._all?.inject) { + if (typeof served.pages._all.inject === "object") + templateString = this.buildPage(served.pages._all.inject, templateString); + else if (typeof served.pages._all.inject === "function") + templateString += served.pages._all.inject(); + else if (typeof served.pages._all.inject === "string" || typeof served.pages._all.inject === "number") + templateString += served.pages._all.inject; + } + return templateString; + }; + this.receive = (message) => { + const request = message.args.request; + const response = message.args.response; + const method = message.method; + const served = message.served; + if (this.debug) + console.log(request.method, request.url); + let result = new Promise((resolve, reject) => { + response.on("error", (err) => { + if (!response.writableEnded || !response.destroyed) { + response.statusCode = 400; + response.end(void 0, void 0, () => { + reject(err); + }); + } + }); + let getFailed = () => { + if (response.writableEnded || response.destroyed) + reject(requestURL); + if (requestURL == "./" || requestURL == served?.startpage) { + let template = `

      Brains@Play Server

      `; + if (served?.pages?._all || served?.pages?.error) { + template = this.injectPageCode(template, message.route, served); + } + response.writeHead(200, { "Content-Type": "text/html" }); + response.end(template, "utf-8", () => { + resolve(template); + }); + if (served?.keepState) + this.setState({ [served.address]: template }); + } else if (this.debug) + console.log(`File ${requestURL} does not exist on path!`); + response.writeHead(500); + response.end(void 0, void 0, () => { + reject(requestURL); + }); + }; + if (method === "GET" || method === "get") { + var requestURL = "." + request.url; + if (requestURL == "./" && served?.startpage) { + requestURL = served.startpage; + } + if ((request.url !== "/" || served?.startpage) && fs.existsSync(path.join(process.cwd(), requestURL))) { + if (response.writableEnded || response.destroyed) + reject(requestURL); + fs.readFile(path.join(process.cwd(), requestURL), (error, content) => { + if (error) { + if (error.code == "ENOENT") { + if (served?.errpage) { + fs.readFile(served.errpage, (er, content2) => { + response.writeHead(404, { "Content-Type": "text/html" }); + if (served.pages?._all || served.pages?.error) { + content2 = this.injectPageCode(content2.toString(), message.route, served); + } + response.end(content2, "utf-8"); + reject(content2); + }); + } else { + response.writeHead(404, { "Content-Type": "text/html" }); + let content2 = `

      Error: ${error.code}

      `; + if (served?.pages?._all || served?.pages?.[message.route]) { + content2 = this.injectPageCode(content2.toString(), message.route, served); + } + response.end(content2, "utf-8", () => { + reject(error.code); + }); + } + } else { + response.writeHead(500); + response.end("Something went wrong: " + error.code + " ..\n", "utf-8", () => { + reject(error.code); + }); + } + } else { + var extname2 = String(path.extname(requestURL)).toLowerCase(); + var contentType = this.mimeTypes[extname2] || "application/octet-stream"; + if (contentType === "text/html" && (served?.pages?._all || served?.pages?.[message.route])) { + content = this.injectPageCode(content.toString(), message.route, served); + } + response.writeHead(200, { "Content-Type": contentType }); + response.end(content, "utf-8", () => { + resolve(content); + }); + } + }); + } else if (message.route) { + let route; + if (served) { + let rt = `${served.port}/${message.route}`; + if (this.__node.nodes.get(rt)) + route = rt; + } + if (!route && this.__node.nodes.get(message.route)) + route = message.route; + if (route) { + let res; + if (message.method) { + res = this.handleMethod(route, message.method, void 0); + } else if (message.node) { + res = this.handleGraphNodeCall(message.node, void 0); + } else + res = this.handleServiceMessage({ route, args: void 0, method: message.method }); + if (res instanceof Promise) + res.then((r) => { + if (served?.keepState) + this.setState({ [served.address]: res }); + this.withResult(response, r, message); + resolve(res); + }); + else if (res) { + if (served?.keepState) + this.setState({ [served.address]: res }); + this.withResult(response, res, message); + resolve(res); + } + } else if (message.redirect) { + response.writeHead(301, { "Location": message.redirect }); + response.end(); + resolve(true); + } else + getFailed(); + } else + getFailed(); + } else { + let body = []; + request.on("data", (chunk) => { + body.push(chunk); + }).on("end", () => { + body = Buffer.concat(body).toString(); + if (typeof body === "string") { + let substr = body.substring(0, 8); + if (substr.includes("{") || substr.includes("[")) { + if (substr.includes("\\")) + body = body.replace(/\\/g, ""); + if (body[0] === '"') { + body = body.substring(1, body.length - 1); + } + ; + body = JSON.parse(body); + } + } + let route, method2, args; + if (body?.route) { + route = this.__node.tree[body.route]; + method2 = body.method; + args = body.args; + if (!route) { + if (typeof body.route === "string") { + if (body.route.includes("/") && body.route.length > 1) + body.route = body.route.split("/").pop(); + } + route = this.__node.tree[body.route]; + } + } + if (!route) { + if (message?.route) { + let route2 = this.__node.tree[message.route]; + method2 = message.method; + args = message.args; + if (!route2) { + if (typeof message.route === "string") { + if (message.route.includes("/") && message.route.length > 1) + message.route = message.route.split("/").pop(); + } + route2 = this.__node.tree[message.route]; + } + } + } + let res = body; + if (route) { + if (body.method) { + res = this.handleMethod(route, method2, args); + } else if (body.node) { + res = this.handleGraphNodeCall(body.node, body.args); + } else + res = this.handleServiceMessage({ route, args, method: method2 }); + if (res instanceof Promise) { + res.then((r) => { + this.withResult(response, r, message); + if (served?.keepState) + this.setState({ [served.address]: res }); + resolve(res); + }); + } else { + this.withResult(response, res, message); + if (served?.keepState) + this.setState({ [served.address]: res }); + resolve(res); + } + } else if (!response.writableEnded || !response.destroyed) { + response.statusCode = 200; + response.end(void 0, void 0, () => { + resolve(res); + }); + } else + resolve(res); + }); + } + }).catch((er) => { + console.error("Request Error:", er); + }); + return result; + }; + this.request = (options, send, ondata, onend) => { + let client = http; + if (options.protocol?.includes("https")) { + client = https; + } + delete options.protocol; + const req = client.request(options, (res) => { + if (ondata) + res.on("data", ondata); + if (onend) + res.on("end", onend); + }); + if (options.headers) { + for (const head in options.headers) { + req.setHeader(head, options.headers[head]); + } + } + if (send) + req.write(send); + req.end(); + return req; + }; + this.POST = (url, data, headers) => { + let urlstring = url; + if (urlstring instanceof URL) + urlstring = url.toString(); + let protocol = urlstring.startsWith("https") ? "https" : "http"; + let host, port, path2; + let split = urlstring.split("/"); + split.forEach((s) => { + if (s.includes(":")) { + let ss = s.split(":"); + host = ss[0]; + port = ss[1]; + } + }); + if (split.length > 3) { + path2 = split.slice(3).join("/"); + } + let req = this.request( + { + protocol, + host, + port, + path: path2, + method: "POST", + headers + }, + data + ); + return req; + }; + this.GET = (url) => { + return new Promise((resolve, reject) => { + let client = http; + let urlstring = url; + if (url instanceof URL) + urlstring = url.toString(); + if (urlstring.includes("https")) { + client = https; + } + client.get(url, (resp) => { + let chunks = []; + resp.on("data", (chunk) => { + chunks.push(chunk); + }); + resp.on("end", () => { + resolve(Buffer.concat(chunks)); + }); + }).on("error", (err) => { + reject(err); + }); + }); + }; + this.terminate = (served) => { + if (typeof served === "string") + served = this.servers[served]; + if (typeof served === "object") { + served.server.close(); + if (served.onclose) + served.onclose(served); + } + }; + this.addPage = (path2, template) => { + if (typeof template === "string") { + if (!template.includes(""; + } + if (typeof this.__node.tree[path2] === "object") { + this.__node.tree[path2].get = template; + this.__node.nodes.get(path2).get = template; + } else + this.setTree({ + [path2]: { + get: template + } + }); + }; + this.addHTML = (path2, template) => { + if (typeof template === "string") { + if (!template.includes("<") || !template.includes(">")) + template = "
      " + template + "
      "; + } + if (typeof this.__node.tree[path2] === "object") { + this.__node.tree[path2].get = template; + this.__node.nodes.get(path2).get = template; + } else + this.setTree({ + [path2]: { + get: template + } + }); + }; + this.buildPage = (pageStructure, baseTemplate) => { + let result = ``; + if (baseTemplate) + result += baseTemplate; + let appendTemplate = (obj, r, res) => { + if (typeof obj[r] === "object") { + for (const key in obj) { + appendTemplate(obj, key, res); + } + } else if (this.__node.tree[r]?.get) { + let toAdd = this.__node.tree[r]?.get; + if (typeof toAdd === "function") + toAdd = toAdd(obj[r]); + if (typeof toAdd === "string") { + let lastDiv = res.lastIndexOf("<"); + if (lastDiv > 0) { + let end = res.substring(lastDiv); + res = res.substring(0, lastDiv) + toAdd + end; + } + res += toAdd; + } + } else if (typeof this.__node.tree[r] === "function" || this.__node.tree[r]?.__operator) { + let routeresult; + if (this.__node.tree[r]?.__operator) + routeresult = this.__node.tree[r].__operator(obj[r]); + else + routeresult = this.__node.tree[r](obj[r]); + if (typeof routeresult === "string") { + let lastDiv = res.lastIndexOf("<"); + if (lastDiv > 0) { + let end = res.substring(lastDiv); + res = res.substring(0, lastDiv) + routeresult + end; + } else + res += routeresult; + } + } else if (typeof this.__node.tree[r] === "string") + res += this.__node.tree[r]; + return res; + }; + if (Array.isArray(pageStructure)) { + pageStructure.forEach((r) => { + result = appendTemplate(pageStructure, r, result); + }); + } else if (typeof pageStructure === "object") { + for (const r in pageStructure) { + result = appendTemplate(pageStructure, r, result); + } + } else if (typeof pageStructure === "string") + result += pageStructure; + else if (typeof pageStructure === "function") + result += pageStructure(); + return result; + }; + this.hotreload = (socketURL = `http://localhost:8080/wss`) => { + if (socketURL instanceof URL) + socketURL = socketURL.toString(); + const HotReloadClient = (url = `http://localhost:8080/wss`) => { + let socket = new WebSocket(url); + socket.addEventListener("close", () => { + const interAttemptTimeoutMilliseconds = 100; + const maxDisconnectedTimeMilliseconds = 3e3; + const maxAttempts = Math.round(maxDisconnectedTimeMilliseconds / interAttemptTimeoutMilliseconds); + let attempts = 0; + const reloadIfCanConnect = () => { + attempts++; + if (attempts > maxAttempts) { + console.error("Could not reconnect to dev server."); + return; + } + socket = new WebSocket(url); + socket.onerror = (er) => { + console.error(`Hot reload port disconnected, will reload on reconnected. Attempt ${attempts} of ${maxAttempts}`); + }; + socket.addEventListener("error", () => { + setTimeout(reloadIfCanConnect, interAttemptTimeoutMilliseconds); + }); + socket.addEventListener("open", () => { + location.reload(); + }); + }; + reloadIfCanConnect(); + }); + }; + return ` + - - - \ No newline at end of file diff --git a/examples/loaders/basic/index.ts b/examples/loaders/basic/index.ts deleted file mode 100644 index ec19dff7..00000000 --- a/examples/loaders/basic/index.ts +++ /dev/null @@ -1,48 +0,0 @@ -import {Graph, Loader, GraphNodeProperties, Roots } from '../../../src/core/Graph' -import { loop } from '../../../src/loaders/index' - - -const roots = { - - loopNode:{ - __element:'div', - innerHTML:`
      Hello world!
      `, - __operator:function (){ - const message = `looped: ${performance.now().toFixed(1)}ms`; - this.insertAdjacentHTML('beforeend',`
      ${message}
      `) - console.log(message); - - return true; - }, - __node:{ - loop:1000, //note this doesn't result in perfect 1000ms loops due to how javascript prioritizes stuff, so it's only relative - looping:true - } - } as GraphNodeProperties - -} as Roots - -let customHTMLLoader:Loader = ( - node, -) => { - if(typeof node.__element == 'string') { - node.__props = document.createElement(node.__element); - if(node.__props instanceof HTMLElement) { - for(const key in node) { - node.__props[key] = node[key]; - } - node.__proxyObject(node.__props); - - document.body.insertAdjacentElement('beforeend',node.__props) - } - } -} - -const graph = new Graph({ - roots, - loaders:{ - customHTMLLoader, - loop //load order can matter depending on expected proxies etc like in this case - } -}); - diff --git a/examples/loaders/basic/package.json b/examples/loaders/basic/package.json deleted file mode 100644 index 0f4a02f7..00000000 --- a/examples/loaders/basic/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "tinybuildapp503", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": {}, - "devDependencies": {}, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} \ No newline at end of file diff --git a/examples/loaders/basic/tinybuild.config.js b/examples/loaders/basic/tinybuild.config.js deleted file mode 100644 index 22f73fa6..00000000 --- a/examples/loaders/basic/tinybuild.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.js" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/loaders/html/index.html b/examples/loaders/html/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/loaders/html/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/loaders/html/tinybuild.config.js b/examples/loaders/html/tinybuild.config.js deleted file mode 100644 index 749308ef..00000000 --- a/examples/loaders/html/tinybuild.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/loaders/web_components/components/draggable.js b/examples/loaders/web_components/components/draggable.js deleted file mode 100644 index e7031a78..00000000 --- a/examples/loaders/web_components/components/draggable.js +++ /dev/null @@ -1,43 +0,0 @@ -//https://www.w3schools.com/howto/howto_js_draggable.asp -// Make the DIV element draggable: - -export function makeDraggable(elmnt) { - var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; - if (document.getElementById(elmnt.id + "header")) { - // if present, the header is where you move the DIV from: - document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; - } else { - // otherwise, move the DIV from anywhere inside the DIV: - elmnt.onmousedown = dragMouseDown; - } - - function dragMouseDown(e) { - e = e || window.event; - e.preventDefault(); - // get the mouse cursor position at startup: - pos3 = e.clientX; - pos4 = e.clientY; - document.onmouseup = closeDragElement; - // call a function whenever the cursor moves: - document.onmousemove = elementDrag; - } - - function elementDrag(e) { - e = e || window.event; - e.preventDefault(); - // calculate the new cursor position: - pos1 = pos3 - e.clientX; - pos2 = pos4 - e.clientY; - pos3 = e.clientX; - pos4 = e.clientY; - // set the element's new position: - elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; - elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; - } - - function closeDragElement() { - // stop moving when mouse button is released: - document.onmouseup = null; - document.onmousemove = null; - } -} \ No newline at end of file diff --git a/examples/loaders/web_components/components/node/node.css b/examples/loaders/web_components/components/node/node.css deleted file mode 100644 index 3029b896..00000000 --- a/examples/loaders/web_components/components/node/node.css +++ /dev/null @@ -1,4 +0,0 @@ -.nodeheader { /* component css tags should probably be sufficiently unique like other component libraries, or just use inline styles */ - text-align:center; - width: max-content; -} \ No newline at end of file diff --git a/examples/loaders/web_components/components/node/node.ts b/examples/loaders/web_components/components/node/node.ts deleted file mode 100644 index 12214269..00000000 --- a/examples/loaders/web_components/components/node/node.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { makeDraggable } from "../draggable"; -import { PointHTML } from "../point/point"; - -//@ts-ignore -import style from './node.css'; //in esbuild, set loader:{'.css':'text' } -//@ts-ignore -import html from './node.html'; //add to loader: {...'.html':'text'} - -export class NodeHTML { - - tagName = 'graph-node'; - - __template = '' // = html; - __css = style; - __components = { - 'custom-point-name': PointHTML - } - - draggable=true; - - style = { - position:'absolute', - padding:'10px', - display:'flex', - borderRadius:'10%', - backgroundColor:'lightblue', - cursor:'pointer' - }; - - __onrender = function() { - this.insertAdjacentHTML('beforeend', ` -
      -
      Drag ${this.__node.tag ?? 'Me'}!
      -
      -
      - - - - - - -
      -
      - `) - } - - __onconnected = function() { - makeDraggable(this); //the htmlElement properties are bound to 'this' as well as 'this.__props' so you can manipulate the node directly - }; - - // __children={ - // container:{ - // __element:'div', - // __children:{ - // header:{ - // __element:'div', - // innerHTML:'Drag Me!', - // className:'nodeheader' - // }, - // ln:{__template:'
      '}, - // body:{ - // __element:'div', - // style:{ - // display:'flex' - // }, - // __children:{ - // inputs:{ - // __element:'span', - // style:{ - // width:'12.5%' - // } - // }, - // content:{ - // __element:'span', - // style:{ - // width:'75%' - // } - // }, - // outputs:{ - // __element:'span', - // style:{ - // width:'12.5%' - // }, - // __children:{ - // point:PointHTML, - // point2:PointHTML - // } - // } - // } - // } - // } - // } - // }; - -} \ No newline at end of file diff --git a/examples/loaders/web_components/components/point/point.css b/examples/loaders/web_components/components/point/point.css deleted file mode 100644 index e06d2a6c..00000000 --- a/examples/loaders/web_components/components/point/point.css +++ /dev/null @@ -1,10 +0,0 @@ -.point { - width: 1px; - height: 1px; - border: 10px solid transparent; - border-left-color: greenyellow; - position: relative; -} -.point:hover { - border-left-color: yellow; -} diff --git a/examples/loaders/web_components/components/point/point.html b/examples/loaders/web_components/components/point/point.html deleted file mode 100644 index ad99828e..00000000 --- a/examples/loaders/web_components/components/point/point.html +++ /dev/null @@ -1,2 +0,0 @@ -
      -
      \ No newline at end of file diff --git a/examples/loaders/web_components/components/point/point.ts b/examples/loaders/web_components/components/point/point.ts deleted file mode 100644 index 88a3f6c0..00000000 --- a/examples/loaders/web_components/components/point/point.ts +++ /dev/null @@ -1,18 +0,0 @@ - -//@ts-ignore -import style from './point.css'; //in esbuild, set loader:{'.css':'text' } -//@ts-ignore -import html from './point.html'; //add to loader: {...'.html':'text'} - -export class PointHTML { - - tagName='interactive-point'; - - __template = html; - __css = style; - - __onconnected = function() { - //console.log(this); - }; - -} \ No newline at end of file diff --git a/examples/loaders/web_components/index.ts b/examples/loaders/web_components/index.ts deleted file mode 100644 index 55cf875b..00000000 --- a/examples/loaders/web_components/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import {Graph, GraphNode, wchtmlloader} from '../../../index' -import { NodeHTML } from './components/node/node'; - -new Graph({ - roots:{ - draggable: NodeHTML, - other: NodeHTML - }, - loaders:{ - wchtmlloader - } -}); \ No newline at end of file diff --git a/examples/loaders/web_components/package.json b/examples/loaders/web_components/package.json deleted file mode 100644 index ab88c2bf..00000000 --- a/examples/loaders/web_components/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tinybuildapp5363", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": { - "graphscript": "^0.2.80" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/examples/loaders/web_components/tinybuild.config.js b/examples/loaders/web_components/tinybuild.config.js deleted file mode 100644 index f162fe94..00000000 --- a/examples/loaders/web_components/tinybuild.config.js +++ /dev/null @@ -1,37 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false, - loader:{'.html':'text', '.css':'text' } - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/services/workers/pipelining/index.html b/examples/services/workers/pipelining/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/pipelining/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/pipelining/index.ts b/examples/services/workers/pipelining/index.ts deleted file mode 100644 index cc006d41..00000000 --- a/examples/services/workers/pipelining/index.ts +++ /dev/null @@ -1,113 +0,0 @@ - -import { WorkerInfo, WorkerService, remoteGraphRoutes } from '../../../../index'; - -import worker from './worker' - -//main thread - - -const graph = new WorkerService({ - //props:{} //could set the props instead of globalThis but it really does not matter unless you want to bake in for more complex service modules - roots:{ - ...remoteGraphRoutes, - } -}); - -console.log('Worker Service', graph); - - -const worker1 = graph.addWorker({url:worker}) as WorkerInfo; -const worker2 = graph.addWorker({url:worker}) as WorkerInfo; -const worker3 = graph.addWorker({url:worker}) as WorkerInfo; - -//simulate long tasks -function taskA(input) { // SCOPE REFACTOR: Might actually need to pass self and origin... - return new Promise((res,rej) => { - setTimeout(() => { - console.log(input,42); - res(42); - }, 3000) //long task - }); -}; - -function taskB(input) { // SCOPE REFACTOR: Might actually need to pass self and origin... - return new Promise((res,rej) => { - setTimeout(() => { - console.log(input,42); - res(42); - }, 1000) //long task - }); -}; - -function taskC(input) { // SCOPE REFACTOR: Might actually need to pass self and origin... - return new Promise((res,rej) => { - setTimeout(() => { - console.log(input,42); - res(42); - }, 1500) //long task - }); -}; - -function subTaskA(input:number) { - console.log('multiplying',input,'by 10'); - return input * 10; -} - -function subTaskB(input:number) { - console.log('applying log to',input); - return Math.log(input); -} - -graph.run('transferFunction', - taskA, - worker1, - 'task' //in case of minification really -); - -graph.run('transferFunction', - taskB, - worker2, - 'task' -); - -graph.run('transferFunction', - taskC, - worker3, - 'task' -); - - -//now for a message channel pipeline. -graph.run('transferFunction', - subTaskA, - worker1, - 'subTaskA' -).then(console.log); - -graph.run('transferFunction', - subTaskB, - worker2, - 'subTaskB' -).then(console.log); - -let portId = graph.establishMessageChannel(worker1, worker2); - -//subscribe worker 2 to worker 1 directly (no overhead on main thread) -worker2.post('subscribeToWorker',[ - 'subTaskA', - portId, - 'subTaskB' -]); - -//now subscribe to the output on the main thread (or it could be a rendering thread etc., mind the rules of using threads!) -worker2.subscribe('subTaskB',(res) => { - console.log('result from worker2', res); -}).then(() => { - worker1.run('subTaskA', 42); //makes sure this runs after worker\2 is ready -}); - - - -worker1.run('task','What is the meaning of life?'); -worker2.run('task','What is the meaning of life?'); -worker3.run('task','What is the meaning of life?'); diff --git a/examples/services/workers/pipelining/package-lock.json b/examples/services/workers/pipelining/package-lock.json deleted file mode 100644 index 1e72f344..00000000 --- a/examples/services/workers/pipelining/package-lock.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "tinybuildapp9800", - "version": "0.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "tinybuildapp9800", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "dependencies": { - "web-worker": "^1.2.0" - }, - "devDependencies": {} - }, - "../../../../../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.205", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.17.10", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.9.5" - } - }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - } - } -} diff --git a/examples/services/workers/pipelining/package.json b/examples/services/workers/pipelining/package.json deleted file mode 100644 index 7b486bbd..00000000 --- a/examples/services/workers/pipelining/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tinybuildapp9800", - "version": "0.0.0", - "description": "Barebones esbuild and test node server implementation. For building", - "main": "index.js", - "type": "module", - "scripts": { - "start": "tinybuild", - "build": "tinybuild build", - "serve": "tinybuild serve", - "init": "node tinybuild/init.js", - "concurrent": "concurrently \\'npm run python\\' \\'npm start\\'", - "dev": "npm run pip && npm i --save-dev concurrently && npm i --save-dev nodemon && npm run concurrent", - "startdev": "nodemon --exec \\'node tinybuild.js\\' -e ejs,js,ts,jsx,tsx,css,html,jpg,png,scss,txt,csv", - "python": "python python/server.py", - "pip": "pip install quart && pip install websockets", - "pwa": "npm i workbox-cli && workbox generateSW node_server/pwa/workbox-config.js && npm run build && npm start" - }, - "keywords": [ - "esbuild" - ], - "author": "", - "license": "LGPL-3.0-or-later", - "dependencies": { - "web-worker": "^1.2.0" - }, - "nodemonConfig": { - "env": { - "NODEMON": true - }, - "ignore": [ - "dist/", - ".temp/" - ] - } -} diff --git a/examples/services/workers/pipelining/tinybuild.config.js b/examples/services/workers/pipelining/tinybuild.config.js deleted file mode 100644 index 749308ef..00000000 --- a/examples/services/workers/pipelining/tinybuild.config.js +++ /dev/null @@ -1,36 +0,0 @@ -const config = { - bundler: { //esbuild settings, set false to skip build step or add bundle:true to config object to only bundle (alt methods) - entryPoints: [ //entry point file(s). These can include .js, .mjs, .ts, .jsx, .tsx, or other javascript files. Make sure your entry point is a ts file if you want to generate types - "index.ts" - ], - outfile: "dist/index", //exit point file, will append .js as well as indicators like .esm.js, .node.js for other build flags - //outdir:[] //exit point files, define for multiple bundle files - bundleBrowser: true, //create plain js build? Can include globals and init scripts - bundleESM: false, //create esm module js files - bundleTypes: false, //create .d.ts files, the entry point must be a typescript file! (ts, tsx, etc) - bundleNode: false, //create node platform plain js build, specify platform:'node' to do the rest of the files - bundleHTML: false, //wrap the first entry point file as a plain js script in a boilerplate html file, frontend scripts can be run standalone like a .exe! Server serves this as start page if set to true. - minify: true, - sourcemap: false - //globalThis:null //'mymodule' - //globals:{'index.js':['Graph']} - //init:{'index.js':function(bundle) { console.log('prepackaged bundle script!', bundle); }.toString(); } //pass stringified functions in to init bundle scripts in a custom way (e.g. for quick rebundling) - }, - server: { //node server settings, set false to skip server step or add serve:true to config object to only serve (alt methods) - debug: false, - protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well - host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 - startpage: "index.html", //home page - socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port - //watch: ['../'], //watch additional directories other than the current working directory - pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) - python: false,//7000, //quart server port (configured via the python server script file still) - python_node: 7001, //websocket relay port (relays messages to client from nodejs that were sent to it by python) - errpage: "node_modules/tinybuild/tinybuild/node_server/other/404.html", //default error page, etc. - certpath: "node_modules/tinybuild/tinybuild/node_server/ssl/cert.pem", //if using https, this is required. See cert.pfx.md for instructions - keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions - } -} -export default config; //module.exports = config; //es5 \ No newline at end of file diff --git a/examples/services/workers/pipelining/worker.ts b/examples/services/workers/pipelining/worker.ts deleted file mode 100644 index 64639d93..00000000 --- a/examples/services/workers/pipelining/worker.ts +++ /dev/null @@ -1,21 +0,0 @@ - -import { WorkerService, remoteGraphRoutes } from '../../../../index'; - -//worker threads - -declare var WorkerGlobalScope; - -if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { - - const worker = new WorkerService({ - //props:{} //could set the props instead of globalThis but it really does not matter unless you want to bake in for more complex service modules - roots:{ - ...remoteGraphRoutes, - } - }); - - console.log('worker', worker) - -} - -export default self as any; diff --git a/examples/services/workers/workerECS/index.html b/examples/services/workers/workerECS/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/workerECS/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/workercanvas/index.html b/examples/services/workers/workercanvas/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/workercanvas/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/workerthreejs/index.html b/examples/services/workers/workerthreejs/index.html deleted file mode 100644 index 49564abb..00000000 --- a/examples/services/workers/workerthreejs/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/examples/services/workers/workerthreejs/package-lock.json b/examples/services/workers/workerthreejs/package-lock.json deleted file mode 100644 index 30c2e101..00000000 --- a/examples/services/workers/workerthreejs/package-lock.json +++ /dev/null @@ -1,165 +0,0 @@ -{ - "name": "tinybuildapp261", - "version": "0.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "tinybuildapp261", - "version": "0.0.0", - "license": "LGPL-3.0-or-later", - "dependencies": { - "graphscript": "^0.0.157", - "three": "^0.143.0" - } - }, - "node_modules/better-sse": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.7.1.tgz", - "integrity": "sha512-2t7XGg6hQFNwtmFXKi6/jyY5K0/4fa5UoOqVSYG2W/AFbVCt8gPnFw2LHM9ude91a8KhoXtRt9zOwpVZ5f5K5g==", - "engines": { - "node": ">=12", - "pnpm": ">=6" - } - }, - "node_modules/brainsatplay-data": { - "version": "0.0.48", - "resolved": "https://registry.npmjs.org/brainsatplay-data/-/brainsatplay-data-0.0.48.tgz", - "integrity": "sha512-3xJ4C5ts0z6dKTkaEI0LrHO443gphOj/OAP9JfZARZXE5MO+kMsOIlvAgijeP7ty4btZtg7MNEEacwIBXREgbQ==", - "dependencies": { - "brainsatplay-math": "^0.0.2" - } - }, - "node_modules/brainsatplay-data/node_modules/brainsatplay-math": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.2.tgz", - "integrity": "sha512-7fjUfcmR2TcHtRh9jCds1WF1HZWhvvDytE6ngrkOUnMTQTbrDs0iAcp8NjMEiHumJRjcaD/c6PN60wIY0rjQaQ==" - }, - "node_modules/brainsatplay-math": { - "version": "0.0.22", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.22.tgz", - "integrity": "sha512-er+7fobi+bgtuiaN5Pcg0cpOfl/d5hrM8W8sF5lnX9VWhcs2TvyG3J0UV+pozGYSBvtqij7Evs4HhhFIh3cfbQ==" - }, - "node_modules/bson-objectid": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.3.tgz", - "integrity": "sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g==" - }, - "node_modules/gpujsutils": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.10.tgz", - "integrity": "sha512-hn74yMSZrT4pf4nlS3SRZvUe7UaGCs3KYoi/dqhTJk3Gho2M9SScj7BHewTcNI1M2UonTkcaR/CA1KgXxekfVQ==" - }, - "node_modules/graphscript": { - "version": "0.0.157", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.0.157.tgz", - "integrity": "sha512-VAxGbKZ6zx9xYVnzkVhWWgjBy0YaSup3G+e05PJe5FlWDjttFDmOgA6WloywkvK24zX0kWamj2Xmz9N4fmJx+w==", - "dependencies": { - "better-sse": "^0.7.1", - "brainsatplay-data": "^0.0.48", - "brainsatplay-math": "^0.0.22", - "bson-objectid": "^2.0.3", - "gpujsutils": "^1.0.8", - "web-worker": "^1.2.0", - "ws": "^8.7.0" - } - }, - "node_modules/three": { - "version": "0.143.0", - "resolved": "https://registry.npmjs.org/three/-/three-0.143.0.tgz", - "integrity": "sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg==" - }, - "node_modules/web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - }, - "node_modules/ws": { - "version": "8.8.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.8.1.tgz", - "integrity": "sha512-bGy2JzvzkPowEJV++hF07hAD6niYSr0JzBNo/J29WsB57A2r7Wlc1UFcTR9IzrPvuNVO4B8LGqF8qcpsVOhJCA==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - }, - "dependencies": { - "better-sse": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/better-sse/-/better-sse-0.7.1.tgz", - "integrity": "sha512-2t7XGg6hQFNwtmFXKi6/jyY5K0/4fa5UoOqVSYG2W/AFbVCt8gPnFw2LHM9ude91a8KhoXtRt9zOwpVZ5f5K5g==" - }, - "brainsatplay-data": { - "version": "0.0.48", - "resolved": "https://registry.npmjs.org/brainsatplay-data/-/brainsatplay-data-0.0.48.tgz", - "integrity": "sha512-3xJ4C5ts0z6dKTkaEI0LrHO443gphOj/OAP9JfZARZXE5MO+kMsOIlvAgijeP7ty4btZtg7MNEEacwIBXREgbQ==", - "requires": { - "brainsatplay-math": "^0.0.2" - }, - "dependencies": { - "brainsatplay-math": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.2.tgz", - "integrity": "sha512-7fjUfcmR2TcHtRh9jCds1WF1HZWhvvDytE6ngrkOUnMTQTbrDs0iAcp8NjMEiHumJRjcaD/c6PN60wIY0rjQaQ==" - } - } - }, - "brainsatplay-math": { - "version": "0.0.22", - "resolved": "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.22.tgz", - "integrity": "sha512-er+7fobi+bgtuiaN5Pcg0cpOfl/d5hrM8W8sF5lnX9VWhcs2TvyG3J0UV+pozGYSBvtqij7Evs4HhhFIh3cfbQ==" - }, - "bson-objectid": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.3.tgz", - "integrity": "sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g==" - }, - "gpujsutils": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/gpujsutils/-/gpujsutils-1.0.10.tgz", - "integrity": "sha512-hn74yMSZrT4pf4nlS3SRZvUe7UaGCs3KYoi/dqhTJk3Gho2M9SScj7BHewTcNI1M2UonTkcaR/CA1KgXxekfVQ==" - }, - "graphscript": { - "version": "0.0.157", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.0.157.tgz", - "integrity": "sha512-VAxGbKZ6zx9xYVnzkVhWWgjBy0YaSup3G+e05PJe5FlWDjttFDmOgA6WloywkvK24zX0kWamj2Xmz9N4fmJx+w==", - "requires": { - "better-sse": "^0.7.1", - "brainsatplay-data": "^0.0.48", - "brainsatplay-math": "^0.0.22", - "bson-objectid": "^2.0.3", - "gpujsutils": "^1.0.8", - "web-worker": "^1.2.0", - "ws": "^8.7.0" - } - }, - "three": { - "version": "0.143.0", - "resolved": "https://registry.npmjs.org/three/-/three-0.143.0.tgz", - "integrity": "sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg==" - }, - "web-worker": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", - "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" - }, - "ws": { - "version": "8.8.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.8.1.tgz", - "integrity": "sha512-bGy2JzvzkPowEJV++hF07hAD6niYSr0JzBNo/J29WsB57A2r7Wlc1UFcTR9IzrPvuNVO4B8LGqF8qcpsVOhJCA==", - "requires": {} - } - } -} diff --git a/examples/advanced/webrtcrouter/README.md b/examples/webrtcrouter/README.md similarity index 100% rename from examples/advanced/webrtcrouter/README.md rename to examples/webrtcrouter/README.md diff --git a/examples/advanced/webrtcrouter/backend.ts b/examples/webrtcrouter/backend.ts similarity index 88% rename from examples/advanced/webrtcrouter/backend.ts rename to examples/webrtcrouter/backend.ts index 25177e2d..101c244f 100644 --- a/examples/advanced/webrtcrouter/backend.ts +++ b/examples/webrtcrouter/backend.ts @@ -10,13 +10,12 @@ process.on('exit', exitHandler.bind(null,{cleanup:true})); //catches ctrl+c event process.on('SIGINT', exitHandler.bind(null, {exit:true})); - -import { Router, User } from "../../../src/services/router/Router"; -import { SocketServerProps, WSSbackend } from "../../../src/services/wss/WSS.node"; -import { SSEbackend, SSEProps } from "../../../src/services/sse/SSE.node"; -import { HTTPbackend, ServerProps } from "../../../src/services/http/HTTP.node"; -import { SessionsService } from "../../../src/services/sessions/sessions.service"; -import { scriptBoilerPlate } from "../../../src/services/http/boilerplate"; +import { Router, User } from "../../services/router/Router"; +import { SocketServerProps, WSSbackend } from "../../services/wss/WSS.node"; +import { SSEbackend, SSEProps } from "../../services/sse/SSE.node"; +import { HTTPbackend, ServerProps } from "../../services/http/HTTP.node"; +import { SessionsService } from "../../services/sessions/sessions.service"; +import { scriptBoilerPlate } from "../../services/http/boilerplate"; const router = new Router({ graph:{ @@ -29,7 +28,7 @@ const router = new Router({ 'server1':{ protocol:'http', host:'localhost', - port:8080, + port:8082, pages:{ '/':scriptBoilerPlate('dist/frontend.js'), //serve the built dist 'config':{ @@ -47,7 +46,7 @@ const router = new Router({ 'test':'
      TEST
      ', _all:{ inject:{ //page building - hotreload:'ws://localhost:8080/hotreload' //this is a route that exists as dynamic content with input arguments, in this case it's a url, could pass objects etc in as arguments + hotreload:'ws://localhost:8082/hotreload' //this is a route that exists as dynamic content with input arguments, in this case it's a url, could pass objects etc in as arguments } } }, @@ -111,10 +110,14 @@ const router = new Router({ order:['sse','wss'],//prefer certain connection sources in a certain order, defaults to load order (if appropriate callbacks are available for subscription) }); //on frontend we want to prefer wss first as sse is POST-reliant from browser +console.log('rETURNED') + //router.services.sessions.users = router.users; //console.log(Object.keys(router.services)); +console.log('addUser') + router.addUser({ _id:'admin' }); @@ -132,8 +135,12 @@ let session = (router.services.sessions as SessionsService).openSharedSession( 'admin' ); +console.log('sessionLoop') + router.run('sessionLoop'); +console.log('SBUSCRIBING') +// NOTE: Not currently getting a new user router.subscribe('addUser', (user:User) => { console.log('new user!', user._id); if(typeof user === 'object') { diff --git a/examples/advanced/webrtcrouter/frontend.ts b/examples/webrtcrouter/frontend.ts similarity index 93% rename from examples/advanced/webrtcrouter/frontend.ts rename to examples/webrtcrouter/frontend.ts index c0519715..e8f9bd3c 100644 --- a/examples/advanced/webrtcrouter/frontend.ts +++ b/examples/webrtcrouter/frontend.ts @@ -1,28 +1,10 @@ -import { HTTPfrontend } from '../../../src/services/http/HTTP.browser'; -import { Router } from '../../../src/services/router/Router' -import { EventSourceProps, SSEfrontend } from '../../../src/services/sse/SSE.browser'; -import { SessionsService } from '../../../src/services/sessions/sessions.service'; -import { WebRTCfrontend, WebRTCInfo } from '../../../src/services/webrtc/WebRTC.browser'; -import { WebSocketProps, WSSfrontend } from '../../../src/services/wss/WSS.browser'; -import {Graph, htmlloader} from '../../../index' - -//how it works -//https://hacks.mozilla.org/2013/07/webrtc-and-the-ocean-of-acronyms/ - -/* Execution. A Signal channel is an intermediary to pass data, e.g. a socket server. -________________________________________________________ -| peer A | STUN | TURN | Signal channel | Peer B | - - x-whoamI-> - <--NAT---x - x---make channel--> - x----------offer sdp------------>|x------------> //make call - <---------answer sdp------------x|<------------x //accept call - x------ice candidate A---------->|x------------> //send communication stuff - <------ice candidate B----------x|<------------x //send communication stuff back - <---------------who am I?-------------x //then this stuff establishes the data channels and streams (or something) - x--------------IP and port------------> -*/ +import { HTTPfrontend } from '../../services/http/HTTP.browser'; +import { Router } from '../../services/router/Router' +import { EventSourceProps, SSEfrontend } from '../../services/sse/SSE.browser'; +import { SessionsService } from '../../services/sessions/sessions.service'; +import { WebRTCfrontend, WebRTCInfo } from '../../services/webrtc/WebRTC.browser'; +import { WebSocketProps, WSSfrontend } from '../../services/wss/WSS.browser'; +import {Graph, htmlloader} from '../../index' const router = new Router({ order:['webrtc','wss','sse'], @@ -31,7 +13,7 @@ const router = new Router({ loaders:{ htmlloader }, - roots:{ + tree:{ 'main':{ tagName:'div', __children:{ @@ -73,20 +55,19 @@ const router = new Router({ service:SSEfrontend, config:{ 'testsse':{ - url:'http://localhost:8080/sse', + url:'http://localhost:8082/sse', events:{ 'test':(ev)=>{console.log('test',ev.data)} } } as EventSourceProps } }, - 'webrtc':WebRTCfrontend, 'wss':{ service:WSSfrontend, config:{ 'testsocket':{ host:'localhost', - port:8080, + port:8082, path:'wss', onopen:(ev,ws,wsinfo)=>{ console.log('socket opened!'); @@ -99,8 +80,8 @@ const router = new Router({ (router.services.sessions as SessionsService).run('userUpdateLoop',user); - user.rooms = {} as any; - user.localrtc = {} as any; + user.rooms = {}; + user.localrtc = {}; console.log(user); @@ -136,7 +117,7 @@ const router = new Router({ }, }).then((room:WebRTCInfo) => { - user.rooms[newId].hostdescription = room.description; + user.rooms[newId].hostdescription = room.hostdescription; user.localrtc[newId] = room; (document.getElementById('myrooms') as HTMLElement).insertAdjacentHTML('beforeend',` @@ -208,21 +189,21 @@ const router = new Router({ ownerId:userId, isLive:false, hostcandidates:{}, - hostdescription:remoteroom.description, + hostdescription:remoteroom.hostdescription, peercandidates:{}, peerdescription:undefined }; (router.services.webrtc as WebRTCfrontend).openRTC({ _id:roomId, - description:remoteroom.description, + hostdescription:remoteroom.hostdescription, onicecandidate:(ev) => { if(ev.candidate) user.rooms[roomId].peercandidates[`peercandidate${Math.floor(Math.random()*1000000000000000)}`] = ev.candidate; }, }).then((localroom) => { user.localrtc[roomId] = localroom; - user.rooms[roomId].peerdescription = localroom.description; + user.rooms[roomId].peerdescription = localroom.peerdescription; (user.localrtc[roomId].rtc as RTCPeerConnection).addEventListener('datachannel',(ev) => { @@ -338,14 +319,16 @@ const router = new Router({ } as WebSocketProps, // 'hotreload':{ // host:'localhost', - // port:8080, + // port:8081, // path:'hotreload' // } as WebSocketProps } - } + }, + 'webrtc':WebRTCfrontend } }); //router.services.sessions.users = router.users; +console.log('Graph', router) console.log(router.__node.nodes.keys()) \ No newline at end of file diff --git a/examples/advanced/webrtcrouter/index.html b/examples/webrtcrouter/index.html similarity index 100% rename from examples/advanced/webrtcrouter/index.html rename to examples/webrtcrouter/index.html diff --git a/examples/advanced/webrtcrouter/package-lock.json b/examples/webrtcrouter/package-lock.json similarity index 99% rename from examples/advanced/webrtcrouter/package-lock.json rename to examples/webrtcrouter/package-lock.json index cd093aaf..b9dee49d 100644 --- a/examples/advanced/webrtcrouter/package-lock.json +++ b/examples/webrtcrouter/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp2273", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "better-sse": "^0.7.1", "brainsatplay-math": "^0.0.22", diff --git a/examples/advanced/webrtcrouter/package.json b/examples/webrtcrouter/package.json similarity index 97% rename from examples/advanced/webrtcrouter/package.json rename to examples/webrtcrouter/package.json index 394c4a0b..27db694f 100644 --- a/examples/advanced/webrtcrouter/package.json +++ b/examples/webrtcrouter/package.json @@ -26,7 +26,7 @@ "web-worker": "^1.2.0", "ws": "^8.7.0"}, "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "nodemonConfig": { "env": { "NODEMON": true diff --git a/examples/advanced/webrtcrouter/tinybuild.backend.js b/examples/webrtcrouter/tinybuild.backend.js similarity index 100% rename from examples/advanced/webrtcrouter/tinybuild.backend.js rename to examples/webrtcrouter/tinybuild.backend.js diff --git a/examples/advanced/webrtcrouter/tinybuild.config.js b/examples/webrtcrouter/tinybuild.config.js similarity index 98% rename from examples/advanced/webrtcrouter/tinybuild.config.js rename to examples/webrtcrouter/tinybuild.config.js index 792d7fa5..c639249c 100644 --- a/examples/advanced/webrtcrouter/tinybuild.config.js +++ b/examples/webrtcrouter/tinybuild.config.js @@ -33,4 +33,4 @@ const config = { // keypath: "node_modules/tinybuild/tinybuild/node_server/ssl/key.pem" //if using https, this is required. See cert.pfx.md for instructions // } } -module.exports = config; //es5 \ No newline at end of file +module.exports = config; //es5 //export default config; // \ No newline at end of file diff --git a/examples/webrtcrouter/yarn.lock b/examples/webrtcrouter/yarn.lock new file mode 100644 index 00000000..e27fda55 --- /dev/null +++ b/examples/webrtcrouter/yarn.lock @@ -0,0 +1,33 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +better-sse@^0.7.1: + version "0.7.1" + resolved "https://registry.yarnpkg.com/better-sse/-/better-sse-0.7.1.tgz#5617f0f1b06f831f425a819c835bd7a6d54d5c82" + integrity sha512-2t7XGg6hQFNwtmFXKi6/jyY5K0/4fa5UoOqVSYG2W/AFbVCt8gPnFw2LHM9ude91a8KhoXtRt9zOwpVZ5f5K5g== + +brainsatplay-math@^0.0.22: + version "0.0.22" + resolved "https://registry.yarnpkg.com/brainsatplay-math/-/brainsatplay-math-0.0.22.tgz#580e2d2cd7573a49fad64facdc176cfe64c080f3" + integrity sha512-er+7fobi+bgtuiaN5Pcg0cpOfl/d5hrM8W8sF5lnX9VWhcs2TvyG3J0UV+pozGYSBvtqij7Evs4HhhFIh3cfbQ== + +bson-objectid@^2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/bson-objectid/-/bson-objectid-2.0.4.tgz#339211572ef97dc98f2d68eaee7b99b7be59a089" + integrity sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ== + +gpujsutils@^1.0.12: + version "1.0.12" + resolved "https://registry.yarnpkg.com/gpujsutils/-/gpujsutils-1.0.12.tgz#390874df5e6d0fdae8b674c22edc6f198a411bc0" + integrity sha512-Zu6k59yavNqprmGGlrZT7fEVVex1Y5MWH/Eq7N5Mx8FrYRotmhtf2H4lAtlX9kR+TxffW51JUruJXnFOEvUg4Q== + +web-worker@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/web-worker/-/web-worker-1.2.0.tgz#5d85a04a7fbc1e7db58f66595d7a3ac7c9c180da" + integrity sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA== + +ws@^8.7.0: + version "8.11.0" + resolved "https://registry.yarnpkg.com/ws/-/ws-8.11.0.tgz#6a0d36b8edfd9f96d8b25683db2f8d7de6e8e143" + integrity sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg== diff --git a/examples/services/workers/workerECS/PickHelper.js b/examples/workerECS/PickHelper.js similarity index 100% rename from examples/services/workers/workerECS/PickHelper.js rename to examples/workerECS/PickHelper.js diff --git a/examples/services/workers/workerECS/ecs_test.ts b/examples/workerECS/ecs_test.ts similarity index 98% rename from examples/services/workers/workerECS/ecs_test.ts rename to examples/workerECS/ecs_test.ts index 5d4c049e..e7547507 100644 --- a/examples/services/workers/workerECS/ecs_test.ts +++ b/examples/workerECS/ecs_test.ts @@ -9,21 +9,20 @@ import { WorkerCanvasControls, WorkerInfo, htmlloader, - HTMLNodeProperties, - remoteGraphRoutes -} from '../../../../index'//'graphscript' + HTMLNodeProperties +} from '../../index'//'graphscript' import gsworker from './worker' const workers = new WorkerService(); -const router = new Router({ services:{ workers, workerCanvasRoutes, remoteGraphRoutes }, loaders:{htmlloader} }); +const router = new Router({ services:{ workers, workerCanvasRoutes }, loaders:{htmlloader} }); console.log(router); document.body.style.height = '100vh' -let ret = router.load({ +let ret = router.setTree({ 'main':{ tagName:'div', __children:{ @@ -247,6 +246,7 @@ let ret = router.load({ const scene = new THREE.Scene(); + canvas.addEventListener('resize', (ev) => { //console.log('resizing', canvas.clientWidth, canvas.clientHeight) renderer.setSize(canvas.clientWidth, canvas.clientHeight, false); @@ -393,24 +393,25 @@ let ret = router.load({ ['x','y','z'] //or for arrays could be the array values ); + return { entityId:this.__node.graph.entityId, positions:positionBuffer }; //typedarrays are automatically transferred }; - workers.run('transferFunction', - bufferPositions, + workers.transferFunction( entities, + bufferPositions, 'bufferPositions' ); - workers.run('transferFunction', - bufferPositions, + workers.transferFunction( entities2, + bufferPositions, 'bufferPositions' ); - + entities.post('ECSService.subscribe',[ 'movement', 'bufferPositions' diff --git a/examples/basics/proxy/index.html b/examples/workerECS/index.html similarity index 100% rename from examples/basics/proxy/index.html rename to examples/workerECS/index.html diff --git a/examples/services/workers/workerECS/package-lock.json b/examples/workerECS/package-lock.json similarity index 98% rename from examples/services/workers/workerECS/package-lock.json rename to examples/workerECS/package-lock.json index a4479335..f7d0175b 100644 --- a/examples/services/workers/workerECS/package-lock.json +++ b/examples/workerECS/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp261", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47", "three": "^0.143.0", @@ -39,7 +39,7 @@ "integrity": "sha512-X9l63+mitFW0pxLF43jDZjxxkwE6a1SUGZJRGE4nmGoU9r599ilfQmXluBPPKuoK1B+ODcUrGi6eleAbA7C9Ow==", "dependencies": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.9.0" @@ -111,7 +111,7 @@ "integrity": "sha512-X9l63+mitFW0pxLF43jDZjxxkwE6a1SUGZJRGE4nmGoU9r599ilfQmXluBPPKuoK1B+ODcUrGi6eleAbA7C9Ow==", "requires": { "better-sse": "~0.8.0", - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.9.0" diff --git a/examples/services/workers/workerECS/package.json b/examples/workerECS/package.json similarity index 93% rename from examples/services/workers/workerECS/package.json rename to examples/workerECS/package.json index 2de0265a..11a00a53 100644 --- a/examples/services/workers/workerECS/package.json +++ b/examples/workerECS/package.json @@ -1,5 +1,5 @@ { - "name": "graphscript-workerecs-example", + "name": "tinybuildapp261", "version": "0.0.0", "description": "Barebones esbuild and test node server implementation. For building", "main": "index.js", @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47", "three": "^0.143.0", diff --git a/examples/services/workers/workerECS/tinybuild.config.js b/examples/workerECS/tinybuild.config.js similarity index 96% rename from examples/services/workers/workerECS/tinybuild.config.js rename to examples/workerECS/tinybuild.config.js index 0342d1fb..b999bb37 100644 --- a/examples/services/workers/workerECS/tinybuild.config.js +++ b/examples/workerECS/tinybuild.config.js @@ -20,10 +20,10 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8081, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port + hotreload: 5001, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) diff --git a/examples/services/workers/workerECS/worker.ts b/examples/workerECS/worker.ts similarity index 85% rename from examples/services/workers/workerECS/worker.ts rename to examples/workerECS/worker.ts index d60fb2f5..0fbe4379 100644 --- a/examples/services/workers/workerECS/worker.ts +++ b/examples/workerECS/worker.ts @@ -1,14 +1,14 @@ import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, ECSService, //GPUService -} from '../../../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' +} from '../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' -import {Systems} from '../../../../src/extras/index.services' +import {Systems} from '../../extras/index.services' -import { CanvasProps } from '../../../../src/services/worker/WorkerCanvas'; +import { CanvasProps } from '../../services/worker/WorkerCanvas'; import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' @@ -25,11 +25,10 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope services:{ //GPUService, ECSService, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading }, - roots:{ + tree:{ ...workerCanvasRoutes, - ...remoteGraphRoutes, receiveThreeCanvas:function(options:CanvasProps){ //modified canvas receiver that installs desired threejs modules const ThreeProps = { //e.g. install these systems to 'self', which is the worker canvas THREE, diff --git a/examples/workerECS/yarn.lock b/examples/workerECS/yarn.lock new file mode 100644 index 00000000..47fb89d9 --- /dev/null +++ b/examples/workerECS/yarn.lock @@ -0,0 +1,56 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +better-sse@~0.8.0: + version "0.8.0" + resolved "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz" + integrity sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA== + +brainsatplay-math@~0.0.25: + version "0.0.25" + resolved "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz" + integrity sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ== + +bson-objectid@~2.0.3: + version "2.0.3" + resolved "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.3.tgz" + integrity sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g== + +graphscript@~0.1.47: + version "0.1.49" + resolved "https://registry.npmjs.org/graphscript/-/graphscript-0.1.49.tgz" + integrity sha512-X9l63+mitFW0pxLF43jDZjxxkwE6a1SUGZJRGE4nmGoU9r599ilfQmXluBPPKuoK1B+ODcUrGi6eleAbA7C9Ow== + dependencies: + better-sse "~0.8.0" + brainsatplay-math "~0.0.25" + bson-objectid "~2.0.3" + web-worker "~1.2.0" + ws "~8.9.0" + +three@^0.143.0: + version "0.143.0" + resolved "https://registry.npmjs.org/three/-/three-0.143.0.tgz" + integrity sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg== + +web-worker@~1.2.0: + version "1.2.0" + resolved "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz" + integrity sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA== + +webgl-plot-utils@^0.3.13: + version "0.3.13" + resolved "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz" + integrity sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg== + dependencies: + webgl-plot "~0.7.0" + +webgl-plot@~0.7.0: + version "0.7.0" + resolved "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz" + integrity sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A== + +ws@~8.9.0: + version "8.9.0" + resolved "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz" + integrity sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg== diff --git a/examples/workercanvas/dist/index.js b/examples/workercanvas/dist/index.js new file mode 100644 index 00000000..5600db6f --- /dev/null +++ b/examples/workercanvas/dist/index.js @@ -0,0 +1,6924 @@ +(() => { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] + }) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw new Error('Dynamic require of "' + x + '" is not supported'); + }); + var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); + var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); + }; + var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); + }; + var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); + }; + var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; + }; + + // ../../services/e2ee/sjcl.js + var require_sjcl = __commonJS({ + "../../services/e2ee/sjcl.js"(exports, module) { + "use strict"; + var sjcl2 = { cipher: {}, hash: {}, keyexchange: {}, mode: {}, misc: {}, codec: {}, exception: { corrupt: function(a) { + this.toString = function() { + return "CORRUPT: " + this.message; + }; + this.message = a; + }, invalid: function(a) { + this.toString = function() { + return "INVALID: " + this.message; + }; + this.message = a; + }, bug: function(a) { + this.toString = function() { + return "BUG: " + this.message; + }; + this.message = a; + }, notReady: function(a) { + this.toString = function() { + return "NOT READY: " + this.message; + }; + this.message = a; + } } }; + sjcl2.cipher.aes = function(a) { + this.s[0][0][0] || this.O(); + var b, c, d, e, f = this.s[0][4], g = this.s[1]; + b = a.length; + var h = 1; + if (4 !== b && 6 !== b && 8 !== b) + throw new sjcl2.exception.invalid("invalid aes key size"); + this.b = [d = a.slice(0), e = []]; + for (a = b; a < 4 * b + 28; a++) { + c = d[a - 1]; + if (0 === a % b || 8 === b && 4 === a % b) + c = f[c >>> 24] << 24 ^ f[c >> 16 & 255] << 16 ^ f[c >> 8 & 255] << 8 ^ f[c & 255], 0 === a % b && (c = c << 8 ^ c >>> 24 ^ h << 24, h = h << 1 ^ 283 * (h >> 7)); + d[a] = d[a - b] ^ c; + } + for (b = 0; a; b++, a--) + c = d[b & 3 ? a : a - 4], e[b] = 4 >= a || 4 > b ? c : g[0][f[c >>> 24]] ^ g[1][f[c >> 16 & 255]] ^ g[2][f[c >> 8 & 255]] ^ g[3][f[c & 255]]; + }; + sjcl2.cipher.aes.prototype = { encrypt: function(a) { + return t(this, a, 0); + }, decrypt: function(a) { + return t(this, a, 1); + }, s: [[[], [], [], [], []], [[], [], [], [], []]], O: function() { + var a = this.s[0], b = this.s[1], c = a[4], d = b[4], e, f, g, h = [], k = [], l, n, m, p; + for (e = 0; 256 > e; e++) + k[(h[e] = e << 1 ^ 283 * (e >> 7)) ^ e] = e; + for (f = g = 0; !c[f]; f ^= l || 1, g = k[g] || 1) + for (m = g ^ g << 1 ^ g << 2 ^ g << 3 ^ g << 4, m = m >> 8 ^ m & 255 ^ 99, c[f] = m, d[m] = f, n = h[e = h[l = h[f]]], p = 16843009 * n ^ 65537 * e ^ 257 * l ^ 16843008 * f, n = 257 * h[m] ^ 16843008 * m, e = 0; 4 > e; e++) + a[e][f] = n = n << 24 ^ n >>> 8, b[e][m] = p = p << 24 ^ p >>> 8; + for (e = 0; 5 > e; e++) + a[e] = a[e].slice(0), b[e] = b[e].slice(0); + } }; + function t(a, b, c) { + if (4 !== b.length) + throw new sjcl2.exception.invalid("invalid aes block size"); + var d = a.b[c], e = b[0] ^ d[0], f = b[c ? 3 : 1] ^ d[1], g = b[2] ^ d[2]; + b = b[c ? 1 : 3] ^ d[3]; + var h, k, l, n = d.length / 4 - 2, m, p = 4, r = [0, 0, 0, 0]; + h = a.s[c]; + a = h[0]; + var q = h[1], v = h[2], w = h[3], x = h[4]; + for (m = 0; m < n; m++) + h = a[e >>> 24] ^ q[f >> 16 & 255] ^ v[g >> 8 & 255] ^ w[b & 255] ^ d[p], k = a[f >>> 24] ^ q[g >> 16 & 255] ^ v[b >> 8 & 255] ^ w[e & 255] ^ d[p + 1], l = a[g >>> 24] ^ q[b >> 16 & 255] ^ v[e >> 8 & 255] ^ w[f & 255] ^ d[p + 2], b = a[b >>> 24] ^ q[e >> 16 & 255] ^ v[f >> 8 & 255] ^ w[g & 255] ^ d[p + 3], p += 4, e = h, f = k, g = l; + for (m = 0; 4 > m; m++) + r[c ? 3 & -m : m] = x[e >>> 24] << 24 ^ x[f >> 16 & 255] << 16 ^ x[g >> 8 & 255] << 8 ^ x[b & 255] ^ d[p++], h = e, e = f, f = g, g = b, b = h; + return r; + } + sjcl2.bitArray = { bitSlice: function(a, b, c) { + a = sjcl2.bitArray.$(a.slice(b / 32), 32 - (b & 31)).slice(1); + return void 0 === c ? a : sjcl2.bitArray.clamp(a, c - b); + }, extract: function(a, b, c) { + var d = Math.floor(-b - c & 31); + return ((b + c - 1 ^ b) & -32 ? a[b / 32 | 0] << 32 - d ^ a[b / 32 + 1 | 0] >>> d : a[b / 32 | 0] >>> d) & (1 << c) - 1; + }, concat: function(a, b) { + if (0 === a.length || 0 === b.length) + return a.concat(b); + var c = a[a.length - 1], d = sjcl2.bitArray.getPartial(c); + return 32 === d ? a.concat(b) : sjcl2.bitArray.$(b, d, c | 0, a.slice(0, a.length - 1)); + }, bitLength: function(a) { + var b = a.length; + return 0 === b ? 0 : 32 * (b - 1) + sjcl2.bitArray.getPartial(a[b - 1]); + }, clamp: function(a, b) { + if (32 * a.length < b) + return a; + a = a.slice(0, Math.ceil(b / 32)); + var c = a.length; + b = b & 31; + 0 < c && b && (a[c - 1] = sjcl2.bitArray.partial(b, a[c - 1] & 2147483648 >> b - 1, 1)); + return a; + }, partial: function(a, b, c) { + return 32 === a ? b : (c ? b | 0 : b << 32 - a) + 1099511627776 * a; + }, getPartial: function(a) { + return Math.round(a / 1099511627776) || 32; + }, equal: function(a, b) { + if (sjcl2.bitArray.bitLength(a) !== sjcl2.bitArray.bitLength(b)) + return false; + var c = 0, d; + for (d = 0; d < a.length; d++) + c |= a[d] ^ b[d]; + return 0 === c; + }, $: function(a, b, c, d) { + var e; + e = 0; + for (void 0 === d && (d = []); 32 <= b; b -= 32) + d.push(c), c = 0; + if (0 === b) + return d.concat(a); + for (e = 0; e < a.length; e++) + d.push(c | a[e] >>> b), c = a[e] << 32 - b; + e = a.length ? a[a.length - 1] : 0; + a = sjcl2.bitArray.getPartial(e); + d.push(sjcl2.bitArray.partial(b + a & 31, 32 < b + a ? c : d.pop(), 1)); + return d; + }, i: function(a, b) { + return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; + }, byteswapM: function(a) { + var b, c; + for (b = 0; b < a.length; ++b) + c = a[b], a[b] = c >>> 24 | c >>> 8 & 65280 | (c & 65280) << 8 | c << 24; + return a; + } }; + sjcl2.codec.utf8String = { fromBits: function(a) { + var b = "", c = sjcl2.bitArray.bitLength(a), d, e; + for (d = 0; d < c / 8; d++) + 0 === (d & 3) && (e = a[d / 4]), b += String.fromCharCode(e >>> 8 >>> 8 >>> 8), e <<= 8; + return decodeURIComponent(escape(b)); + }, toBits: function(a) { + a = unescape(encodeURIComponent(a)); + var b = [], c, d = 0; + for (c = 0; c < a.length; c++) + d = d << 8 | a.charCodeAt(c), 3 === (c & 3) && (b.push(d), d = 0); + c & 3 && b.push(sjcl2.bitArray.partial(8 * (c & 3), d)); + return b; + } }; + sjcl2.codec.hex = { fromBits: function(a) { + var b = "", c; + for (c = 0; c < a.length; c++) + b += ((a[c] | 0) + 263882790666240).toString(16).substr(4); + return b.substr(0, sjcl2.bitArray.bitLength(a) / 4); + }, toBits: function(a) { + var b, c = [], d; + a = a.replace(/\s|0x/g, ""); + d = a.length; + a = a + "00000000"; + for (b = 0; b < a.length; b += 8) + c.push(parseInt(a.substr(b, 8), 16) ^ 0); + return sjcl2.bitArray.clamp(c, 4 * d); + } }; + sjcl2.codec.base32 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", X: "0123456789ABCDEFGHIJKLMNOPQRSTUV", BITS: 32, BASE: 5, REMAINING: 27, fromBits: function(a, b, c) { + var d = sjcl2.codec.base32.BASE, e = sjcl2.codec.base32.REMAINING, f = "", g = 0, h = sjcl2.codec.base32.B, k = 0, l = sjcl2.bitArray.bitLength(a); + c && (h = sjcl2.codec.base32.X); + for (c = 0; f.length * d < l; ) + f += h.charAt((k ^ a[c] >>> g) >>> e), g < d ? (k = a[c] << d - g, g += e, c++) : (k <<= d, g -= d); + for (; f.length & 7 && !b; ) + f += "="; + return f; + }, toBits: function(a, b) { + a = a.replace(/\s|=/g, "").toUpperCase(); + var c = sjcl2.codec.base32.BITS, d = sjcl2.codec.base32.BASE, e = sjcl2.codec.base32.REMAINING, f = [], g, h = 0, k = sjcl2.codec.base32.B, l = 0, n, m = "base32"; + b && (k = sjcl2.codec.base32.X, m = "base32hex"); + for (g = 0; g < a.length; g++) { + n = k.indexOf(a.charAt(g)); + if (0 > n) { + if (!b) + try { + return sjcl2.codec.base32hex.toBits(a); + } catch (p) { + } + throw new sjcl2.exception.invalid("this isn't " + m + "!"); + } + h > e ? (h -= e, f.push(l ^ n >>> h), l = n << c - h) : (h += d, l ^= n << c - h); + } + h & 56 && f.push(sjcl2.bitArray.partial(h & 56, l, 1)); + return f; + } }; + sjcl2.codec.base32hex = { fromBits: function(a, b) { + return sjcl2.codec.base32.fromBits(a, b, 1); + }, toBits: function(a) { + return sjcl2.codec.base32.toBits(a, 1); + } }; + sjcl2.codec.base64 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fromBits: function(a, b, c) { + var d = "", e = 0, f = sjcl2.codec.base64.B, g = 0, h = sjcl2.bitArray.bitLength(a); + c && (f = f.substr(0, 62) + "-_"); + for (c = 0; 6 * d.length < h; ) + d += f.charAt((g ^ a[c] >>> e) >>> 26), 6 > e ? (g = a[c] << 6 - e, e += 26, c++) : (g <<= 6, e -= 6); + for (; d.length & 3 && !b; ) + d += "="; + return d; + }, toBits: function(a, b) { + a = a.replace(/\s|=/g, ""); + var c = [], d, e = 0, f = sjcl2.codec.base64.B, g = 0, h; + b && (f = f.substr(0, 62) + "-_"); + for (d = 0; d < a.length; d++) { + h = f.indexOf(a.charAt(d)); + if (0 > h) + throw new sjcl2.exception.invalid("this isn't base64!"); + 26 < e ? (e -= 26, c.push(g ^ h >>> e), g = h << 32 - e) : (e += 6, g ^= h << 32 - e); + } + e & 56 && c.push(sjcl2.bitArray.partial(e & 56, g, 1)); + return c; + } }; + sjcl2.codec.base64url = { fromBits: function(a) { + return sjcl2.codec.base64.fromBits(a, 1, 1); + }, toBits: function(a) { + return sjcl2.codec.base64.toBits(a, 1); + } }; + sjcl2.hash.sha256 = function(a) { + this.b[0] || this.O(); + a ? (this.F = a.F.slice(0), this.A = a.A.slice(0), this.l = a.l) : this.reset(); + }; + sjcl2.hash.sha256.hash = function(a) { + return new sjcl2.hash.sha256().update(a).finalize(); + }; + sjcl2.hash.sha256.prototype = { blockSize: 512, reset: function() { + this.F = this.Y.slice(0); + this.A = []; + this.l = 0; + return this; + }, update: function(a) { + "string" === typeof a && (a = sjcl2.codec.utf8String.toBits(a)); + var b, c = this.A = sjcl2.bitArray.concat(this.A, a); + b = this.l; + a = this.l = b + sjcl2.bitArray.bitLength(a); + if (9007199254740991 < a) + throw new sjcl2.exception.invalid("Cannot hash more than 2^53 - 1 bits"); + if ("undefined" !== typeof Uint32Array) { + var d = new Uint32Array(c), e = 0; + for (b = 512 + b - (512 + b & 511); b <= a; b += 512) + u(this, d.subarray(16 * e, 16 * (e + 1))), e += 1; + c.splice(0, 16 * e); + } else + for (b = 512 + b - (512 + b & 511); b <= a; b += 512) + u(this, c.splice(0, 16)); + return this; + }, finalize: function() { + var a, b = this.A, c = this.F, b = sjcl2.bitArray.concat(b, [sjcl2.bitArray.partial(1, 1)]); + for (a = b.length + 2; a & 15; a++) + b.push(0); + b.push(Math.floor(this.l / 4294967296)); + for (b.push(this.l | 0); b.length; ) + u(this, b.splice(0, 16)); + this.reset(); + return c; + }, Y: [], b: [], O: function() { + function a(a2) { + return 4294967296 * (a2 - Math.floor(a2)) | 0; + } + for (var b = 0, c = 2, d, e; 64 > b; c++) { + e = true; + for (d = 2; d * d <= c; d++) + if (0 === c % d) { + e = false; + break; + } + e && (8 > b && (this.Y[b] = a(Math.pow(c, 0.5))), this.b[b] = a(Math.pow(c, 1 / 3)), b++); + } + } }; + function u(a, b) { + var c, d, e, f = a.F, g = a.b, h = f[0], k = f[1], l = f[2], n = f[3], m = f[4], p = f[5], r = f[6], q = f[7]; + for (c = 0; 64 > c; c++) + 16 > c ? d = b[c] : (d = b[c + 1 & 15], e = b[c + 14 & 15], d = b[c & 15] = (d >>> 7 ^ d >>> 18 ^ d >>> 3 ^ d << 25 ^ d << 14) + (e >>> 17 ^ e >>> 19 ^ e >>> 10 ^ e << 15 ^ e << 13) + b[c & 15] + b[c + 9 & 15] | 0), d = d + q + (m >>> 6 ^ m >>> 11 ^ m >>> 25 ^ m << 26 ^ m << 21 ^ m << 7) + (r ^ m & (p ^ r)) + g[c], q = r, r = p, p = m, m = n + d | 0, n = l, l = k, k = h, h = d + (k & l ^ n & (k ^ l)) + (k >>> 2 ^ k >>> 13 ^ k >>> 22 ^ k << 30 ^ k << 19 ^ k << 10) | 0; + f[0] = f[0] + h | 0; + f[1] = f[1] + k | 0; + f[2] = f[2] + l | 0; + f[3] = f[3] + n | 0; + f[4] = f[4] + m | 0; + f[5] = f[5] + p | 0; + f[6] = f[6] + r | 0; + f[7] = f[7] + q | 0; + } + sjcl2.mode.ccm = { name: "ccm", G: [], listenProgress: function(a) { + sjcl2.mode.ccm.G.push(a); + }, unListenProgress: function(a) { + a = sjcl2.mode.ccm.G.indexOf(a); + -1 < a && sjcl2.mode.ccm.G.splice(a, 1); + }, fa: function(a) { + var b = sjcl2.mode.ccm.G.slice(), c; + for (c = 0; c < b.length; c += 1) + b[c](a); + }, encrypt: function(a, b, c, d, e) { + var f, g = b.slice(0), h = sjcl2.bitArray, k = h.bitLength(c) / 8, l = h.bitLength(g) / 8; + e = e || 64; + d = d || []; + if (7 > k) + throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes"); + for (f = 2; 4 > f && l >>> 8 * f; f++) + ; + f < 15 - k && (f = 15 - k); + c = h.clamp(c, 8 * (15 - f)); + b = sjcl2.mode.ccm.V(a, b, c, d, e, f); + g = sjcl2.mode.ccm.C(a, g, c, b, e, f); + return h.concat(g.data, g.tag); + }, decrypt: function(a, b, c, d, e) { + e = e || 64; + d = d || []; + var f = sjcl2.bitArray, g = f.bitLength(c) / 8, h = f.bitLength(b), k = f.clamp(b, h - e), l = f.bitSlice(b, h - e), h = (h - e) / 8; + if (7 > g) + throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes"); + for (b = 2; 4 > b && h >>> 8 * b; b++) + ; + b < 15 - g && (b = 15 - g); + c = f.clamp(c, 8 * (15 - b)); + k = sjcl2.mode.ccm.C(a, k, c, l, e, b); + a = sjcl2.mode.ccm.V(a, k.data, c, d, e, b); + if (!f.equal(k.tag, a)) + throw new sjcl2.exception.corrupt("ccm: tag doesn't match"); + return k.data; + }, na: function(a, b, c, d, e, f) { + var g = [], h = sjcl2.bitArray, k = h.i; + d = [h.partial(8, (b.length ? 64 : 0) | d - 2 << 2 | f - 1)]; + d = h.concat(d, c); + d[3] |= e; + d = a.encrypt(d); + if (b.length) + for (c = h.bitLength(b) / 8, 65279 >= c ? g = [h.partial(16, c)] : 4294967295 >= c && (g = h.concat([h.partial(16, 65534)], [c])), g = h.concat(g, b), b = 0; b < g.length; b += 4) + d = a.encrypt(k(d, g.slice(b, b + 4).concat([0, 0, 0]))); + return d; + }, V: function(a, b, c, d, e, f) { + var g = sjcl2.bitArray, h = g.i; + e /= 8; + if (e % 2 || 4 > e || 16 < e) + throw new sjcl2.exception.invalid("ccm: invalid tag length"); + if (4294967295 < d.length || 4294967295 < b.length) + throw new sjcl2.exception.bug("ccm: can't deal with 4GiB or more data"); + c = sjcl2.mode.ccm.na(a, d, c, e, g.bitLength(b) / 8, f); + for (d = 0; d < b.length; d += 4) + c = a.encrypt(h(c, b.slice(d, d + 4).concat([0, 0, 0]))); + return g.clamp(c, 8 * e); + }, C: function(a, b, c, d, e, f) { + var g, h = sjcl2.bitArray; + g = h.i; + var k = b.length, l = h.bitLength(b), n = k / 50, m = n; + c = h.concat([h.partial(8, f - 1)], c).concat([0, 0, 0]).slice(0, 4); + d = h.bitSlice(g(d, a.encrypt(c)), 0, e); + if (!k) + return { tag: d, data: [] }; + for (g = 0; g < k; g += 4) + g > n && (sjcl2.mode.ccm.fa(g / k), n += m), c[3]++, e = a.encrypt(c), b[g] ^= e[0], b[g + 1] ^= e[1], b[g + 2] ^= e[2], b[g + 3] ^= e[3]; + return { tag: d, data: h.clamp(b, l) }; + } }; + sjcl2.mode.ocb2 = { name: "ocb2", encrypt: function(a, b, c, d, e, f) { + if (128 !== sjcl2.bitArray.bitLength(c)) + throw new sjcl2.exception.invalid("ocb iv must be 128 bits"); + var g, h = sjcl2.mode.ocb2.S, k = sjcl2.bitArray, l = k.i, n = [0, 0, 0, 0]; + c = h(a.encrypt(c)); + var m, p = []; + d = d || []; + e = e || 64; + for (g = 0; g + 4 < b.length; g += 4) + m = b.slice(g, g + 4), n = l(n, m), p = p.concat(l(c, a.encrypt(l(c, m)))), c = h(c); + m = b.slice(g); + b = k.bitLength(m); + g = a.encrypt(l(c, [0, 0, 0, b])); + m = k.clamp(l(m.concat([0, 0, 0]), g), b); + n = l(n, l(m.concat([0, 0, 0]), g)); + n = a.encrypt(l(n, l(c, h(c)))); + d.length && (n = l(n, f ? d : sjcl2.mode.ocb2.pmac(a, d))); + return p.concat(k.concat(m, k.clamp(n, e))); + }, decrypt: function(a, b, c, d, e, f) { + if (128 !== sjcl2.bitArray.bitLength(c)) + throw new sjcl2.exception.invalid("ocb iv must be 128 bits"); + e = e || 64; + var g = sjcl2.mode.ocb2.S, h = sjcl2.bitArray, k = h.i, l = [0, 0, 0, 0], n = g(a.encrypt(c)), m, p, r = sjcl2.bitArray.bitLength(b) - e, q = []; + d = d || []; + for (c = 0; c + 4 < r / 32; c += 4) + m = k(n, a.decrypt(k(n, b.slice(c, c + 4)))), l = k(l, m), q = q.concat(m), n = g(n); + p = r - 32 * c; + m = a.encrypt(k(n, [0, 0, 0, p])); + m = k(m, h.clamp(b.slice(c), p).concat([ + 0, + 0, + 0 + ])); + l = k(l, m); + l = a.encrypt(k(l, k(n, g(n)))); + d.length && (l = k(l, f ? d : sjcl2.mode.ocb2.pmac(a, d))); + if (!h.equal(h.clamp(l, e), h.bitSlice(b, r))) + throw new sjcl2.exception.corrupt("ocb: tag doesn't match"); + return q.concat(h.clamp(m, p)); + }, pmac: function(a, b) { + var c, d = sjcl2.mode.ocb2.S, e = sjcl2.bitArray, f = e.i, g = [0, 0, 0, 0], h = a.encrypt([0, 0, 0, 0]), h = f(h, d(d(h))); + for (c = 0; c + 4 < b.length; c += 4) + h = d(h), g = f(g, a.encrypt(f(h, b.slice(c, c + 4)))); + c = b.slice(c); + 128 > e.bitLength(c) && (h = f(h, d(h)), c = e.concat(c, [-2147483648, 0, 0, 0])); + g = f(g, c); + return a.encrypt(f(d(f(h, d(h))), g)); + }, S: function(a) { + return [a[0] << 1 ^ a[1] >>> 31, a[1] << 1 ^ a[2] >>> 31, a[2] << 1 ^ a[3] >>> 31, a[3] << 1 ^ 135 * (a[0] >>> 31)]; + } }; + sjcl2.mode.gcm = { name: "gcm", encrypt: function(a, b, c, d, e) { + var f = b.slice(0); + b = sjcl2.bitArray; + d = d || []; + a = sjcl2.mode.gcm.C(true, a, f, d, c, e || 128); + return b.concat(a.data, a.tag); + }, decrypt: function(a, b, c, d, e) { + var f = b.slice(0), g = sjcl2.bitArray, h = g.bitLength(f); + e = e || 128; + d = d || []; + e <= h ? (b = g.bitSlice(f, h - e), f = g.bitSlice(f, 0, h - e)) : (b = f, f = []); + a = sjcl2.mode.gcm.C(false, a, f, d, c, e); + if (!g.equal(a.tag, b)) + throw new sjcl2.exception.corrupt("gcm: tag doesn't match"); + return a.data; + }, ka: function(a, b) { + var c, d, e, f, g, h = sjcl2.bitArray.i; + e = [ + 0, + 0, + 0, + 0 + ]; + f = b.slice(0); + for (c = 0; 128 > c; c++) { + (d = 0 !== (a[Math.floor(c / 32)] & 1 << 31 - c % 32)) && (e = h(e, f)); + g = 0 !== (f[3] & 1); + for (d = 3; 0 < d; d--) + f[d] = f[d] >>> 1 | (f[d - 1] & 1) << 31; + f[0] >>>= 1; + g && (f[0] ^= -520093696); + } + return e; + }, j: function(a, b, c) { + var d, e = c.length; + b = b.slice(0); + for (d = 0; d < e; d += 4) + b[0] ^= 4294967295 & c[d], b[1] ^= 4294967295 & c[d + 1], b[2] ^= 4294967295 & c[d + 2], b[3] ^= 4294967295 & c[d + 3], b = sjcl2.mode.gcm.ka(b, a); + return b; + }, C: function(a, b, c, d, e, f) { + var g, h, k, l, n, m, p, r, q = sjcl2.bitArray; + m = c.length; + p = q.bitLength(c); + r = q.bitLength(d); + h = q.bitLength(e); + g = b.encrypt([0, 0, 0, 0]); + 96 === h ? (e = e.slice(0), e = q.concat(e, [1])) : (e = sjcl2.mode.gcm.j(g, [0, 0, 0, 0], e), e = sjcl2.mode.gcm.j(g, e, [0, 0, Math.floor(h / 4294967296), h & 4294967295])); + h = sjcl2.mode.gcm.j(g, [0, 0, 0, 0], d); + n = e.slice(0); + d = h.slice(0); + a || (d = sjcl2.mode.gcm.j(g, h, c)); + for (l = 0; l < m; l += 4) + n[3]++, k = b.encrypt(n), c[l] ^= k[0], c[l + 1] ^= k[1], c[l + 2] ^= k[2], c[l + 3] ^= k[3]; + c = q.clamp(c, p); + a && (d = sjcl2.mode.gcm.j(g, h, c)); + a = [Math.floor(r / 4294967296), r & 4294967295, Math.floor(p / 4294967296), p & 4294967295]; + d = sjcl2.mode.gcm.j(g, d, a); + k = b.encrypt(e); + d[0] ^= k[0]; + d[1] ^= k[1]; + d[2] ^= k[2]; + d[3] ^= k[3]; + return { tag: q.bitSlice(d, 0, f), data: c }; + } }; + sjcl2.misc.hmac = function(a, b) { + this.W = b = b || sjcl2.hash.sha256; + var c = [[], []], d, e = b.prototype.blockSize / 32; + this.w = [new b(), new b()]; + a.length > e && (a = b.hash(a)); + for (d = 0; d < e; d++) + c[0][d] = a[d] ^ 909522486, c[1][d] = a[d] ^ 1549556828; + this.w[0].update(c[0]); + this.w[1].update(c[1]); + this.R = new b(this.w[0]); + }; + sjcl2.misc.hmac.prototype.encrypt = sjcl2.misc.hmac.prototype.mac = function(a) { + if (this.aa) + throw new sjcl2.exception.invalid("encrypt on already updated hmac called!"); + this.update(a); + return this.digest(a); + }; + sjcl2.misc.hmac.prototype.reset = function() { + this.R = new this.W(this.w[0]); + this.aa = false; + }; + sjcl2.misc.hmac.prototype.update = function(a) { + this.aa = true; + this.R.update(a); + }; + sjcl2.misc.hmac.prototype.digest = function() { + var a = this.R.finalize(), a = new this.W(this.w[1]).update(a).finalize(); + this.reset(); + return a; + }; + sjcl2.misc.pbkdf2 = function(a, b, c, d, e) { + c = c || 1e4; + if (0 > d || 0 > c) + throw new sjcl2.exception.invalid("invalid params to pbkdf2"); + "string" === typeof a && (a = sjcl2.codec.utf8String.toBits(a)); + "string" === typeof b && (b = sjcl2.codec.utf8String.toBits(b)); + e = e || sjcl2.misc.hmac; + a = new e(a); + var f, g, h, k, l = [], n = sjcl2.bitArray; + for (k = 1; 32 * l.length < (d || 1); k++) { + e = f = a.encrypt(n.concat(b, [k])); + for (g = 1; g < c; g++) + for (f = a.encrypt(f), h = 0; h < f.length; h++) + e[h] ^= f[h]; + l = l.concat(e); + } + d && (l = n.clamp(l, d)); + return l; + }; + sjcl2.prng = function(a) { + this.c = [new sjcl2.hash.sha256()]; + this.m = [0]; + this.P = 0; + this.H = {}; + this.N = 0; + this.U = {}; + this.Z = this.f = this.o = this.ha = 0; + this.b = [0, 0, 0, 0, 0, 0, 0, 0]; + this.h = [0, 0, 0, 0]; + this.L = void 0; + this.M = a; + this.D = false; + this.K = { progress: {}, seeded: {} }; + this.u = this.ga = 0; + this.I = 1; + this.J = 2; + this.ca = 65536; + this.T = [0, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024]; + this.da = 3e4; + this.ba = 80; + }; + sjcl2.prng.prototype = { + randomWords: function(a, b) { + var c = [], d; + d = this.isReady(b); + var e; + if (d === this.u) + throw new sjcl2.exception.notReady("generator isn't seeded"); + if (d & this.J) { + d = !(d & this.I); + e = []; + var f = 0, g; + this.Z = e[0] = new Date().valueOf() + this.da; + for (g = 0; 16 > g; g++) + e.push(4294967296 * Math.random() | 0); + for (g = 0; g < this.c.length && (e = e.concat(this.c[g].finalize()), f += this.m[g], this.m[g] = 0, d || !(this.P & 1 << g)); g++) + ; + this.P >= 1 << this.c.length && (this.c.push(new sjcl2.hash.sha256()), this.m.push(0)); + this.f -= f; + f > this.o && (this.o = f); + this.P++; + this.b = sjcl2.hash.sha256.hash(this.b.concat(e)); + this.L = new sjcl2.cipher.aes(this.b); + for (d = 0; 4 > d && (this.h[d] = this.h[d] + 1 | 0, !this.h[d]); d++) + ; + } + for (d = 0; d < a; d += 4) + 0 === (d + 1) % this.ca && y(this), e = z(this), c.push(e[0], e[1], e[2], e[3]); + y(this); + return c.slice(0, a); + }, + setDefaultParanoia: function(a, b) { + if (0 === a && "Setting paranoia=0 will ruin your security; use it only for testing" !== b) + throw new sjcl2.exception.invalid("Setting paranoia=0 will ruin your security; use it only for testing"); + this.M = a; + }, + addEntropy: function(a, b, c) { + c = c || "user"; + var d, e, f = new Date().valueOf(), g = this.H[c], h = this.isReady(), k = 0; + d = this.U[c]; + void 0 === d && (d = this.U[c] = this.ha++); + void 0 === g && (g = this.H[c] = 0); + this.H[c] = (this.H[c] + 1) % this.c.length; + switch (typeof a) { + case "number": + void 0 === b && (b = 1); + this.c[g].update([d, this.N++, 1, b, f, 1, a | 0]); + break; + case "object": + c = Object.prototype.toString.call(a); + if ("[object Uint32Array]" === c) { + e = []; + for (c = 0; c < a.length; c++) + e.push(a[c]); + a = e; + } else + for ("[object Array]" !== c && (k = 1), c = 0; c < a.length && !k; c++) + "number" !== typeof a[c] && (k = 1); + if (!k) { + if (void 0 === b) + for (c = b = 0; c < a.length; c++) + for (e = a[c]; 0 < e; ) + b++, e = e >>> 1; + this.c[g].update([d, this.N++, 2, b, f, a.length].concat(a)); + } + break; + case "string": + void 0 === b && (b = a.length); + this.c[g].update([d, this.N++, 3, b, f, a.length]); + this.c[g].update(a); + break; + default: + k = 1; + } + if (k) + throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string"); + this.m[g] += b; + this.f += b; + h === this.u && (this.isReady() !== this.u && A("seeded", Math.max(this.o, this.f)), A("progress", this.getProgress())); + }, + isReady: function(a) { + a = this.T[void 0 !== a ? a : this.M]; + return this.o && this.o >= a ? this.m[0] > this.ba && new Date().valueOf() > this.Z ? this.J | this.I : this.I : this.f >= a ? this.J | this.u : this.u; + }, + getProgress: function(a) { + a = this.T[a ? a : this.M]; + return this.o >= a ? 1 : this.f > a ? 1 : this.f / a; + }, + startCollectors: function() { + if (!this.D) { + this.a = { loadTimeCollector: B(this, this.ma), mouseCollector: B(this, this.oa), keyboardCollector: B(this, this.la), accelerometerCollector: B(this, this.ea), touchCollector: B(this, this.qa) }; + if (window.addEventListener) + window.addEventListener("load", this.a.loadTimeCollector, false), window.addEventListener("mousemove", this.a.mouseCollector, false), window.addEventListener("keypress", this.a.keyboardCollector, false), window.addEventListener("devicemotion", this.a.accelerometerCollector, false), window.addEventListener("touchmove", this.a.touchCollector, false); + else if (document.attachEvent) + document.attachEvent("onload", this.a.loadTimeCollector), document.attachEvent("onmousemove", this.a.mouseCollector), document.attachEvent("keypress", this.a.keyboardCollector); + else + throw new sjcl2.exception.bug("can't attach event"); + this.D = true; + } + }, + stopCollectors: function() { + this.D && (window.removeEventListener ? (window.removeEventListener("load", this.a.loadTimeCollector, false), window.removeEventListener("mousemove", this.a.mouseCollector, false), window.removeEventListener("keypress", this.a.keyboardCollector, false), window.removeEventListener("devicemotion", this.a.accelerometerCollector, false), window.removeEventListener("touchmove", this.a.touchCollector, false)) : document.detachEvent && (document.detachEvent("onload", this.a.loadTimeCollector), document.detachEvent("onmousemove", this.a.mouseCollector), document.detachEvent("keypress", this.a.keyboardCollector)), this.D = false); + }, + addEventListener: function(a, b) { + this.K[a][this.ga++] = b; + }, + removeEventListener: function(a, b) { + var c, d, e = this.K[a], f = []; + for (d in e) + e.hasOwnProperty(d) && e[d] === b && f.push(d); + for (c = 0; c < f.length; c++) + d = f[c], delete e[d]; + }, + la: function() { + C(this, 1); + }, + oa: function(a) { + var b, c; + try { + b = a.x || a.clientX || a.offsetX || 0, c = a.y || a.clientY || a.offsetY || 0; + } catch (d) { + c = b = 0; + } + 0 != b && 0 != c && this.addEntropy([b, c], 2, "mouse"); + C(this, 0); + }, + qa: function(a) { + a = a.touches[0] || a.changedTouches[0]; + this.addEntropy([a.pageX || a.clientX, a.pageY || a.clientY], 1, "touch"); + C(this, 0); + }, + ma: function() { + C(this, 2); + }, + ea: function(a) { + a = a.accelerationIncludingGravity.x || a.accelerationIncludingGravity.y || a.accelerationIncludingGravity.z; + if (window.orientation) { + var b = window.orientation; + "number" === typeof b && this.addEntropy(b, 1, "accelerometer"); + } + a && this.addEntropy(a, 2, "accelerometer"); + C(this, 0); + } + }; + function A(a, b) { + var c, d = sjcl2.random.K[a], e = []; + for (c in d) + d.hasOwnProperty(c) && e.push(d[c]); + for (c = 0; c < e.length; c++) + e[c](b); + } + function C(a, b) { + "undefined" !== typeof window && window.performance && "function" === typeof window.performance.now ? a.addEntropy(window.performance.now(), b, "loadtime") : a.addEntropy(new Date().valueOf(), b, "loadtime"); + } + function y(a) { + a.b = z(a).concat(z(a)); + a.L = new sjcl2.cipher.aes(a.b); + } + function z(a) { + for (var b = 0; 4 > b && (a.h[b] = a.h[b] + 1 | 0, !a.h[b]); b++) + ; + return a.L.encrypt(a.h); + } + function B(a, b) { + return function() { + b.apply(a, arguments); + }; + } + sjcl2.random = new sjcl2.prng(6); + a: + try { + if (G = "undefined" !== typeof module && module.exports) { + try { + H = __require("crypto"); + } catch (a) { + H = null; + } + G = E = H; + } + if (G && E.randomBytes) + D = E.randomBytes(128), D = new Uint32Array(new Uint8Array(D).buffer), sjcl2.random.addEntropy(D, 1024, "crypto['randomBytes']"); + else if ("undefined" !== typeof window && "undefined" !== typeof Uint32Array) { + F = new Uint32Array(32); + if (window.crypto && window.crypto.getRandomValues) + window.crypto.getRandomValues(F); + else if (window.msCrypto && window.msCrypto.getRandomValues) + window.msCrypto.getRandomValues(F); + else + break a; + sjcl2.random.addEntropy(F, 1024, "crypto['getRandomValues']"); + } + } catch (a) { + "undefined" !== typeof window && window.console && (console.log("There was an error collecting entropy from the browser:"), console.log(a)); + } + var D; + var E; + var F; + var G; + var H; + sjcl2.json = { defaults: { v: 1, iter: 1e4, ks: 128, ts: 64, mode: "ccm", adata: "", cipher: "aes" }, ja: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl2.json, f = e.g({ iv: sjcl2.random.randomWords(4, 0) }, e.defaults), g; + e.g(f, c); + c = f.adata; + "string" === typeof f.salt && (f.salt = sjcl2.codec.base64.toBits(f.salt)); + "string" === typeof f.iv && (f.iv = sjcl2.codec.base64.toBits(f.iv)); + if (!sjcl2.mode[f.mode] || !sjcl2.cipher[f.cipher] || "string" === typeof a && 100 >= f.iter || 64 !== f.ts && 96 !== f.ts && 128 !== f.ts || 128 !== f.ks && 192 !== f.ks && 256 !== f.ks || 2 > f.iv.length || 4 < f.iv.length) + throw new sjcl2.exception.invalid("json encrypt: invalid parameters"); + "string" === typeof a ? (g = sjcl2.misc.cachedPbkdf2(a, f), a = g.key.slice(0, f.ks / 32), f.salt = g.salt) : sjcl2.ecc && a instanceof sjcl2.ecc.elGamal.publicKey && (g = a.kem(), f.kemtag = g.tag, a = g.key.slice(0, f.ks / 32)); + "string" === typeof b && (b = sjcl2.codec.utf8String.toBits(b)); + "string" === typeof c && (f.adata = c = sjcl2.codec.utf8String.toBits(c)); + g = new sjcl2.cipher[f.cipher](a); + e.g(d, f); + d.key = a; + f.ct = "ccm" === f.mode && sjcl2.arrayBuffer && sjcl2.arrayBuffer.ccm && b instanceof ArrayBuffer ? sjcl2.arrayBuffer.ccm.encrypt(g, b, f.iv, c, f.ts) : sjcl2.mode[f.mode].encrypt(g, b, f.iv, c, f.ts); + return f; + }, encrypt: function(a, b, c, d) { + var e = sjcl2.json, f = e.ja.apply(e, arguments); + return e.encode(f); + }, ia: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl2.json; + b = e.g(e.g(e.g({}, e.defaults), b), c, true); + var f, g; + f = b.adata; + "string" === typeof b.salt && (b.salt = sjcl2.codec.base64.toBits(b.salt)); + "string" === typeof b.iv && (b.iv = sjcl2.codec.base64.toBits(b.iv)); + if (!sjcl2.mode[b.mode] || !sjcl2.cipher[b.cipher] || "string" === typeof a && 100 >= b.iter || 64 !== b.ts && 96 !== b.ts && 128 !== b.ts || 128 !== b.ks && 192 !== b.ks && 256 !== b.ks || !b.iv || 2 > b.iv.length || 4 < b.iv.length) + throw new sjcl2.exception.invalid("json decrypt: invalid parameters"); + "string" === typeof a ? (g = sjcl2.misc.cachedPbkdf2(a, b), a = g.key.slice(0, b.ks / 32), b.salt = g.salt) : sjcl2.ecc && a instanceof sjcl2.ecc.elGamal.secretKey && (a = a.unkem(sjcl2.codec.base64.toBits(b.kemtag)).slice(0, b.ks / 32)); + "string" === typeof f && (f = sjcl2.codec.utf8String.toBits(f)); + g = new sjcl2.cipher[b.cipher](a); + f = "ccm" === b.mode && sjcl2.arrayBuffer && sjcl2.arrayBuffer.ccm && b.ct instanceof ArrayBuffer ? sjcl2.arrayBuffer.ccm.decrypt(g, b.ct, b.iv, b.tag, f, b.ts) : sjcl2.mode[b.mode].decrypt(g, b.ct, b.iv, f, b.ts); + e.g(d, b); + d.key = a; + return 1 === c.raw ? f : sjcl2.codec.utf8String.fromBits(f); + }, decrypt: function(a, b, c, d) { + var e = sjcl2.json; + return e.ia(a, e.decode(b), c, d); + }, encode: function(a) { + var b, c = "{", d = ""; + for (b in a) + if (a.hasOwnProperty(b)) { + if (!b.match(/^[a-z0-9]+$/i)) + throw new sjcl2.exception.invalid("json encode: invalid property name"); + c += d + '"' + b + '":'; + d = ","; + switch (typeof a[b]) { + case "number": + case "boolean": + c += a[b]; + break; + case "string": + c += '"' + escape(a[b]) + '"'; + break; + case "object": + c += '"' + sjcl2.codec.base64.fromBits(a[b], 0) + '"'; + break; + default: + throw new sjcl2.exception.bug("json encode: unsupported type"); + } + } + return c + "}"; + }, decode: function(a) { + a = a.replace(/\s/g, ""); + if (!a.match(/^\{.*\}$/)) + throw new sjcl2.exception.invalid("json decode: this isn't json!"); + a = a.replace(/^\{|\}$/g, "").split(/,/); + var b = {}, c, d; + for (c = 0; c < a.length; c++) { + if (!(d = a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i))) + throw new sjcl2.exception.invalid("json decode: this isn't json!"); + null != d[3] ? b[d[2]] = parseInt(d[3], 10) : null != d[4] ? b[d[2]] = d[2].match(/^(ct|adata|salt|iv)$/) ? sjcl2.codec.base64.toBits(d[4]) : unescape(d[4]) : null != d[5] && (b[d[2]] = "true" === d[5]); + } + return b; + }, g: function(a, b, c) { + void 0 === a && (a = {}); + if (void 0 === b) + return a; + for (var d in b) + if (b.hasOwnProperty(d)) { + if (c && void 0 !== a[d] && a[d] !== b[d]) + throw new sjcl2.exception.invalid("required parameter overridden"); + a[d] = b[d]; + } + return a; + }, sa: function(a, b) { + var c = {}, d; + for (d in a) + a.hasOwnProperty(d) && a[d] !== b[d] && (c[d] = a[d]); + return c; + }, ra: function(a, b) { + var c = {}, d; + for (d = 0; d < b.length; d++) + void 0 !== a[b[d]] && (c[b[d]] = a[b[d]]); + return c; + } }; + sjcl2.encrypt = sjcl2.json.encrypt; + sjcl2.decrypt = sjcl2.json.decrypt; + sjcl2.misc.pa = {}; + sjcl2.misc.cachedPbkdf2 = function(a, b) { + var c = sjcl2.misc.pa, d; + b = b || {}; + d = b.iter || 1e3; + c = c[a] = c[a] || {}; + d = c[d] = c[d] || { firstSalt: b.salt && b.salt.length ? b.salt.slice(0) : sjcl2.random.randomWords(2, 0) }; + c = void 0 === b.salt ? d.firstSalt : b.salt; + d[c] = d[c] || sjcl2.misc.pbkdf2(a, c, b.iter); + return { key: d[c].slice(0), salt: c.slice(0) }; + }; + "undefined" !== typeof module && module.exports && (module.exports = sjcl2); + "function" === typeof define && define([], function() { + return sjcl2; + }); + } + }); + + // ../../node_modules/web-worker/cjs/browser.js + var require_browser = __commonJS({ + "../../node_modules/web-worker/cjs/browser.js"(exports, module) { + module.exports = Worker; + } + }); + + // ../../core/loaders/props/props.loader.ts + var props_loader_default = (node) => { + if (node.__properties.__props) + node.____apply(node.__properties.__props, true); + }; + + // ../../core/libraries/esmonitor/dist/index.esm.js + var __defProp2 = Object.defineProperty; + var __export = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var moduleStringTag = "[object Module]"; + var esm = (object) => { + const res = object && (!!Object.keys(object).reduce((a, b) => { + const desc = Object.getOwnPropertyDescriptor(object, b); + const isModule = desc && desc.get && !desc.set ? 1 : 0; + return a + isModule; + }, 0) || Object.prototype.toString.call(object) === moduleStringTag); + return !!res; + }; + var isSame = (a, b) => { + if (a && typeof a === "object" && b && typeof b === "object") { + const jA = JSON.stringify(a); + const jB = JSON.stringify(b); + return jA === jB; + } else + return a === b; + }; + var iterateSymbols = (obj, callback) => { + return Promise.all(Object.getOwnPropertySymbols(obj).map((sym) => callback(sym, obj[sym]))); + }; + var getPath = (type, info2) => { + const pathType = info2.path[type]; + if (!pathType) + throw new Error("Invalid Path Type"); + const filtered = pathType.filter((v) => typeof v === "string"); + return filtered.join(info2.keySeparator); + }; + var getPathInfo = (path, options) => { + let splitPath = path; + if (typeof path === "string") + splitPath = path.split(options.keySeparator); + else if (typeof path === "symbol") + splitPath = [path]; + return { + id: splitPath[0], + path: splitPath.slice(1) + }; + }; + var runCallback = (callback, path, info2, output, setGlobal = true) => { + if (callback instanceof Function) { + if (output && typeof output === "object" && typeof output.then === "function") + output.then((value) => callback(path, info2, value)); + else + callback(path, info2, output); + } + if (setGlobal && globalThis.ESMonitorState) { + const callback2 = globalThis.ESMonitorState.callback; + globalThis.ESMonitorState.state[path] = { output, value: info2 }; + runCallback(callback2, path, info2, output, false); + } + }; + var defaultSamplingRate = 60; + var _pollingId, _sps, _a; + var Poller = (_a = class { + constructor(listeners2, sps) { + __privateAdd(this, _pollingId, void 0); + __privateAdd(this, _sps, void 0); + this.listeners = {}; + this.setOptions = (opts = {}) => { + for (let key in opts) + this[key] = opts[key]; + }; + this.add = (info2) => { + const sub = info2.sub; + this.listeners[sub] = info2; + this.start(); + return true; + }; + this.get = (sub) => this.listeners[sub]; + this.remove = (sub) => { + delete this.listeners[sub]; + if (!Object.keys(this.listeners).length) + this.stop(); + }; + this.poll = (listeners22) => { + iterateSymbols(listeners22, (sym, o) => { + let { callback, current, history } = o; + if (!o.path.resolved) + o.path.resolved = getPath("output", o); + if (!isSame(current, history)) { + runCallback(callback, o.path.resolved, {}, current); + if (typeof current === "object") { + if (Array.isArray(current)) + history = [...current]; + else + history = { ...current }; + } else + listeners22[sym].history = current; + } + }); + }; + this.start = (listeners22 = this.listeners) => { + if (!this.sps) + this.sps = defaultSamplingRate; + else if (!__privateGet(this, _pollingId)) { + console.warn("[escode]: Starting Polling!"); + __privateSet(this, _pollingId, setInterval(() => this.poll(listeners22), 1e3 / this.sps)); + } + }; + this.stop = () => { + if (__privateGet(this, _pollingId)) { + console.warn("[escode]: Stopped Polling!"); + clearInterval(__privateGet(this, _pollingId)); + __privateSet(this, _pollingId, void 0); + } + }; + if (listeners2) + this.listeners = listeners2; + if (sps) + this.sps = sps; + } + get sps() { + return __privateGet(this, _sps); + } + set sps(sps) { + __privateSet(this, _sps, sps); + const listeners2 = this.listeners; + const nListeners = Object.keys(listeners2).length; + if (nListeners) { + this.stop(); + this.start(); + } + } + }, _pollingId = new WeakMap(), _sps = new WeakMap(), _a); + var listeners_exports = {}; + __export(listeners_exports, { + functionExecution: () => functionExecution, + functions: () => functions2, + getProxyFunction: () => getProxyFunction, + info: () => info, + register: () => register, + set: () => set, + setterExecution: () => setterExecution, + setters: () => setters + }); + globalThis.ESMonitorState = { + state: {}, + callback: void 0, + info: {} + }; + var global_default = globalThis.ESMonitorState; + var performance2 = async (callback, args) => { + const tic = globalThis.performance.now(); + const output = await callback(...args); + const toc = globalThis.performance.now(); + return { + output, + value: toc - tic + }; + }; + var infoFunctions = { + performance: performance2 + }; + var get = (func, args, info2) => { + let result = { + value: {}, + output: void 0 + }; + const infoToGet = { ...global_default.info, ...info2 }; + for (let key in infoToGet) { + if (infoToGet[key] && infoFunctions[key]) { + const ogFunc = func; + func = async (...args2) => { + const o = await infoFunctions[key](ogFunc, args2); + result.value[key] = o.value; + return o.output; + }; + } + } + result.output = func(...args); + return result; + }; + var isProxy = Symbol("isProxy"); + var fromInspectable = Symbol("fromInspectable"); + var fromInspectableHandler = Symbol("fromInspectableHandler"); + var keySeparator = "."; + var hasKey = (key, obj) => key in obj; + var getShortcut = (path, shortcuts, keySeparator2) => { + const sc = shortcuts[path[0]]; + if (sc) { + const value = sc[path.slice(1).join(keySeparator2)]; + if (value) + return value; + } + }; + var getFromPath = (baseObject, path, opts = {}) => { + const fallbackKeys = opts.fallbacks ?? []; + const keySeparator2 = opts.keySeparator ?? keySeparator; + if (opts.shortcuts) { + const shortcut = getShortcut(path, opts.shortcuts, keySeparator2); + if (shortcut) { + if (opts.output === "info") + return { value: shortcut, exists: true, shortcut: true }; + else + return shortcut; + } + } + if (typeof path === "string") + path = path.split(keySeparator2).flat(); + else if (typeof path == "symbol") + path = [path]; + let exists; + path = [...path]; + path = path.map((o) => typeof o === "string" ? o.split(keySeparator2) : o).flat(); + let ref = baseObject; + for (let i = 0; i < path.length; i++) { + if (ref) { + const str = path[i]; + if (!hasKey(str, ref) && "__children" in ref) { + for (let i2 in fallbackKeys) { + const key = fallbackKeys[i2]; + if (hasKey(key, ref)) { + ref = ref[key]; + break; + } + } + } + exists = hasKey(str, ref); + if (exists) + ref = ref[str]; + else { + ref = void 0; + exists = true; + } + } + } + if (opts.output === "info") + return { value: ref, exists }; + else + return ref; + }; + var setFromPath = (path, value, ref, opts = {}) => { + const create = opts?.create ?? false; + const keySeparator2 = opts?.keySeparator ?? keySeparator; + if (typeof path === "string") + path = path.split(keySeparator2); + else if (typeof path == "symbol") + path = [path]; + path = [...path]; + const copy = [...path]; + const last = copy.pop(); + if (ref.__children) + ref = ref.__children; + for (let i = 0; i < copy.length; i++) { + const str = copy[i]; + let has = hasKey(str, ref); + if (create && !has) { + ref[str] = {}; + has = true; + } + if (has) + ref = ref[str]; + if (ref.__children) + ref = ref.__children; + } + ref[last] = value; + return true; + }; + var handlers_exports = {}; + __export(handlers_exports, { + functions: () => functions, + objects: () => objects + }); + function define2(key, registerAsNewKey) { + const inspectable = this; + const target = this.target; + if (!this.parent) { + let value = target[key]; + if (typeof value === "function") { + target[key] = async (...args) => await this.proxy[key]({ [fromInspectable]: true, value }, ...args); + } else { + try { + Object.defineProperty(target, key, { + get: () => value, + set: function(val) { + value = val; + inspectable.proxy[key] = { [isProxy]: this[isProxy], [fromInspectable]: true, value: val }; + }, + enumerable: true, + configurable: true + }); + } catch (e) { + console.error(`Could not reassign ${key} to a top-level setter...`); + } + } + } + if (registerAsNewKey) + this.newKeys.add(key); + this.create(key, target, void 0, true); + } + var define_default = define2; + var functions = function() { + const inspectable = this; + return { + apply: async function(target, thisArg, argumentsList) { + try { + let foo = target; + const isFromInspectable = argumentsList[0]?.[fromInspectable]; + if (isFromInspectable) { + foo = argumentsList[0].value; + argumentsList = argumentsList.slice(1); + } + let listeners2 = inspectable.listeners.functions; + const pathStr = inspectable.path.join(inspectable.options.keySeparator); + const toActivate = listeners2 ? listeners2[pathStr] : void 0; + let output, executionInfo = {}; + if (toActivate) { + executionInfo = functionExecution(thisArg, toActivate, foo, argumentsList); + output = executionInfo.output; + } else { + output = foo.apply(thisArg, argumentsList); + executionInfo = inspectable?.state?.[pathStr]?.value ?? {}; + } + const callback = inspectable.options.callback; + runCallback(callback, pathStr, executionInfo, output); + return output; + } catch (e) { + console.warn(`Function failed:`, e, inspectable.path); + } + } + }; + }; + var objects = function() { + const inspectable = this; + return { + get(target, prop, receiver) { + if (prop === isProxy) + return true; + return Reflect.get(target, prop, receiver); + }, + set(target, prop, newVal, receiver) { + if (prop === isProxy) + return true; + const pathStr = [...inspectable.path, prop].join(inspectable.options.keySeparator); + const isFromProxy = newVal?.[isProxy]; + const isFromInspectable = newVal?.[fromInspectable]; + if (isFromInspectable) + newVal = newVal.value; + const listeners2 = inspectable.listeners.setters; + const desc = Object.getOwnPropertyDescriptor(target, prop); + const createListener = desc && !desc.get && !desc.set; + if (createListener) { + if (typeof inspectable.options.globalCallback === "function") { + const id = inspectable.path[0]; + define_default.call(inspectable, prop, true); + set("setters", pathStr, newVal, inspectable.options.globalCallback, { [id]: inspectable.root }, inspectable.listeners, inspectable.options); + } + } + if (newVal) { + const newProxy = inspectable.create(prop, target, newVal); + if (newProxy) + newVal = newProxy; + } + const toActivate = !isFromProxy; + if (listeners2 && toActivate && !inspectable.newKeys.has(prop)) { + const toActivate2 = listeners2[pathStr]; + if (toActivate2) + setterExecution(toActivate2, newVal); + } + const callback = inspectable.options.callback; + const info2 = inspectable?.state?.[pathStr]?.value ?? {}; + runCallback(callback, pathStr, info2, newVal); + if (isFromInspectable || !toActivate) + return true; + else + return Reflect.set(target, prop, newVal, receiver); + } + }; + }; + var canCreate = (parent, key, val) => { + try { + if (val === void 0) + val = parent[key]; + } catch (e) { + return e; + } + const alreadyIs = parent[key] && parent[key][isProxy]; + if (alreadyIs) + return false; + const type = typeof val; + const isObject = type === "object"; + const isFunction = type == "function"; + const notObjOrFunc = !val || !(isObject || isFunction); + if (notObjOrFunc) + return false; + if (val instanceof Element) + return false; + if (val instanceof EventTarget) + return false; + const isESM = isObject && esm(val); + if (isFunction) + return true; + else { + const desc = Object.getOwnPropertyDescriptor(parent, key); + if (desc && (desc.value && desc.writable || desc.set)) { + if (!isESM) + return true; + } else if (!parent.hasOwnProperty(key)) + return true; + } + return false; + }; + var Inspectable = class { + constructor(target = {}, opts = {}, name, parent) { + this.path = []; + this.listeners = {}; + this.newKeys = /* @__PURE__ */ new Set(); + this.state = {}; + this.set = (path, info2, update) => { + this.state[path] = { + output: update, + value: info2 + }; + setFromPath(path, update, this.proxy, { create: true }); + }; + this.check = canCreate; + this.create = (key, parent2, val, set2 = false) => { + const create = this.check(parent2, key, val); + if (val === void 0) + val = parent2[key]; + if (create && !(create instanceof Error)) { + parent2[key] = new Inspectable(val, this.options, key, this); + return parent2[key]; + } + if (set2) { + try { + this.proxy[key] = val ?? parent2[key]; + } catch (e) { + const isESM = esm(parent2); + const path = [...this.path, key]; + console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM ? " because the parent is an ESM." : ""}`, isESM ? "" : e); + } + } + return; + }; + if (!opts.pathFormat) + opts.pathFormat = "relative"; + if (!opts.keySeparator) + opts.keySeparator = keySeparator; + if (target.__proxy) + this.proxy = target.__proxy; + else if (target[isProxy]) + this.proxy = target; + else { + this.target = target; + this.options = opts; + this.parent = parent; + if (this.parent) { + this.root = this.parent.root; + this.path = [...this.parent.path]; + this.state = this.parent.state ?? {}; + } else + this.root = target; + if (name) + this.path.push(name); + if (this.options.listeners) + this.listeners = this.options.listeners; + if (this.options.path) { + if (this.options.path instanceof Function) + this.path = this.options.path(this.path); + else if (Array.isArray(this.options.path)) + this.path = this.options.path; + else + console.log("Invalid path", this.options.path); + } + if (this.path) + this.path = this.path.filter((str) => typeof str === "string"); + if (!this.options.keySeparator) + this.options.keySeparator = keySeparator; + let type = this.options.type; + if (type != "object") + type = typeof target === "function" ? "function" : "object"; + const handler2 = handlers_exports[`${type}s`].call(this); + this.proxy = new Proxy(target, handler2); + Object.defineProperty(target, "__proxy", { value: this.proxy, enumerable: false }); + Object.defineProperty(target, "__esInspectable", { value: this, enumerable: false }); + for (let key in target) + define_default.call(this, key); + } + return this.proxy; + } + }; + var setFromOptions = (path, value, baseOptions, opts) => { + const ref = opts.reference; + const id = Array.isArray(path) ? path[0] : typeof path === "string" ? path.split(baseOptions.keySeparator)[0] : path; + let isDynamic = opts.hasOwnProperty("static") ? !opts.static : false; + if (isDynamic && !globalThis.Proxy) { + isDynamic = false; + console.warn("Falling back to using function interception and setters..."); + } + if (isDynamic) { + value = new Inspectable(value, { + pathFormat: baseOptions.pathFormat, + keySeparator: baseOptions.keySeparator, + listeners: opts.listeners, + path: (path2) => path2.filter((str) => !baseOptions.fallbacks || !baseOptions.fallbacks.includes(str)) + }, id); + } + let options = { keySeparator: baseOptions.keySeparator, ...opts }; + setFromPath(path, value, ref, options); + return value; + }; + var info = (id, callback, path, originalValue, base, listeners2, options, refShortcut = {}) => { + if (typeof path === "string") + path = path.split(options.keySeparator); + const relativePath = path.join(options.keySeparator); + const refs = base; + const shortcutRef = refShortcut.ref; + const shortcutPath = refShortcut.path; + const get3 = (path2) => { + const thisBase = shortcutRef ?? base; + const res = getFromPath(thisBase, path2, { + keySeparator: options.keySeparator, + fallbacks: options.fallbacks + }); + return res; + }; + const set2 = (path2, value) => { + const thisBase = shortcutRef ?? base; + setFromOptions(path2, value, options, { + reference: thisBase, + listeners: listeners2 + }); + }; + let onUpdate = options.onUpdate; + let infoToOutput = {}; + if (onUpdate && typeof onUpdate === "object" && onUpdate.callback instanceof Function) { + infoToOutput = onUpdate.info ?? {}; + onUpdate = onUpdate.callback; + } + const absolute = [id, ...path]; + let pathInfo = { + absolute, + relative: relativePath.split(options.keySeparator), + parent: absolute.slice(0, -1) + }; + pathInfo.output = pathInfo[options.pathFormat]; + const completePathInfo = pathInfo; + const info2 = { + id, + path: completePathInfo, + keySeparator: options.keySeparator, + infoToOutput, + callback: (...args) => { + const output = callback(...args); + if (onUpdate instanceof Function) + onUpdate(...args); + return output; + }, + get current() { + return get3(shortcutPath ?? info2.path.absolute); + }, + set current(val) { + set2(shortcutPath ?? info2.path.absolute, val); + }, + get parent() { + return get3(shortcutPath ? shortcutPath?.slice(0, -1) : info2.path.parent); + }, + get reference() { + return refs[id]; + }, + set reference(val) { + refs[id] = val; + }, + original: originalValue, + history: typeof originalValue === "object" ? Object.assign({}, originalValue) : originalValue, + sub: Symbol("subscription"), + last: path.slice(-1)[0] + }; + return info2; + }; + var registerInLookup = (name, sub, lookups) => { + if (lookups) { + const id = Math.random(); + lookups.symbol[sub] = { + name, + id + }; + if (!lookups.name[name]) + lookups.name[name] = {}; + lookups.name[name][id] = sub; + } + }; + var register = (info2, collection, lookups) => { + const absolute = getPath("absolute", info2); + if (!collection[absolute]) + collection[absolute] = {}; + collection[absolute][info2.sub] = info2; + registerInLookup(absolute, info2.sub, lookups); + return true; + }; + var listeners = { + functions: functions2, + setters + }; + var set = (type, absPath, value, callback, base, allListeners, options) => { + const { id, path } = getPathInfo(absPath, options); + const fullInfo = info(id, callback, path, value, base, listeners, options); + if (listeners[type]) + listeners[type](fullInfo, allListeners[type], allListeners.lookup); + else { + const path2 = getPath("absolute", fullInfo); + allListeners[type][path2][fullInfo.sub] = fullInfo; + if (allListeners.lookup) + registerInLookup(path2, fullInfo.sub, allListeners.lookup); + } + }; + var get2 = (info2, collection) => collection[getPath("absolute", info2)]; + var handler = (info2, collection, subscribeCallback, lookups) => { + let success = !!get2(info2, collection); + if (!success) { + let parent = info2.parent; + let val = parent?.[info2.last]; + success = subscribeCallback(val, parent); + } + return register(info2, collection, lookups); + }; + var setterExecution = (listeners2, value) => { + return iterateSymbols(listeners2, (_, o) => { + const path = getPath("output", o); + runCallback(o.callback, path, {}, value); + }); + }; + function setters(info2, collection, lookups) { + const thisValue = this; + return handler(info2, collection["setters"], (value, parent) => { + let val = value; + if (!parent) + return; + if (!parent[isProxy]) { + let redefine = true; + try { + delete parent[info2.last]; + } catch (e) { + console.error("Unable to redeclare setters. May already be a dynamic object..."); + redefine = false; + } + if (redefine) { + try { + Object.defineProperty(parent, info2.last, { + get: () => val, + set: async (v) => { + const isFunction = typeof val === "function"; + val = v; + if (!isFunction) { + const listeners2 = Object.assign({}, collection["setters"][getPath("absolute", info2)]); + setterExecution(listeners2, v); + } else + val = getProxyFunction.call(thisValue, info2, collection, val); + }, + enumerable: true, + configurable: true + }); + } catch (e) { + throw e; + } + } + } + }, lookups); + } + function getProxyFunction(info2, collection, fn) { + return function(...args) { + const listeners2 = collection["functions"][getPath("absolute", info2)]; + return functionExecution(this, listeners2, fn ?? info2.original, args); + }; + } + var functionExecution = (context, listeners2, func, args) => { + listeners2 = Object.assign({}, listeners2); + const keys = Object.getOwnPropertySymbols(listeners2); + const infoTemplate = listeners2[keys[0]] ?? {}; + const executionInfo = get((...args2) => func.call(context, ...args2), args, infoTemplate.infoToOutput); + iterateSymbols(listeners2, (_, o) => { + const path = getPath("output", o); + runCallback(o.callback, path, executionInfo.value, executionInfo.output); + }); + return executionInfo; + }; + function functions2(info2, collection, lookups) { + return handler(info2, collection["functions"], (_, parent) => { + if (!parent[isProxy]) { + parent[info2.last] = getProxyFunction.call(this, info2, collection); + return setters(info2, collection, lookups); + } + }, lookups); + } + var drillSimple = (obj, callback, options) => { + let accumulator = options.accumulator; + if (!accumulator) + accumulator = options.accumulator = {}; + const ignore = options.ignore || []; + const path = options.path || []; + const condition = options.condition || true; + const seen = []; + const fromSeen = []; + let drill = (obj2, acc = {}, globalInfo) => { + for (let key in obj2) { + if (ignore.includes(key)) + continue; + const val = obj2[key]; + const newPath = [...globalInfo.path, key]; + const info2 = { + typeof: typeof val, + name: val?.constructor?.name, + simple: true, + object: val && typeof val === "object", + path: newPath + }; + if (info2.object) { + const name = info2.name; + const isESM = esm(val); + if (isESM || name === "Object" || name === "Array") { + info2.simple = true; + const idx = seen.indexOf(val); + if (idx !== -1) + acc[key] = fromSeen[idx]; + else { + seen.push(val); + const pass = condition instanceof Function ? condition(key, val, info2) : condition; + info2.pass = pass; + acc[key] = callback(key, val, info2); + if (pass) { + fromSeen.push(acc[key]); + acc[key] = drill(val, acc[key], { ...globalInfo, path: newPath }); + } + } + } else { + info2.simple = false; + acc[key] = callback(key, val, info2); + } + } else + acc[key] = callback(key, val, info2); + } + return acc; + }; + return drill(obj, accumulator, { path }); + }; + var createLookup = () => { + return { symbol: {}, name: {} }; + }; + var Monitor = class { + constructor(opts = {}) { + this.poller = new Poller(); + this.options = { + pathFormat: "relative", + keySeparator + }; + this.listeners = { + polling: this.poller.listeners, + functions: {}, + setters: {}, + lookup: createLookup() + }; + this.references = {}; + this.get = (path, output, reference = this.references, throwError = true) => { + return getFromPath(reference, path, { + keySeparator: this.options.keySeparator, + fallbacks: this.options.fallbacks, + output + }, throwError); + }; + this.set = (path, value, opts2 = {}) => { + const optsCopy = { ...opts2 }; + if (!optsCopy.reference) + optsCopy.reference = this.references; + if (!optsCopy.listeners) + optsCopy.listeners = this.listeners; + return setFromOptions(path, value, this.options, optsCopy); + }; + this.on = (absPath, callback) => { + const info2 = getPathInfo(absPath, this.options); + return this.listen(info2.id, callback, info2.path); + }; + this.getInfo = (label, callback, path, original) => { + const info2 = info(label, callback, path, original, this.references, this.listeners, this.options); + const id = Math.random(); + const lookups = this.listeners.lookup; + const name = getPath("absolute", info2); + lookups.symbol[info2.sub] = { + name, + id + }; + if (!lookups.name[name]) + lookups.name[name] = {}; + lookups.name[name][id] = info2.sub; + return info2; + }; + this.listen = (id, callback, path = [], __internal = {}) => { + if (typeof path === "string") + path = path.split(this.options.keySeparator); + else if (typeof path === "symbol") + path = [path]; + const arrayPath = path; + let baseRef = this.get(id); + if (!baseRef) { + console.error(`Reference does not exist.`, id); + return; + } + if (!__internal.poll) + __internal.poll = esm(baseRef); + if (!__internal.seen) + __internal.seen = []; + const __internalComplete = __internal; + const thisPath = [id, ...arrayPath]; + const ref = this.get(thisPath); + const toMonitorInternally = (val, allowArrays = false) => { + const first = val && typeof val === "object"; + if (!first) + return false; + const isEl = val instanceof Element; + if (isEl) + return false; + if (allowArrays) + return true; + else + return !Array.isArray(val); + }; + let subs = {}; + const subscribeAll = toMonitorInternally(ref, true); + if (subscribeAll) { + if (ref.__esInspectable) + ref.__esInspectable.options.globalCallback = callback; + drillSimple(ref, (_, __, drillInfo) => { + if (drillInfo.pass) + return; + else { + const fullPath = [...arrayPath, ...drillInfo.path]; + const internalSubs = this.listen(id, callback, fullPath, __internalComplete); + Object.assign(subs, internalSubs); + } + }, { + condition: (_, val) => toMonitorInternally(val) + }); + } + let info2; + let success = false; + try { + info2 = this.getInfo(id, callback, arrayPath, ref); + if (info2) { + if (__internalComplete.poll) + success = this.poller.add(info2); + else { + let type = "setters"; + if (typeof ref === "function") + type = "functions"; + success = this.add(type, info2); + } + } + } catch (e) { + console.error("Fallback to polling:", path, e); + success = this.poller.add(info2); + } + if (success) { + subs[getPath("absolute", info2)] = info2.sub; + if (this.options.onInit instanceof Function) { + const executionInfo = {}; + for (let key in info2.infoToOutput) + executionInfo[key] = void 0; + this.options.onInit(getPath("output", info2), executionInfo); + } + return subs; + } else { + console.error("Failed to subscribe to:", path); + return; + } + }; + this.add = (type, info2) => { + if (listeners_exports[type]) + return listeners_exports[type](info2, this.listeners, this.listeners.lookup); + else { + this.listeners[type][getPath("absolute", info2)][info2.sub] = info2; + return true; + } + }; + this.remove = (subs) => { + if (!subs) { + subs = { + ...this.listeners.functions, + ...this.listeners.setters, + ...this.listeners.polling + }; + } + if (typeof subs !== "object") + subs = { sub: subs }; + for (let key in subs) { + let innerSub = subs[key]; + const handleUnsubscribe = (sub) => { + const res = this.unsubscribe(sub); + if (res === false) + console.warn(`Subscription for ${key} does not exist.`, sub); + }; + if (typeof innerSub !== "symbol") + iterateSymbols(innerSub, handleUnsubscribe); + else + handleUnsubscribe(innerSub); + } + return true; + }; + this.unsubscribe = (sub) => { + const info2 = this.listeners.lookup.symbol[sub]; + const absPath = info2.name; + const polling = this.poller.get(sub); + const funcs = this.listeners.functions[absPath]; + const func = funcs?.[sub]; + const setters2 = this.listeners.setters[absPath]; + const setter = setters2?.[sub]; + if (polling) + this.poller.remove(sub); + else if (func) { + delete funcs[sub]; + if (!Object.getOwnPropertySymbols(funcs).length) { + Object.defineProperty(func.parent, func.last, { + value: func.original, + writable: true + }); + delete this.listeners.functions[absPath]; + } + } else if (setter) { + delete setters2[sub]; + if (!Object.getOwnPropertySymbols(setters2).length) { + const parent = setter.parent; + if (parent) { + const last = setter.last; + const value = parent[last]; + Object.defineProperty(parent, last, { value, writable: true }); + } + delete this.listeners.setters[absPath]; + } + } else + return false; + delete this.listeners.lookup.symbol[sub]; + const nameLookup = this.listeners.lookup.name[info2.name]; + delete nameLookup[info2.id]; + if (!Object.getOwnPropertyNames(nameLookup).length) + delete this.listeners.lookup.name[info2.name]; + }; + Object.defineProperty(this.listeners, "lookup", { + value: createLookup(), + enumerable: false, + configurable: false + }); + Object.assign(this.options, opts); + this.poller.setOptions(opts.polling); + } + }; + var src_default = Monitor; + + // ../../core/libraries/edgelord/index.ts + var defaultPath = "default"; + var operatorPath = "__operator"; + var specialKeys = { + path: "__path", + isGraphScript: "__", + listeners: { + value: "__listeners", + branch: "__branch", + bind: "__bind", + trigger: "__trigger", + format: "__format" + } + }; + var listenerObject = Symbol("listenerObject"); + var toSet = Symbol("toSet"); + var subscriptionKey = Symbol("subscriptionKey"); + var configKey = Symbol("configKey"); + var toResolveWithKey = Symbol("toResolveWithKey"); + var isConfigObject = (o) => specialKeys.listeners.format in o || specialKeys.listeners.branch in o || specialKeys.listeners.trigger in o || specialKeys.listeners.bind in o; + var initializedStatus = "INITIALIZED"; + var registeredStatus = "REGISTERED"; + var globalFrom = {}; + var globalTo = {}; + var globalActive = {}; + var _triggers, _queue, _toResolveWith, _initialize, _getAbsolutePath, _getPathInfo; + var Edgelord = class { + constructor(listeners2, root, context) { + this.original = {}; + this.active = {}; + this.globals = {}; + this.context = { + options: {} + }; + this.rootPath = ""; + this.status = ""; + __privateAdd(this, _triggers, []); + __privateAdd(this, _queue, []); + __privateAdd(this, _toResolveWith, void 0); + this.setInitialProperties = (listeners2 = {}, root, context = {}) => { + Object.assign(this.context, context); + if (root) + this.rootPath = root; + if (!this.context.options.keySeparator) + this.context.options.keySeparator = this.context.monitor.options.keySeparator; + this.original = listeners2; + const globals = [{ name: "active", ref: globalActive }, { name: "from", ref: globalFrom }, { name: "to", ref: globalTo }]; + globals.forEach((o) => { + if (!o.ref[this.context.id]) + o.ref[this.context.id] = {}; + this.globals[o.name] = o.ref[this.context.id]; + }); + __privateSet(this, _toResolveWith, this.getManager()); + this.runEachListener(listeners2, this.addToGlobalLog); + }; + this.getManager = (mode = "from") => { + let target = mode === "to" ? this.globals.to : this.globals.from; + this.rootPath.split(this.context.options.keySeparator).forEach((key) => { + if (!target[key]) + target[key] = {}; + target = target[key]; + }); + return target[toResolveWithKey] ?? this; + }; + this.onStart = (f) => { + const res = __privateGet(this, _toResolveWith); + const isSame2 = res === this; + if (isSame2) { + if (this.status === initializedStatus) + f(); + else + __privateGet(this, _queue).push(f); + } else + res.onStart(f); + }; + this.runEachListener = (listeners2, callback) => { + if (!callback) + return; + for (const first in listeners2) { + const second = listeners2[first]; + if (!second) { + console.warn("Skipping empty listener:", first); + continue; + } + if (second && typeof second === "object") { + const from = second; + const to = first; + for (let fromPath in from) { + callback(fromPath, to, from[fromPath]); + } + } else { + const from = first; + const to = second; + const typeOf = typeof to; + if (typeOf === "function") + callback(from, "", to); + else if (typeOf === "string") + callback(from, to, to); + else + console.error("Improperly Formatted Listener", to); + } + } + }; + this.register = (listeners2 = this.original) => { + this.runEachListener(listeners2, this.add); + this.status = registeredStatus; + }; + __privateAdd(this, _initialize, (o) => { + const res = this.context.monitor.get(o.path, "info"); + if (typeof res.value === "function") { + const args = Array.isArray(o.args) ? o.args : [o.args]; + res.value(...args); + } else + console.error("Cannot yet trigger values...", o); + }); + this.initialize = (o) => { + if (!this.status) + __privateGet(this, _triggers).push(o); + else if (this.status === registeredStatus) { + this.status = initializedStatus; + __privateGet(this, _triggers).forEach(__privateGet(this, _initialize)); + __privateGet(this, _queue).forEach((f) => f()); + __privateSet(this, _queue, []); + __privateSet(this, _triggers, []); + } else + __privateGet(this, _initialize).call(this, o); + }; + this.start = () => { + this.register(); + this.initialize(); + }; + __privateAdd(this, _getAbsolutePath, (name) => { + const sep = this.context.monitor.options.keySeparator; + return !name || !this.rootPath || this.rootPath === name.slice(0, this.rootPath.length) && name[this.rootPath.length] === sep ? name : [this.rootPath, name].join(sep); + }); + __privateAdd(this, _getPathInfo, (path) => { + const output = { + absolute: {}, + relative: {} + }; + path = __privateGet(this, _getAbsolutePath).call(this, path); + let rel = this.rootPath ? path.replace(`${this.rootPath}.`, "") : path; + const baseArr = path.split(this.context.options.keySeparator); + output.absolute.array = [this.context.id, ...baseArr]; + output.relative.array = rel.split(this.context.options.keySeparator); + let obj = this.context.monitor.get(output.relative.array, void 0, this.context.instance, false); + if (this.context.graph) { + if (obj && this.context.bound) { + output.absolute.array = [this.context.id, this.context.bound, ...output.absolute.array.slice(1)]; + output.relative.array.unshift(this.context.bound); + } else if (!obj) { + const rel2 = output.relative.array.join(this.context.options.keySeparator); + obj = this.context.graph.get(rel2); + } + } + const isGraphScript = obj && typeof obj === "object" && specialKeys.isGraphScript in obj; + if (isGraphScript) { + if (obj[operatorPath]) { + output.absolute.array.push(operatorPath); + output.relative.array.push(operatorPath); + } else if (obj[defaultPath]) { + output.absolute.array.push(defaultPath); + output.relative.array.push(defaultPath); + } + } + output.absolute.value = output.absolute.array.slice(1).join(this.context.options.keySeparator); + output.relative.value = output.relative.array.join(this.context.options.keySeparator); + return output; + }); + this.add = (from, to, value = true, subscription) => { + if (typeof to == "function") { + value = to; + to = ""; + } else if (typeof to !== "string") { + console.error("Improperly Formatted Listener", from, to, value); + return; + } + if (!value) + return; + const fromInfo = __privateGet(this, _getPathInfo).call(this, from); + const toInfo = __privateGet(this, _getPathInfo).call(this, to); + const absPath = fromInfo.absolute.value; + if (!subscription) + subscription = this.globals.active[absPath]?.[subscriptionKey]; + if (!subscription) { + subscription = this.context.monitor.on(fromInfo.absolute.array, (path, _, update) => this.activate(path, update), { + ref: this.context.instance, + path: fromInfo.relative.array + }); + } + if (typeof value == "string") + value = toInfo.absolute.array.slice(1).join(this.context.options.keySeparator); + const info2 = { + value, + [listenerObject]: true + }; + const refs = [this.active, this.globals.active]; + refs.forEach((ref) => { + if (!ref[absPath]) + ref[absPath] = {}; + const base = ref[absPath]; + if (!base[subscriptionKey]) { + Object.defineProperty(base, subscriptionKey, { + value: subscription, + configurable: true + }); + } + base[toInfo.absolute.value] = info2; + }); + const args = value[specialKeys.listeners.trigger]; + if (args) + __privateGet(this, _toResolveWith).initialize({ + path: fromInfo.absolute.array, + args + }); + this.addToGlobalLog(absPath); + return info2; + }; + this.addToGlobalLog = (path, mode = "from") => { + const absolutePath = __privateGet(this, _getAbsolutePath).call(this, path); + let target = mode === "to" ? this.globals.to : this.globals.from; + const globalPath = absolutePath.split(this.context.options.keySeparator); + globalPath.forEach((key) => { + if (!target[key]) + target[key] = {}; + target = target[key]; + if (!target[toResolveWithKey]) + target[toResolveWithKey] = this; + }); + }; + this.remove = (from, to) => { + const fromInfo = __privateGet(this, _getPathInfo).call(this, from); + const toInfo = __privateGet(this, _getPathInfo).call(this, to); + const path = [fromInfo.absolute.value, toInfo.absolute.value]; + const toRemove = [ + { ref: this.active, path }, + { ref: this.globals.active, path, unlisten: true } + ]; + toRemove.forEach((o) => { + const { ref, path: path2, unlisten } = o; + let base = ref[path2[0]]; + if (typeof base === "object") { + delete base[path2[1]]; + if (Object.keys(base).length === 0) { + delete ref[path2[0]]; + const sub = base[subscriptionKey]; + if (unlisten && sub) { + this.context.monitor.remove(sub); + } + delete base[subscriptionKey]; + } + } else + delete ref[path2[0]]; + }); + }; + this.clear = (name) => { + const value = __privateGet(this, _getAbsolutePath).call(this, name); + Object.keys(this.active).forEach((from) => { + Object.keys(this.active[from]).forEach((to) => { + if (!value || from.slice(0, value.length) === value || to.slice(0, value.length) === value) + this.remove(from, to); + }); + }); + }; + this.has = (from, ref = this.active) => !!ref[from]; + this.get = (from, ref = this.active) => ref[from]; + this.activate = (from, update) => { + const listenerGroups = [{ + info: this.get(from, this.globals.active), + name: from + }]; + listenerGroups.forEach((group) => { + const info2 = group.info; + if (info2) { + if (info2[listenerObject]) { + this.pass(from, { + value: info2.value, + parent: this.active, + key: group.name, + subscription: info2.subscription, + __value: true + }, update); + } else if (typeof info2 === "object") { + for (let key in info2) { + this.pass(from, { + parent: info2, + key, + subscription: info2[key].subscription, + value: info2[key].value + }, update); + } + } else + console.error("Improperly Formatted Listener", info2); + } + }); + }; + this.pass = (from, target, update) => { + const id = this.context.id; + const isValue = target?.__value; + let parent = target.parent; + let to = target.key; + const info2 = target.parent[to]; + target = info2.value; + let config = info2?.[configKey]; + let ogValue = target; + const type = typeof target; + const checkIfSetter = (path, willSet) => { + const info3 = this.context.monitor.get(path, "info"); + if (info3.exists) { + const val = info3.value; + const noDefault = typeof val !== "function" && !val?.default; + const value = noDefault ? toSet : val; + const res = { value }; + if (willSet) { + target = res.value; + parent[to] = res; + } + return res; + } else + return { value: void 0 }; + }; + const transform = (willSet) => { + const fullPath = [id]; + fullPath.push(...to.split(this.context.options.keySeparator)); + return checkIfSetter(fullPath, willSet); + }; + const getPathArray = (latest) => { + const path = [id]; + const topPath = []; + if (this.rootPath) + topPath.push(...this.rootPath.split(this.context.options.keySeparator)); + topPath.push(...latest.split(this.context.options.keySeparator)); + path.push(...topPath); + return path; + }; + if (typeof target === "boolean") { + if (!isValue) + transform(true); + else + console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`); + } else if (type === "string") { + const path = getPathArray(ogValue); + checkIfSetter(path, true); + if (isValue) { + parent[to] = { [ogValue]: parent[to] }; + to = ogValue; + } + } else if (target && type === "object") { + const isConfig = isConfigObject(ogValue); + if (isConfig) { + if ("value" in ogValue) { + if (isValue) { + target = parent[to] = ogValue.value; + } else { + target = parent[to].value = ogValue.value; + } + } else + transform(true); + if (ogValue) { + if (ogValue) + config = ogValue; + } + Object.defineProperty(parent[to], configKey, { value: config }); + } + } + let isValidInput = true; + if (config) { + const bindKey = specialKeys.listeners.value; + if (bindKey in config) { + const path = getPathArray(config[bindKey].original ?? config[bindKey]); + if (typeof config[bindKey] === "string") { + const res = this.context.monitor.get(path); + if (!res) + target = `because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.`; + else { + config[bindKey] = { + value: res, + original: config[bindKey] + }; + } + } else if (!config[bindKey].value.__parent) { + target = `because ${config[bindKey].original ?? id.toString()} has become unparented.`; + } + } else { + const branchKey = specialKeys.listeners.branch; + const formatKey = specialKeys.listeners.format; + if (branchKey in config) { + const isValid = config[branchKey].find((o) => { + let localValid = []; + if ("if" in o) + localValid.push(o.if(update)); + if ("is" in o) + localValid.push(o.is === update); + const isValidLocal = localValid.length > 0 && localValid.reduce((a, b) => a && b, true); + if (isValidLocal) { + if ("value" in o) + update = o.value; + } + return isValidLocal; + }); + if (!isValid) + isValidInput = false; + } + if (formatKey in config) { + try { + update = config[formatKey](update); + if (update === void 0) + isValidInput = false; + } catch (e) { + console.error("Failed to format arguments", e); + } + } + } + } + if (isValidInput && update !== void 0) { + const arrayUpdate = Array.isArray(update) ? update : [update]; + if (target === toSet) { + const parentPath = [id]; + parentPath.push(...to.split(this.context.options.keySeparator)); + const idx = parentPath.pop(); + const info3 = this.context.monitor.get(parentPath, "info"); + if (info3.value) + info3.value[idx] = update; + else + console.error(`Cannot set value on ${parentPath.filter((str) => typeof str !== "symbol").join(this.context.options.keySeparator)} from ${from}`); + } else if (target?.default) + target.default.call(target, ...arrayUpdate); + else if (typeof target === "function") { + const noContext = parent[to][listenerObject]; + if (noContext) + target.call(config?.[specialKeys.listeners.bind]?.value ?? this.context.instance, ...arrayUpdate); + else + target(...arrayUpdate); + } else { + let baseMessage = to ? `listener: ${from} \u2014> ${to}` : `listener from ${from}`; + if (parent) { + console.warn(`Deleting ${baseMessage}`, target); + delete parent[to]; + } else + console.error(`Failed to add ${baseMessage}`, target); + } + } + }; + if (listeners2 || root || context) + this.setInitialProperties(listeners2, root, context); + } + }; + _triggers = new WeakMap(); + _queue = new WeakMap(); + _toResolveWith = new WeakMap(); + _initialize = new WeakMap(); + _getAbsolutePath = new WeakMap(); + _getPathInfo = new WeakMap(); + var edgelord_default = Edgelord; + + // ../../core/Graph2.ts + function applyLoader(node, parent, graph = this, tree = graph.__node.tree, properties, tag = node.__node.tag, loader) { + const args = [node, parent, graph, tree, properties, tag]; + if (typeof loader === "object") { + if (loader.init) + loader(...args); + if (loader.connected) + node.__addOnconnected(loader.connect); + if (loader.disconnected) + node.__addOndisconnected(loader.disconnect); + } else if (typeof loader === "function") + loader(...args); + } + function applyLoaders(node, parent, graph = this, tree = graph.__node.tree, properties, tag = node.__node.tag, loaders2 = this.__node.loaders) { + for (const l in loaders2) + applyLoader(node, parent, graph, tree, properties, tag, loaders2[l]); + } + var _parent, _graph, _properties, _options, _applied, _applySetters; + var GraphNode = class { + constructor(properties, parent, graph, options) { + this.__ = Symbol("graphscript"); + this.__node = { + tag: `node${Math.floor(Math.random() * 1e15)}`, + unique: `${Math.random()}`, + ref: this, + flow: new edgelord_default() + }; + __privateAdd(this, _parent, void 0); + __privateAdd(this, _graph, void 0); + __privateAdd(this, _properties, {}); + __privateAdd(this, _options, {}); + __privateAdd(this, _applied, []); + __privateAdd(this, _applySetters, (properties = __privateGet(this, _properties), proxy = __privateGet(this, _properties), ignore = []) => { + const isProxy2 = proxy === true; + let keys = Object.getOwnPropertyNames(properties); + if (isProxy2) { + proxy = properties; + keys = getAllPropertyNames(properties); + } + for (const key of keys) { + if (ignore.includes(key)) + continue; + if (__privateGet(this, _applied).includes(key)) + continue; + __privateGet(this, _applied).push(key); + if (key === "__properties") + Object.defineProperty(this, key, { + get: () => __privateGet(this, _properties), + enumerable: true + }); + else if (key === "__props") { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => { + proxy[key] = value; + __privateGet(this, _applySetters).call(this, value, true); + }, + enumerable: true, + configurable: true + }); + } else { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => proxy[key] = value, + enumerable: true, + configurable: false + }); + } + } + }); + this.____apply = __privateGet(this, _applySetters); + this.__init = (properties, parent = __privateGet(this, _parent), graph = __privateGet(this, _graph), options = __privateGet(this, _options)) => { + __privateSet(this, _parent, parent); + __privateSet(this, _graph, graph); + __privateSet(this, _options, options); + if (properties) { + let orig = properties; + if (typeof properties === "function") { + if (isNativeClass(properties)) { + properties = new properties(); + } else + properties = { + __operator: properties, + __node: { + forward: true, + tag: properties.name + } + }; + } else if (typeof properties === "string") { + if (graph?.get(properties)) { + properties = graph.get(properties); + } + } + if (typeof properties === "object") { + if (parent instanceof Graph && properties instanceof Graph) { + if (properties.__node.loaders) + Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); + if (parent.__node.mapGraphs) { + properties.__node.nodes.forEach((n) => { + parent.set(properties.__node.tag + "." + n.__node.tag, n); + }); + let ondelete = () => { + properties.__node.nodes.forEach((n) => { + parent.__node.nodes.delete(properties.__node.tag + "." + n.__node.tag); + }); + }; + this.__addOndisconnected(ondelete); + } + properties = properties.__node.tree; + } + __privateSet(this, _properties, properties); + if (!properties.__node) + properties.__node = {}; + if (!properties.__node.initial) + this.__node.initial = orig; + if (properties.__props) { + if (typeof properties.__props === "function") + properties.__props = new properties.__props(); + } + if (typeof properties.__node === "string") { + if (graph?.get(properties.__node.tag)) { + properties = graph.get(properties.__node.tag); + } else + properties.__node = {}; + } else if (!properties.__node) + properties.__node = {}; + if (graph) + properties.__node.graph = graph; + if (properties.__operator) { + if (typeof properties.__operator === "string") { + if (graph) { + let n = graph.get(properties.__operator); + if (n) + properties.__operator = n.__operator; + if (!properties.__node.tag && properties.__operator.name) + properties.__node.tag = properties.__operator.name; + } + } + } + if (!properties.__node.tag) { + if (properties.__operator?.name) + properties.__node.tag = properties.__operator.name; + else + properties.__node.tag = `node${Math.floor(Math.random() * 1e15)}`; + } + if (!properties.__parent && parent) + properties.__parent = parent; + if (parent?.__node && !(parent instanceof Graph || properties instanceof Graph)) + properties.__node.tag = parent.__node.tag + "." + properties.__node.tag; + properties.__node = Object.assign(this.__node, properties.__node); + const ogProperties = properties; + __privateGet(this, _applySetters).call(this); + applyLoaders.call(graph, this, parent, graph, graph?.__node?.tree, properties); + __privateGet(this, _applySetters).call(this, void 0, void 0, ["__props"]); + if (properties instanceof Graph) + this.__node.source = properties; + if (typeof options.onInit === "function") + options.onInit(); + if (graph) { + const symbol = (graph.__node.ref ?? this).__; + const monitor = graph.monitor; + this.__node.flow.setInitialProperties(this.__listeners, void 0, { + id: symbol, + instance: this, + monitor, + graph, + bound: this.__node.tag + }); + } else + console.error("No flow manager created for " + this.__node.tag); + } + } + }; + this.__init(properties, parent, graph, options); + } + get __properties() { + return __privateGet(this, _properties); + } + __addOnconnected(callback) { + if (Array.isArray(this.__onconnected)) { + this.__onconnected.push(callback); + } else if (typeof this.__onconnected === "function") { + this.__onconnected = [callback, this.__onconnected]; + } else + this.__onconnected = callback; + } + __addOndisconnected(callback) { + if (Array.isArray(this.__ondisconnected)) { + this.__ondisconnected.push(callback); + } else if (typeof this.__ondisconnected === "function") { + this.__ondisconnected = [callback, this.__ondisconnected]; + } else + this.__ondisconnected = callback; + } + __callConnected(node = this) { + if (typeof this.__onconnected === "function") { + this.__onconnected(this); + } else if (Array.isArray(this.__onconnected)) { + this.__onconnected.forEach((o) => { + o.call(this, this); + }); + } + } + __callDisconnected(node = this) { + if (typeof this.__ondisconnected === "function") + this.__ondisconnected(this); + else if (Array.isArray(this.__ondisconnected)) { + this.__ondisconnected.forEach((o) => { + o.call(this, this); + }); + } + } + }; + _parent = new WeakMap(); + _graph = new WeakMap(); + _properties = new WeakMap(); + _options = new WeakMap(); + _applied = new WeakMap(); + _applySetters = new WeakMap(); + var _init; + var _Graph = class { + constructor(options) { + this.monitor = new src_default({ + keySeparator: ".", + fallbacks: ["__children"] + }); + this.__node = { + tag: `graph${Math.floor(Math.random() * 1e15)}`, + nodes: /* @__PURE__ */ new Map(), + ref: new GraphNode(), + loaders: [ + props_loader_default + ] + }; + this.init = (options) => { + if (options) { + if (options.loaders) { + this.setLoaders(options.loaders); + delete options.loaders; + } + recursivelyAssign(this.__node, options); + if (options.tree) + this.setTree(options.tree); + } + }; + __privateAdd(this, _init, (properties) => { + const node = this.__node.ref; + node.__init(properties, this, this, { + onInit: () => { + this.monitor.set(node.__, node.__properties); + } + }); + return node; + }); + this.setTree = (tree) => { + const hasGraphscriptProperties = Object.keys(tree).find((str) => { + const slice = str.slice(0, 2); + return slice === "__" && str !== "__node"; + }); + if (!hasGraphscriptProperties) + tree = { __children: tree }; + if (!tree.__node) + tree.__node = {}; + this.__node.tree = Object.assign(this.__node.tree ? this.__node.tree : {}, tree); + let cpy = Object.assign({}, tree); + if (cpy.__node) + delete cpy.__node; + let listeners2 = this.recursiveSet(cpy, this, void 0, tree); + if (!tree.__node.tag) + tree.__node.tag = this.__node.tag; + const node = __privateGet(this, _init).call(this, tree); + const children = node.__children; + const copy = Object.assign({}, children); + if (children) + listeners2 = this.recursiveSet(copy, this, void 0, children); + if (node.__listeners) + listeners2[node.__node.tag] = node.__listeners; + this.__node.nodes.forEach((n) => n.__node.flow.start()); + node.__callConnected(); + return cpy; + }; + this.setLoaders = (loaders2, replace) => { + console.error("Setting loaders", loaders2); + if (replace) + this.__node.loaders = loaders2; + else { + if (Array.isArray(this.__node.loaders)) { + if (Array.isArray(loaders2)) + this.__node.loaders = [...this.__node.loaders, ...loaders2]; + else + this.__node.loaders = [...this.__node.loaders, ...Object.values(loaders2)]; + } else + Object.assign(this.__node.loaders, loaders2); + } + return this.__node.loaders; + }; + this.add = (properties, parent) => { + let listeners2 = {}; + if (typeof parent === "string") + parent = this.get(parent); + let instanced; + if (typeof properties === "function") { + if (isNativeClass(properties)) { + if (properties.prototype instanceof GraphNode) { + properties = properties.prototype.constructor(properties, parent, this); + instanced = true; + } else + properties = new properties(); + } else + properties = { __operator: properties }; + } else if (typeof properties === "string") + properties = this.__node.tree[properties]; + if (!instanced) { + properties = Object.assign({}, properties); + } + if (!properties.__node) + properties.__node = {}; + properties.__node.initial = properties; + if (typeof properties === "object" && (!properties?.__node?.tag || !this.get(properties.__node.tag))) { + let node; + if (instanced) + node = properties; + else + node = new GraphNode(properties, parent, this); + this.set(node.__node.tag, node); + this.__node.tree[node.__node.tag] = properties; + if (node.__listeners) { + listeners2[node.__node.tag] = node.__listeners; + } + if (node.__children) { + const children = node.__children; + const copy = Object.assign({}, children); + this.recursiveSet(copy, node, listeners2, children); + } + node.__callConnected(); + return node; + } + return; + }; + this.recursiveSet = (t, parent, listeners2 = {}, origin = t) => { + let keys = Object.getOwnPropertyNames(origin); + for (const key of keys) { + if (key.includes("__")) + continue; + let p = origin[key]; + if (Array.isArray(p)) + continue; + let instanced; + if (typeof p === "function") { + if (isNativeClass(p)) { + p = new p(); + if (p instanceof GraphNode) { + p = p.prototype.constructor(p, parent, this); + instanced = true; + } + } else + p = { __operator: p }; + } else if (typeof p === "string") + p = this.__node.tree[p]; + else if (typeof p === "boolean") + p = this.__node.tree[key]; + if (typeof p === "object") { + if (!p.__node) + p.__node = {}; + if (!p.__node.tag) + p.__node.tag = key; + p.__node.initial = t[key]; + if (this.get(p.__node.tag) && !(parent?.__node && this.get(parent.__node.tag + "." + p.__node.tag)) || parent?.__node && this.get(parent.__node.tag + "." + p.__node.tag)) + continue; + let node; + if (instanced) + node = p; + else + node = new GraphNode(p, parent, this); + this.set(node.__node.tag, node); + t[key] = node; + this.__node.tree[node.__node.tag] = p; + if (node.__listeners) { + listeners2[node.__node.tag] = node.__listeners; + } + if (node.__children) { + const children = node.__children; + const copy = Object.assign({}, children); + this.recursiveSet(copy, node, listeners2, children); + } + let parentNode = parent instanceof _Graph ? parent.__node.ref : parent; + parentNode.__addOnconnected(() => node.__callConnected()); + } + } + return listeners2; + }; + this.remove = (node) => { + if (typeof node === "string") + node = this.get(node); + if (node instanceof GraphNode) { + this.delete(node.__node.tag); + delete this.__node.tree[node.__node.tag]; + this.clearListeners(node); + node.__callDisconnected(); + const recursiveRemove = (t) => { + for (const key in t) { + const node2 = t[key].__node.ref; + this.clearListeners(node2); + this.delete(node2.__node.tag); + delete this.__node.tree[node2.__node.tag]; + this.delete(key); + delete this.__node.tree[key]; + node2.__node.tag = node2.__node.tag.substring(node2.__node.tag.lastIndexOf(".") + 1); + this.clearListeners(node2); + node2.__callDisconnected(); + if (node2.__children) + recursiveRemove(node2.__children); + } + }; + if (node.__children) + recursiveRemove(node.__children); + } + if (node?.__node.tag && node?.__parent) { + node.__parent = void 0; + node.__node.tag = node.__node.tag.substring(node.__node.tag.indexOf(".") + 1); + } + return node; + }; + this.run = (node, ...args) => { + if (typeof node === "string") { + let nd = this.get(node); + if (!nd && node.includes(".")) { + nd = this.get(node.substring(0, node.lastIndexOf("."))); + if (typeof nd?.[node.substring(node.lastIndexOf(".") + 1)] === "function") + return nd[node.substring(node.lastIndexOf(".") + 1)](...args); + } else if (nd?.__operator) + return nd.__operator(...args); + } + if (node?.__operator) { + return node?.__operator(...args); + } + }; + this.clearListeners = (node) => { + this.unsubscribe(node); + this.clear(node); + }; + this.get = (tag, base) => { + if (base instanceof GraphNode) + base = base.__node.tag; + if (tag === this.__node.tag) + return this.__node.ref; + if (base) { + const relFrom = [base, tag].join("."); + const got = this.get(relFrom); + if (got) + return got; + } + return this.__node.nodes.get(tag); + }; + this.set = (tag, node) => { + return this.__node.nodes.set(tag, node); + }; + this.delete = (tag) => { + return this.__node.nodes.delete(tag); + }; + this.getProps = (node, getInitial) => { + if (typeof node === "string") + node = this.get(node); + if (node instanceof GraphNode) { + let cpy; + if (getInitial) + cpy = Object.assign({}, this.__node.tree[node.__node.tag]); + else { + cpy = Object.assign({}, node); + delete cpy.__unsubscribe; + delete cpy.__setOperator; + delete cpy.__node; + delete cpy.__subscribeState; + delete cpy.__subscribe; + } + } + }; + this.subscribe = (from, to, value = true, bound = this.__node.ref) => { + if (typeof from !== "string") + from = from.__node.tag; + if (typeof bound === "string") + bound = this.get(bound); + if (bound) + bound.__node.flow.add(from, to, value); + }; + this.unsubscribe = (node, from, to) => this.clear(from, to, node); + this.clear = (from, to, bound) => { + const nd = typeof bound === "string" ? this.get(bound) : bound; + if (typeof from === "symbol") + return this.__node.flow.remove(from); + let fromString = from instanceof GraphNode ? from.__node.tag : from; + let toString = to instanceof GraphNode ? to.__node.tag : to; + const remove = (n) => { + const flow = n.__node.flow; + toString ? flow.remove(fromString, toString) : flow.clear(fromString); + }; + if (nd) + remove(nd); + else { + remove(this.__node.ref); + this.__node.nodes.forEach(remove); + } + }; + this.activate = (from, value) => this.__node.ref.__node.flow.activate(from, value); + this.setState = (update) => { + for (let key in update) + this.activate(key, update); + }; + this.init(options); + } + }; + var Graph = _Graph; + _init = new WeakMap(); + function recursivelyAssign(target, obj) { + for (const key in obj) { + if (obj[key]?.constructor.name === "Object" && !Array.isArray(obj[key])) { + if (target[key]?.constructor.name === "Object" && !Array.isArray(target[key])) + recursivelyAssign(target[key], obj[key]); + else + target[key] = recursivelyAssign({}, obj[key]); + } else { + target[key] = obj[key]; + } + } + return target; + } + function getAllPropertyNames(obj) { + var props = []; + do { + if (obj.constructor.name === "Object") + props.push(...Object.keys(obj)); + else + Object.getOwnPropertyNames(obj).forEach(function(prop) { + if (props.indexOf(prop) === -1) + props.push(prop); + }); + } while (obj = Object.getPrototypeOf(obj)); + return props; + } + function isNativeClass(thing) { + return typeof thing === "function" && thing.hasOwnProperty("prototype") && !thing.hasOwnProperty("arguments"); + } + + // ../../core/loaders/index.ts + var backprop = (node, parent, graph) => { + if (node.__node.backward && parent instanceof GraphNode) + graph.subscribe(parent.__node.tag, node.__node.tag); + }; + var loop = (node, parent, graph) => { + if (node.__operator && !node.__node.looperSet) { + node.__node.looperSet = true; + if (typeof node.__node.delay === "number") { + let fn = node.__operator; + const delay = (...args) => { + return new Promise((res, rej) => { + setTimeout(async () => { + res(await fn(...args)); + }, node.__node.delay); + }); + }; + node.__operator = delay; + } else if (node.__node.frame === true) { + let fn = node.__operator; + const frame = (...args) => { + return new Promise((res, rej) => { + requestAnimationFrame(async () => { + res(await fn(...args)); + }); + }); + }; + node.__operator = frame; + } + if (typeof node.__node.repeat === "number" || typeof node.__node.recursive === "number") { + let fn = node.__operator; + const repeat = async (...args) => { + let i = node.__node.repeat ? node.__node.repeat : node.__node.recursive; + let result; + let repeater = async (tick, ...inp) => { + while (tick > 0) { + if (node.__node.delay || node.__node.frame) { + fn(...inp).then(async (res) => { + if (node.__node.recursive) { + await repeater(tick, res); + } else + await repeater(tick, ...inp); + }); + break; + } else + result = await fn(...args); + tick--; + } + }; + await repeater(i, ...args); + return result; + }; + node.__operator = repeat; + } + if (node.__node.loop && typeof node.__node.loop === "number") { + let ogFunction = node.__operator; + const looper = function(...args) { + if (!("looping" in node.__node)) + node.__node.looping = true; + if (node.__node.looping) { + const res = ogFunction.call(node, ...args); + setTimeout(() => { + node.__operator(...args); + }, node.__node.loop); + return res; + } + }; + node.__operator = looper; + node.__addOnconnected((node2) => { + if (node2.__node.looping) + node2.__operator(); + }); + let ondelete = (node2) => { + if (node2.__node.looping) + node2.__node.looping = false; + }; + node.__addOndisconnected(ondelete); + } + } + }; + var animate = (node, parent, graph) => { + if (node.__node.animate === true || node.__animation) { + let fn = node.__operator; + const animate2 = (...args) => { + if (!("animating" in node.__node)) + node.__node.animating = true; + if (node.__node.animating) { + if (typeof node.__animation === "function") + node.__animation(...args); + else + fn.call(node, ...args); + requestAnimationFrame(() => { + node.__operator(...args); + }); + } + return true; + }; + node.__operator = animate2; + node.__addOnconnected((node2) => { + if (node2.__node.animating || (!("animating" in node2.__node) || node2.__node.animating) && node2.__animation) + setTimeout(() => { + requestAnimationFrame(node2.__operator); + }, 10); + }); + node.__addOndisconnected((node2) => { + if (node2.__node.animating) + node2.__node.animating = false; + }); + } + }; + var branching = (node, parent, graph) => { + if (typeof node.__node.branch === "object" && node.__operator && !node.__node.branchApplied) { + let fn = node.__operator; + node.__node.branchApplied = true; + node.__operator = (...args) => { + let result = fn(...args); + for (const key in node.__node.branch) { + let triggered = () => { + if (typeof node.__node.branch[key].then === "function") { + node.__node.branch[key].then(result); + } else if (node.__node.branch[key].then instanceof GraphNode && node.__node.branch[key].then.__operator) { + node.__node.branch[key].then.__operator(result); + } else + result = node.__node.branch[key].then; + }; + if (typeof node.__node.branch[key].if === "function") { + if (node.__node.branch[key].if(result)) { + triggered(); + } + } else if (node.__node.branch[key].if === result) { + triggered(); + } + } + return result; + }; + } + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (node.__listeners[key].branch && !node.__listeners[key].branchApplied) { + let fn = node.__listeners[key].callback; + node.__listeners[key].branchApplied = true; + node.__listeners.callback = (ret2) => { + let triggered = () => { + if (typeof node.__listeners[key].branch.then === "function") { + ret2 = node.__listeners[key].branch.then(ret2); + } else if (node.__listeners[key].branch.then instanceof GraphNode && node.__listeners[key].branch.then.__operator) { + ret2 = node.__listeners[key].branch.then.__operator(ret2); + } else + ret2 = node.__listeners[key].branch.then; + }; + if (typeof node.__listeners[key].branch.if === "function") { + if (node.__listeners[key].branch.if(ret2)) { + triggered(); + } + } else if (node.__listeners[key].branch.if === ret2) { + triggered(); + } + return fn(ret2); + }; + } + } + } + } + }; + var triggerListenerOncreate = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (node.__listeners[key].oncreate) { + node.__listeners[key].callback(node.__listeners[key].oncreate); + } + } + } + } + }; + var bindListener = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (typeof node.__listeners[key].binding === "object") { + node.__listeners.callback = node.__listeners.callback.bind(node.__listeners[key].binding); + } + } + } + } + }; + var transformListenerResult = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (typeof node.__listeners[key].transform === "function" && !node.__listeners[key].transformApplied) { + let fn = node.__listeners[key].callback; + node.__listeners[key].transformApplied = true; + node.__listeners.callback = (ret2) => { + ret2 = node.__listeners[key].transform(ret2); + return fn(ret2); + }; + } + } + } + } + }; + var substitute__operator = (node, parent, graph) => { + if (node.post && !node.__operator) { + node.__operator = node.post; + } else if (!node.__operator && typeof node.get == "function") { + node.__operator = node.get; + } + if (!node.get && node.__operator) { + node.get = node.__operator; + } + if (node.aliases) { + node.aliases.forEach((a) => { + graph.set(a, node); + let ondelete = (node2) => { + graph.__node.nodes.delete(a); + }; + node.__addOndisconnected(ondelete); + }); + } + if (typeof graph.__node.tree[node.__node.tag] === "object" && node.get) + graph.__node.tree[node.__node.tag].get = node.get; + }; + var loaders = { + backprop, + loop, + animate, + branching, + triggerListenerOncreate, + bindListener, + transformListenerResult, + substitute__operator + }; + + // ../../services/Service.ts + var Service = class extends Graph { + constructor(options) { + super({ + ...options, + loaders: options?.loaders ? Object.assign({ ...loaders }, options.loaders) : { ...loaders } + }); + this.name = `service${Math.floor(Math.random() * 1e15)}`; + this.addServices = (services) => { + for (const s in services) { + if (typeof services[s] === "function") + services[s] = new services[s](); + if (services[s]?.__node?.loaders) + Object.assign(this.__node.loaders, services[s].__node.loaders); + if (services[s]?.__node?.nodes) { + services[s].__node.nodes.forEach((n, tag) => { + if (!this.get(tag)) { + this.set(tag, n); + } else + this.set(s + "." + tag, n); + }); + this.__node.nodes.forEach((n, k) => { + if (!services[s].__node.nodes.get(k)) + services[s].__node.nodes.set(k, n); + }); + let set2 = this.set; + this.set = (tag, node) => { + services[s].set(tag, node); + return set2(tag, node); + }; + let del = this.delete; + this.delete = (tag) => { + services[s].delete(tag); + return del(tag); + }; + } else if (typeof services[s] === "object") { + this.setTree(services[s]); + } + } + }; + this.handleMethod = (route, method, args) => { + let m = method.toLowerCase(); + let src = this.__node.nodes.get(route); + if (!src) { + src = this.__node.tree[route]; + } + if (src?.[m]) { + if (!(src[m] instanceof Function)) { + if (args) + src[m] = args; + return src[m]; + } else + return src[m](args); + } else + return this.handleServiceMessage({ route, args, method }); + }; + this.transmit = (...args) => { + if (typeof args[0] === "object") { + if (args[0].method) { + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if (args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node) { + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if (this.__node.keepState) { + if (args[0].route) + this.setState({ [args[0].route]: args[0].args }); + if (args[0].node) + this.setState({ [args[0].node]: args[0].args }); + } + return args; + } else + return args; + }; + this.receive = (...args) => { + if (args[0]) { + if (typeof args[0] === "string") { + let substr = args[0].substring(0, 8); + if (substr.includes("{") || substr.includes("[")) { + if (substr.includes("\\")) + args[0] = args[0].replace(/\\/g, ""); + if (args[0][0] === '"') { + args[0] = args[0].substring(1, args[0].length - 1); + } + ; + args[0] = JSON.parse(args[0]); + } + } + } + if (typeof args[0] === "object") { + if (args[0].method) { + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if (args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node) { + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if (this.__node.keepState) { + if (args[0].route) + this.setState({ [args[0].route]: args[0].args }); + if (args[0].node) + this.setState({ [args[0].node]: args[0].args }); + } + return args; + } else + return args; + }; + this.pipe = (source, destination, endpoint, method, callback) => { + if (source instanceof GraphNode) { + if (callback) + return this.subscribe(source, (res) => { + let mod = callback(res); + if (mod !== void 0) + this.transmit({ route: destination, args: mod, method }); + else + this.transmit({ route: destination, args: res, method }, endpoint); + }); + else + return this.subscribe(source, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + } else if (typeof source === "string") + return this.subscribe(source, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + }; + this.pipeOnce = (source, destination, endpoint, method, callback) => { + if (source instanceof GraphNode) { + if (callback) + return source.__node.state.subscribeTriggerOnce(source.__node.unique, (res) => { + let mod = callback(res); + if (mod !== void 0) + this.transmit({ route: destination, args: mod, method }); + else + this.transmit({ route: destination, args: res, method }, endpoint); + }); + else + return this.__node.state.subscribeTriggerOnce(source.__node.unique, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + } else if (typeof source === "string") + return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + }; + this.terminate = (...args) => { + }; + this.isTypedArray = isTypedArray; + this.recursivelyAssign = recursivelyAssign2; + this.spliceTypedArray = spliceTypedArray; + this.ping = () => { + console.log("pinged!"); + return "pong"; + }; + this.echo = (...args) => { + this.transmit(...args); + return args; + }; + if (options?.services) + this.addServices(options.services); + this.setTree(this); + } + handleServiceMessage(message) { + let call; + if (typeof message === "object") { + if (message.route) + call = message.route; + else if (message.node) + call = message.node; + } + if (call) { + if (Array.isArray(message.args)) + return this.run(call, ...message.args); + else + return this.run(call, message.args); + } else + return message; + } + handleGraphNodeCall(route, args) { + if (!route) + return args; + if (args?.args) { + this.handleServiceMessage(args); + } else if (Array.isArray(args)) + return this.run(route, ...args); + else + return this.run(route, args); + } + }; + function isTypedArray(x) { + return ArrayBuffer.isView(x) && Object.prototype.toString.call(x) !== "[object DataView]"; + } + var recursivelyAssign2 = (target, obj) => { + for (const key in obj) { + if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { + if (typeof target[key] === "object" && !Array.isArray(target[key])) + recursivelyAssign2(target[key], obj[key]); + else + target[key] = recursivelyAssign2({}, obj[key]); + } else + target[key] = obj[key]; + } + return target; + }; + function spliceTypedArray(arr, start, end) { + let s = arr.subarray(0, start); + let e; + if (end) { + e = arr.subarray(end + 1); + } + let ta; + if (s.length > 0 || e?.length > 0) + ta = new arr.constructor(s.length + e.length); + if (ta) { + if (s.length > 0) + ta.set(s); + if (e && e.length > 0) + ta.set(e, s.length); + } + return ta; + } + + // ../../services/utils.ts + function parseFunctionFromText(method = "") { + let getFunctionBody = (methodString) => { + return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, "$2$3$4"); + }; + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf("=>") + 1; + if (startindex <= 0) { + startindex = methodString.indexOf("){"); + } + if (startindex <= 0) { + startindex = methodString.indexOf(") {"); + } + return methodString.slice(0, methodString.indexOf("{", startindex) + 1); + }; + let newFuncHead = getFunctionHead(method); + let newFuncBody = getFunctionBody(method); + let newFunc; + if (newFuncHead.includes("function")) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody); + } else { + if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf("{") + 1, newFuncBody.length - 1)); + } else { + try { + newFunc = (0, eval)(newFuncHead + newFuncBody + "}"); + } catch { + } + } + } + return newFunc; + } + var stringifyWithCircularRefs = function() { + const refs = /* @__PURE__ */ new Map(); + const parents = []; + const path = ["this"]; + function clear() { + refs.clear(); + parents.length = 0; + path.length = 1; + } + function updateParents(key, value) { + var idx = parents.length - 1; + var prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value || idx === 0) { + path.push(key); + parents.push(value.pushed); + } else { + while (idx-- >= 0) { + prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value) { + idx += 2; + parents.length = idx; + path.length = idx; + --idx; + parents[idx] = value; + path[idx] = key; + break; + } + } + idx--; + } + } + } + } + function checkCircular(key, value) { + if (value != null) { + if (typeof value === "object") { + if (key) { + updateParents(key, value); + } + let other = refs.get(value); + if (other) { + return "[Circular Reference]" + other; + } else { + refs.set(value, path.join(".")); + } + } + } + return value; + } + return function stringifyWithCircularRefs2(obj, space) { + try { + parents.push(obj); + return JSON.stringify(obj, checkCircular, space); + } finally { + clear(); + } + }; + }(); + if (JSON.stringifyWithCircularRefs === void 0) { + JSON.stringifyWithCircularRefs = stringifyWithCircularRefs; + } + var stringifyFast = function() { + const refs = /* @__PURE__ */ new Map(); + const parents = []; + const path = ["this"]; + function clear() { + refs.clear(); + parents.length = 0; + path.length = 1; + } + function updateParents(key, value) { + var idx = parents.length - 1; + if (parents[idx]) { + var prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value || idx === 0) { + path.push(key); + parents.push(value.pushed); + } else { + while (idx-- >= 0) { + prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value) { + idx += 2; + parents.length = idx; + path.length = idx; + --idx; + parents[idx] = value; + path[idx] = key; + break; + } + } + idx++; + } + } + } + } + } + function checkValues(key, value) { + let val; + if (value != null) { + if (typeof value === "object") { + let c = value.constructor.name; + if (key && c === "Object") { + updateParents(key, value); + } + let other = refs.get(value); + if (other) { + return "[Circular Reference]" + other; + } else { + refs.set(value, path.join(".")); + } + if (c === "Array") { + if (value.length > 20) { + val = value.slice(value.length - 20); + } else + val = value; + } else if (c.includes("Set")) { + val = Array.from(value); + } else if (c !== "Object" && c !== "Number" && c !== "String" && c !== "Boolean") { + val = "instanceof_" + c; + } else if (c === "Object") { + let obj = {}; + for (const prop in value) { + if (value[prop] == null) { + obj[prop] = value[prop]; + } else if (Array.isArray(value[prop])) { + if (value[prop].length > 20) + obj[prop] = value[prop].slice(value[prop].length - 20); + else + obj[prop] = value[prop]; + } else if (value[prop].constructor.name === "Object") { + obj[prop] = {}; + for (const p in value[prop]) { + if (Array.isArray(value[prop][p])) { + if (value[prop][p].length > 20) + obj[prop][p] = value[prop][p].slice(value[prop][p].length - 20); + else + obj[prop][p] = value[prop][p]; + } else { + if (value[prop][p] != null) { + let con = value[prop][p].constructor.name; + if (con.includes("Set")) { + obj[prop][p] = Array.from(value[prop][p]); + } else if (con !== "Number" && con !== "String" && con !== "Boolean") { + obj[prop][p] = "instanceof_" + con; + } else { + obj[prop][p] = value[prop][p]; + } + } else { + obj[prop][p] = value[prop][p]; + } + } + } + } else { + let con = value[prop].constructor.name; + if (con.includes("Set")) { + obj[prop] = Array.from(value[prop]); + } else if (con !== "Number" && con !== "String" && con !== "Boolean") { + obj[prop] = "instanceof_" + con; + } else { + obj[prop] = value[prop]; + } + } + } + val = obj; + } else { + val = value; + } + } else { + val = value; + } + } + return val; + } + return function stringifyFast2(obj, space) { + parents.push(obj); + let res = JSON.stringify(obj, checkValues, space); + clear(); + return res; + }; + }(); + if (JSON.stringifyFast === void 0) { + JSON.stringifyFast = stringifyFast; + } + + // ../../services/unsafe/Unsafe.service.ts + var unsafeRoutes = { + setRoute: function(fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + if (this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__setOperator(fn); + } else { + let node = this.__node.graph.add({ __node: { tag: fnName }, __operator: fn }); + } + return true; + } + return false; + }, + setNode: function(fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + if (this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__setOperator(fn); + } else + this.__node.graph.add({ __node: { tag: fnName }, __operator: fn }); + return true; + } + return false; + }, + setMethod: function(route, fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + if (this.__node.graph.get(route)) { + this.__node.graph.get(route)[fnName] = fn; + } else + this.__node.graph.add({ __node: { tag: fnName, [fnName]: fn } }); + return true; + } + return false; + }, + assignRoute: function(route, source) { + if (this.__node.graph.get(route) && typeof source === "object") { + Object.assign(this.__node.graph.get(route), source); + } + }, + transferClass: (classObj, className) => { + if (typeof classObj === "object") { + let str = classObj.toString(); + let message = { route: "receiveClass", args: [str, className] }; + return message; + } + return false; + }, + receiveClass: function(stringified, className) { + if (typeof stringified === "string") { + if (stringified.indexOf("class") === 0) { + let cls = (0, eval)("(" + stringified + ")"); + let name = className; + if (!name) + name = cls.name; + this.__node.graph[name] = cls; + return true; + } + } + return false; + }, + setGlobal: (key, value) => { + globalThis[key] = value; + return true; + }, + assignGlobalObject: (target, source) => { + if (!globalThis[target]) + return false; + if (typeof source === "object") + Object.assign(globalThis[target], source); + return true; + }, + setValue: function(key, value) { + this.__node.graph[key] = value; + return true; + }, + assignObject: function(target, source) { + if (!this.__node.graph[target]) + return false; + if (typeof source === "object") + Object.assign(this.__node.graph[target], source); + return true; + }, + setGlobalFunction: (fn, fnName) => { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + globalThis[fnName] = fn; + return true; + } + return false; + }, + assignFunctionToGlobalObject: function(globalObjectName, fn, fnName) { + if (!globalThis[globalObjectName]) + return false; + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + this.__node.graph[globalObjectName][fnName] = fn; + return true; + } + return false; + }, + setFunction: function(fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + this.__node.graph[fnName] = fn; + return true; + } + return false; + }, + assignFunctionToObject: function(objectName, fn, fnName) { + if (!this.__node.graph[objectName]) + return false; + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + this.__node.graph[objectName][fnName] = fn; + return true; + } + return false; + } + }; + + // ../../core/loaders/html/DOMElement.js + var DOMElement = class extends HTMLElement { + constructor() { + super(); + __publicField(this, "template", function(self2 = this, props) { + return `
      Custom Fragment Props: ${JSON.stringify(props)}
      `; + }); + __publicField(this, "props", {}); + __publicField(this, "useShadow", false); + __publicField(this, "styles"); + __publicField(this, "oncreate"); + __publicField(this, "onresize"); + __publicField(this, "ondelete"); + __publicField(this, "onchanged"); + __publicField(this, "renderonchanged", false); + __publicField(this, "FRAGMENT"); + __publicField(this, "STYLE"); + __publicField(this, "attachedShadow", false); + __publicField(this, "obsAttributes", ["props", "options", "onchanged", "onresize", "ondelete", "oncreate", "template"]); + __publicField(this, "attributeChangedCallback", (name, old, val) => { + if (name === "onchanged") { + let onchanged = val; + if (typeof onchanged === "string") + onchanged = parseFunctionFromText2(onchanged); + if (typeof onchanged === "function") { + this.onchanged = onchanged; + this.state.data.props = this.props; + this.state.unsubscribeTrigger("props"); + this.state.subscribeTrigger("props", this.onchanged); + let changed = new CustomEvent("changed", { detail: { props: this.props, self: this } }); + this.state.subscribeTrigger("props", () => { + this.dispatchEvent(changed); + }); + } + } else if (name === "onresize") { + let onresize = val; + if (typeof onresize === "string") + onresize = parseFunctionFromText2(onresize); + if (typeof onresize === "function") { + if (this.ONRESIZE) { + try { + window.removeEventListener("resize", this.ONRESIZE); + } catch (err) { + } + } + this.ONRESIZE = (ev) => { + this.onresize(this.props, this); + }; + this.onresize = onresize; + window.addEventListener("resize", this.ONRESIZE); + } + } else if (name === "ondelete") { + let ondelete = val; + if (typeof ondelete === "string") + ondelete = parseFunctionFromText2(ondelete); + if (typeof ondelete === "function") { + this.ondelete = () => { + if (this.ONRESIZE) + window.removeEventListener("resize", this.ONRESIZE); + this.state.unsubscribeTrigger("props"); + if (ondelete) + ondelete(this.props, this); + }; + } + } else if (name === "oncreate") { + let oncreate = val; + if (typeof oncreate === "string") + oncreate = parseFunctionFromText2(oncreate); + if (typeof oncreate === "function") { + this.oncreate = oncreate; + } + } else if (name === "renderonchanged") { + let rpc = val; + if (typeof this.renderonchanged === "number") + this.unsubscribeTrigger(this.renderonchanged); + if (typeof rpc === "string") + rpc = parseFunctionFromText2(rpc); + if (typeof rpc === "function") { + this.renderonchanged = this.state.subscribeTrigger("props", (p) => { + this.render(p); + rpc(this, p); + }); + } else if (rpc != false) + this.renderonchanged = this.state.subscribeTrigger("props", this.render); + } else if (name === "props") { + let newProps = val; + if (typeof newProps === "string") + newProps = JSON.parse(newProps); + Object.assign(this.props, newProps); + this.state.setState({ props: this.props }); + } else if (name === "template") { + let template = val; + this.template = template; + this.render(this.props); + let created = new CustomEvent("created", { detail: { props: this.props } }); + this.dispatchEvent(created); + } else { + let parsed = val; + if (name.includes("eval_")) { + name = name.split("_"); + name.shift(); + name = name.join(); + parsed = parseFunctionFromText2(val); + } else if (typeof val === "string") { + try { + parsed = JSON.parse(val); + } catch (err) { + parsed = val; + } + } + this[name] = parsed; + if (name !== "props" && this.props) + this.props[name] = parsed; + } + }); + __publicField(this, "delete", () => { + this.remove(); + if (typeof this.ondelete === "function") + this.ondelete(this.props); + }); + __publicField(this, "render", (props = this.props) => { + if (typeof this.template === "function") + this.templateResult = this.template(this, props); + else + this.templateResult = this.template; + if (this.styles) + this.templateResult = `${this.templateResult}`; + const t = document.createElement("template"); + if (typeof this.templateResult === "string") + t.innerHTML = this.templateResult; + else if (this.templateResult instanceof HTMLElement) { + if (this.templateResult.parentNode) { + this.templateResult.parentNode.removeChild(this.templateResult); + } + t.appendChild(this.templateResult); + } + const fragment = t.content; + if (this.FRAGMENT) { + if (this.useShadow) { + if (this.STYLE) + this.shadowRoot.removeChild(this.STYLE); + this.FRAGMENT.forEach((c) => { + this.shadowRoot.removeChild(c); + }); + } else + this.FRAGMENT.forEach((c) => { + this.removeChild(c); + }); + } + if (this.useShadow) { + if (!this.attachedShadow) { + this.attachShadow({ mode: "open" }).innerHTML = ""; + this.attachedShadow = true; + } + if (this.styles) { + let style = document.createElement("style"); + style.textContent = this.styles; + this.shadowRoot.prepend(style); + this.STYLE = style; + } + let len = fragment.childNodes.length; + this.shadowRoot.prepend(fragment); + this.FRAGMENT = Array.from(this.shadowRoot.childNodes).slice(0, len); + } else { + let len = fragment.childNodes.length; + this.prepend(fragment); + this.FRAGMENT = Array.from(this.childNodes).slice(0, len); + } + let rendered = new CustomEvent("rendered", { detail: { props: this.props, self: this } }); + this.dispatchEvent(rendered); + if (this.oncreate) + this.oncreate(this, props); + }); + __publicField(this, "state", { + pushToState: {}, + data: {}, + triggers: {}, + setState(updateObj) { + Object.assign(this.pushToState, updateObj); + if (Object.keys(this.triggers).length > 0) { + for (const prop of Object.getOwnPropertyNames(this.triggers)) { + if (this.pushToState[prop]) { + this.data[prop] = this.pushToState[prop]; + delete this.pushToState[prop]; + this.triggers[prop].forEach((obj) => { + obj.onchanged(this.data[prop]); + }); + } + } + } + return this.pushToState; + }, + subscribeTrigger(key, onchanged = (res) => { + }) { + if (key) { + if (!this.triggers[key]) { + this.triggers[key] = []; + } + let l = this.triggers[key].length; + this.triggers[key].push({ idx: l, onchanged }); + return this.triggers[key].length - 1; + } else + return void 0; + }, + unsubscribeTrigger(key, sub) { + let triggers = this.triggers[key]; + if (triggers) { + if (!sub) + delete this.triggers[key]; + else { + let idx = void 0; + let obj = triggers.find((o, i) => { + if (o.idx === sub) { + idx = i; + return true; + } + }); + if (obj) + triggers.splice(idx, 1); + return true; + } + } + }, + subscribeTriggerOnce(key = void 0, onchanged = (value) => { + }) { + let sub; + let changed = (value) => { + onchanged(value); + this.unsubscribeTrigger(key, sub); + }; + sub = this.subscribeTrigger(key, changed); + } + }); + } + get observedAttributes() { + return this.obsAttributes; + } + get obsAttributes() { + return this.obsAttributes; + } + set obsAttributes(att) { + if (typeof att === "string") { + this.obsAttributes.push(att); + } else if (Array.isArray(att)) + this.obsAttributes = att; + } + static get tag() { + return this.name.toLowerCase() + "-"; + } + static addElement(tag = this.tag, cls = this, extend = void 0) { + addCustomElement(cls, tag, extend); + } + connectedCallback() { + if (!this.props) + this.props = {}; + let newProps = this.getAttribute("props"); + if (typeof newProps === "string") + newProps = JSON.parse(newProps); + Object.assign(this.props, newProps); + this.state.setState({ props: this.props }); + Array.from(this.attributes).forEach((att) => { + let name = att.name; + let parsed = att.value; + if (name.includes("eval_") || name.includes("()")) { + if (name.includes("eval_")) + name = name.split("_"); + else if (name.includes("()")) + name = name.substring(0, name.indexOf("(")); + name.shift(); + name = name.join(); + parsed = parseFunctionFromText2(att.value); + } else if (typeof att.value === "string") { + try { + parsed = JSON.parse(att.value); + } catch (err) { + parsed = att.value; + } + } + if (!this[name]) { + Object.defineProperties(this, att, { + value: parsed, + writable: true, + get() { + return this[name]; + }, + set(val) { + this.setAttribute(name, val); + } + }); + } + this[name] = parsed; + if (name !== "props") + this.props[name] = parsed; + this.obsAttributes.push(name); + }); + let resizeevent = new CustomEvent("resized", { detail: { props: this.props, self: this } }); + let changed = new CustomEvent("changed", { detail: { props: this.props, self: this } }); + let deleted = new CustomEvent("deleted", { detail: { props: this.props, self: this } }); + let created = new CustomEvent("created", { detail: { props: this.props, self: this } }); + this.render(this.props); + this.dispatchEvent(created); + this.state.subscribeTrigger("props", () => { + this.dispatchEvent(changed); + }); + if (typeof this.onresize === "function") { + if (this.ONRESIZE) { + try { + window.removeEventListener("resize", this.ONRESIZE); + } catch (err) { + } + } + this.ONRESIZE = (ev) => { + this.onresize(this, this.props); + this.dispatchEvent(resizeevent); + }; + window.addEventListener("resize", this.ONRESIZE); + } + if (typeof this.ondelete === "function") { + let ondelete = this.ondelete; + this.ondelete = (props = this.props) => { + if (this.ONRESIZE) + window.removeEventListener("resize", this.ONRESIZE); + this.state.unsubscribeTrigger("props"); + this.dispatchEvent(deleted); + ondelete(this, props); + }; + } + if (typeof this.onchanged === "function") { + this.state.data.props = this.props; + this.state.subscribeTrigger("props", this.onchanged); + } + if (this.renderonchanged) { + let rpc = this.renderonchanged; + if (typeof this.renderonchanged === "number") + this.unsubscribeTrigger(this.renderonchanged); + if (typeof rpc === "string") + rpc = parseFunctionFromText2(rpc); + if (typeof rpc === "function") { + this.renderonchanged = this.state.subscribeTrigger("props", (p) => { + this.render(p); + rpc(this, p); + }); + } else if (rpc !== false) + this.renderonchanged = this.state.subscribeTrigger("props", this.render); + } + } + get props() { + return this.props; + } + set props(newProps = {}) { + this.setAttribute("props", newProps); + } + get template() { + return this.template; + } + set template(template) { + this.setAttribute("template", template); + } + get render() { + return this.render; + } + get delete() { + return this.delete; + } + get state() { + return this.state; + } + get onchanged() { + return this.onchanged; + } + set onchanged(onchanged) { + this.setAttribute("onchanged", onchanged); + } + get styles() { + return this.styles; + } + set styles(templateStr) { + this.styles = templateStr; + if (this.querySelector("style")) { + this.querySelector("style").innerHTML = templateStr; + } else { + this.render(); + } + } + get renderonchanged() { + return this.renderonchanged; + } + set renderonchanged(onchanged) { + this.setAttribute("renderonchanged", onchanged); + } + get onresize() { + return this.props; + } + set onresize(onresize) { + this.setAttribute("onresize", onresize); + } + get ondelete() { + return this.props; + } + set ondelete(ondelete) { + this.setAttribute("ondelete", ondelete); + } + get oncreate() { + return this.oncreate; + } + set oncreate(oncreate) { + this.setAttribute("oncreated", oncreate); + } + }; + function addCustomElement(cls, tag, extend = null) { + try { + if (extend) { + if (tag) + window.customElements.define(tag, cls, { extends: extend }); + else + window.customElements.define(cls.name.toLowerCase() + "-", cls, { extends: extend }); + } else { + if (tag) + window.customElements.define(tag, cls); + else + window.customElements.define(cls.name.toLowerCase() + "-", cls); + } + } catch (err) { + } + } + function parseFunctionFromText2(method) { + let getFunctionBody = (methodString) => { + return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, "$2$3$4"); + }; + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf(")"); + return methodString.slice(0, methodString.indexOf("{", startindex) + 1); + }; + let newFuncHead = getFunctionHead(method); + let newFuncBody = getFunctionBody(method); + let newFunc; + try { + if (newFuncHead.includes("function")) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody); + } else { + if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf("{") + 1, newFuncBody.length - 1)); + } else { + try { + newFunc = (0, eval)(newFuncHead + newFuncBody + "}"); + } catch (err) { + newFunc = (0, eval)(method); + } + } + } + } catch (err) { + } + return newFunc; + } + + // ../../core/loaders/html/html.loader.ts + var htmlloader = (node, parent, graph, tree, properties, key) => { + if (node.__onresize) { + let onresize = node.__onresize; + node.__onresize = (ev) => { + onresize.call(node, ev, node.__props); + }; + } + if (node.__onremove) { + let ondelete = node.__onremove; + node.__onremove = (element) => { + ondelete.call(node, element); + }; + } + if (node.__onrender) { + let onrender = node.__onrender; + node.__onrender = (element) => onrender.call(node, element); + } + if (node.tagName && !node.__props && !node.__template) { + node.__props = document.createElement(node.tagName); + let keys = Object.getOwnPropertyNames(properties); + for (const k of keys) { + if (k === "style" && typeof properties[k] === "object") { + Object.assign(node.__props.style, properties[k]); + } else + node.__props[k] = properties[k]; + } + } else if (node.__element && !node.__template) { + if (typeof node.__element === "string") + node.__element = document.createElement(node.__element); + if (!(node.__element instanceof HTMLElement)) + return; + node.__props = node.__element; + let keys = Object.getOwnPropertyNames(properties); + for (const k of keys) { + if (k === "style" && typeof properties[k] === "object") { + Object.assign(node.__props.style, properties[k]); + } else + node.__props[k] = properties[k]; + } + } else if (typeof node.__css === "string") { + node.__template = ``; + delete node.__css; + } + if (node.__template) { + if (typeof node.__renderonchanged === "function") { + let renderonchanged = node.__renderonchanged; + node.__renderonchanged = (element) => { + renderonchanged.call(element.node, element); + }; + } + class CustomElement extends DOMElement { + constructor() { + super(...arguments); + this.props = node.props; + this.styles = node.__css; + this.useShadow = node.useShadow; + this.template = node.__template; + this.oncreate = node.__onrender; + this.onresize = node.__onresize; + this.ondelete = node.__onremove; + this.renderonchanged = node.__renderonchanged; + } + } + if (node.__element) + node.tagName = node.__element; + if (!node.tagName) + node.tagName = `element${Math.floor(Math.random() * 1e15)}-`; + CustomElement.addElement(node.tagName); + node.__props = document.createElement(node.tagName); + node.__props.node = node; + let keys = Object.getOwnPropertyNames(properties); + for (const k of keys) { + if (k === "style" && typeof properties[k] === "object") { + Object.assign(node.__props.style, properties[k]); + } else + node.__props[k] = properties[k]; + } + } else if (node.__props instanceof HTMLElement) { + if (node.__onresize) + window.addEventListener("resize", node.__onresize); + } + if (node.__attributes && node.__props instanceof HTMLElement) { + for (const k in node.__attributes) { + if (k === "style" && typeof node.__attribute[k] === "object") { + Object.assign(node.__props.style, node.__attribute[k]); + } + node.__props[k] = node.__attributes[k]; + } + } + if (node.__props instanceof HTMLElement) { + node.__props.id = key; + node.__addOnconnected((n) => { + if (n.__props.parentNode) + n.__props.remove(); + if (n.parentNode) { + if (typeof n.parentNode === "string" && document.getElementById(n.parentNode)) + document.getElementById(n.parentNode).appendChild(n.__props); + else if (n.parentNode instanceof HTMLElement) + n.parentNode.appendChild(n.__props); + } else if (parent.__props instanceof HTMLElement) { + parent.__props.appendChild(node.__props); + } else if (typeof graph.parentNode === "string" && document.getElementById(n.parentNode)) { + document.getElementById(n.parentNode).appendChild(graph.__props); + } else if (graph.parentNode instanceof HTMLElement) { + graph.parentNode.appendChild(node.__props); + } else if (!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement)) + document.body.appendChild(node.__props); + if (node.__onrender && !node.__template) + setTimeout(() => { + node.__onrender(node.__props); + }, 0.01); + }); + node.__addOndisconnected((n) => { + n.__props.remove(); + if (typeof n.__onremove === "function") { + n.__onremove(n.__props); + } + if (n.__onresize) { + window.removeEventListener("resize", n.__onresize); + } + }); + } + }; + + // ../../services/e2ee/E2EE.service.ts + var import_sjcl = __toESM(require_sjcl()); + + // ../../services/http/HTTP.browser.ts + var _HTTPfrontend = class extends Service { + constructor(options, path, fetched) { + super(options); + this.name = "http"; + this.fetchProxied = false; + this.listening = {}; + this.GET = (url2 = "http://localhost:8080/ping", type = "", mimeType) => { + if (type === "json") + mimeType = "application/json"; + return new Promise((resolve, reject) => { + let xhr = _HTTPfrontend.request({ + method: "GET", + url: url2, + responseType: type, + mimeType, + onload: (ev) => { + let data; + if (xhr.responseType === "" || xhr.responseType === "text") + data = xhr.responseText; + else + data = xhr.response; + if (url2 instanceof URL) + url2 = url2.toString(); + this.setState({ [url2]: data }); + resolve(data); + }, + onabort: (er) => { + reject(er); + } + }); + }).catch(console.error); + }; + this.POST = (message, url2 = "http://localhost:8080/echo", type = "", mimeType) => { + if (typeof message === "object" && (type === "json" || type === "text" || !type)) { + message = JSON.stringify(message); + } + if (type === "json") + mimeType = "application/json"; + return new Promise((resolve, reject) => { + let xhr = _HTTPfrontend.request({ + method: "POST", + url: url2, + data: message, + responseType: type, + mimeType, + onload: (ev) => { + let data; + if (xhr.responseType === "" || xhr.responseType === "text") + data = xhr.responseText; + else + data = xhr.response; + if (url2 instanceof URL) + url2 = url2.toString(); + this.setState({ [url2]: data }); + resolve(data); + }, + onabort: (er) => { + reject(er); + } + }); + }).catch(console.error); + }; + this.transmit = (message, url2) => { + let obj = message; + if (typeof obj === "object") { + message = JSON.stringify(obj); + } + if (obj?.method?.toLowerCase() == "get" || message?.toLowerCase() === "get") + return this.GET(url2); + return this.POST(message, url2); + }; + this.transponder = (url2, message, type = "", mimeType) => { + if (typeof message === "object") + message = JSON.stringify(message); + let method = "GET"; + if (message) { + method = "POST"; + } + if (type === "json") + mimeType = "application/json"; + else + return new Promise((resolve, reject) => { + let xhr = _HTTPfrontend.request({ + method, + url: url2, + data: message, + responseType: type, + onload: (ev) => { + let body = xhr.response; + if (typeof body === "string") { + let substr = body.substring(0, 8); + if (substr.includes("{") || substr.includes("[")) { + if (substr.includes("\\")) + body = body.replace(/\\/g, ""); + if (body[0] === '"') { + body = body.substring(1, body.length - 1); + } + ; + body = JSON.parse(body); + } + } + if (typeof body?.method === "string") { + return resolve(this.handleMethod(body.route, body.method, body.args)); + } else if (typeof body?.route === "string") { + return resolve(this.handleServiceMessage(body)); + } else if (typeof body?.node === "string" || body.node instanceof GraphNode) { + return resolve(this.handleGraphNodeCall(body.node, body.args)); + } else + return resolve(body); + }, + onabort: (er) => { + reject(er); + } + }); + }).catch(console.error); + }; + this.listen = (path = "0", fetched = async (clone, args, response) => { + const result = await clone.text(); + const returned = this.receive(result); + this.setState({ [response.url]: returned }); + }) => { + this.listening[path] = {}; + let listenerId = `${path}${Math.floor(Math.random() * 1e15)}`; + this.listening[path][listenerId] = fetched; + if (!this.fetchProxied) { + globalThis.fetch = new Proxy(globalThis.fetch, { + apply(fetch, that, args) { + const result = fetch.apply(that, args); + result.then((response) => { + if (!response.ok) + return; + if (this.listening["0"]) { + for (const key in this.listeners) { + const clone = response.clone(); + this.listening["0"][key](clone, args, response); + } + } else { + for (const key in this.listening) { + if (response.url.includes(key)) { + for (const key2 in this.listening[path]) { + const clone = response.clone(); + this.listening[path][key2](clone, args, response); + } + break; + } + } + } + }).catch((er) => { + console.error(er); + }); + return result; + } + }); + this.fetchProxied = true; + } + return listenerId; + }; + this.stopListening = (path, listener) => { + if (!path && path !== 0) { + for (const key in this.listening) + delete this.listening[key]; + } else { + if (!listener) + delete this.listening[path]; + else + delete this.listening[listener]; + } + }; + this.setTree(this); + this.listen(path, fetched); + } + }; + var HTTPfrontend = _HTTPfrontend; + HTTPfrontend.request = (options) => { + const xhr = new XMLHttpRequest(); + if (options.responseType) + xhr.responseType = options.responseType; + else + options.responseType = "json"; + if (options.mimeType) { + xhr.overrideMimeType(options.mimeType); + } + if (options.onload) + xhr.addEventListener("load", options.onload, false); + if (options.onprogress) + xhr.addEventListener("progress", options.onprogress, false); + if (options.onabort) + xhr.addEventListener("abort", options.onabort, false); + if (options.onloadend) + xhr.addEventListener("loadend", options.onloadend, false); + if (options.onerror) + xhr.addEventListener("error", options.onerror, false); + xhr.open(options.method, options.url, true, options.user, options.pass); + if (!options.onerror) + xhr.onerror = function() { + xhr.abort(); + }; + xhr.send(options.data); + return xhr; + }; + + // ../../services/worker/Worker.service.ts + var import_web_worker = __toESM(require_browser()); + var WorkerService = class extends Service { + constructor(options) { + super(); + this.name = "worker"; + this.workers = {}; + this.threadRot = 0; + this.loadWorkerRoute = (rt, routeKey) => { + if (rt.workerUrl) + rt.url = rt.workerUrl; + if (rt.workerId) + rt.__node.tag = rt.workerId; + if (!rt.__node.tag) + rt.__node.tag = routeKey; + rt._id = rt.__node.tag; + let worker; + if (this.workers[rt._id]) + worker = this.workers[rt._id]; + else if (rt.worker) + worker = rt.worker; + if (!worker) { + worker = this.addWorker(rt); + let ondelete = (rt2) => { + rt2.worker?.terminate(); + }; + rt.__addOndisconnected(ondelete); + } + rt.worker = worker; + if (rt.transferFunctions) { + for (const prop in rt.transferFunctions) { + this.transferFunction(worker, rt.transferFunctions[prop], prop); + } + } + if (rt.transferClasses) { + for (const prop in rt.transferClasses) { + this.transferClass(worker, rt.transferClasses[prop], prop); + } + } + if (worker) { + if (!rt.__operator) { + rt.__operator = (...args) => { + if (rt.callback) { + if (!this.__node.nodes.get(rt.__node.tag)?.__children) + worker.post(rt.callback, args); + else + return worker.run(rt.callback, args); + } else { + if (!this.__node.nodes.get(rt.__node.tag)?.__children) + worker.send(args); + else + return worker.request(args); + } + }; + } + if (rt.init) { + worker.run(rt.init, rt.initArgs, rt.initTransfer); + } + return worker; + } + }; + this.workerloader = { + "workers": (node, parent, graph, tree) => { + let rt = node; + if (!node.parentRoute && (parent?.callback && parent?.worker)) + node.parentRoute = parent?.callback; + if (rt?.worker || rt?.workerId || rt?.workerUrl) { + let worker = this.loadWorkerRoute(rt, rt.__node.tag); + if (worker) { + if (!rt.parentRoute && rt.__parent?.callback) + rt.parentRoute = rt.__parent.callback; + if (rt.__parent && !rt.portId) { + if (typeof rt.__parent === "string") { + if (rt.__node.tag !== rt.__parent && worker._id !== rt.__parent) + rt.portId = this.establishMessageChannel(worker, rt.__parent); + } else if (rt.__node.tag !== rt.__parent?.__node?.tag && worker._id !== rt.__parent.tag) { + rt.portId = this.establishMessageChannel(worker, rt.__parent.worker); + } + } + ; + if (rt.parentRoute) { + if (!rt.stopped) { + if (typeof rt.__parent === "string" && rt.__parent === worker._id) { + worker.run("subscribe", [rt.parentRoute, void 0, rt.callback]); + } else if (rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag) { + worker.run("subscribe", [rt.parentRoute, void 0, rt.callback]); + } else + worker.run("subscribeToWorker", [rt.parentRoute, rt.portId, rt.callback, rt.blocking]).then((sub) => { + worker.workerSubs[rt.parentRoute + rt.portId].sub = sub; + }); + } + if (!(typeof rt.__parent === "string" && rt.__parent === worker._id) && !(rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag)) + worker.workerSubs[rt.parentRoute + rt.portId] = { sub: null, route: rt.parentRoute, portId: rt.portId, callback: rt.callback, blocking: rt.blocking }; + } else if (rt.__parent) { + if (typeof rt.__parent === "string") { + if (!rt.stopped) { + if (rt.__parent === worker._id) { + worker.run("subscribe", [rt.__parent, void 0, rt.callback]); + } else + worker.run("subscribeToWorker", [rt.__parent, rt.portId, rt.callback, rt.blocking]).then((sub) => { + worker.workerSubs[rt.__parent + rt.portId].sub = sub; + }); + } + if (!(typeof rt.__parent === "string" && rt.__parent === worker._id)) + worker.workerSubs[rt.__parent + rt.portId] = { sub: null, route: worker._id, portId: rt.portId, callback: rt.callback, blocking: rt.blocking }; + } else if (rt.__parent?.__node?.tag && rt.__parent?.worker) { + if (!rt.stopped) { + if (rt.__node.tag === rt.__parent.__node.tag || worker._id === rt.__parent.__node.tag) { + worker.run("subscribe", [rt.__parent.__node.tag, void 0, rt.callback]); + } else + worker.run("subscribeToWorker", [rt.__parent.__node.tag, rt.portId, rt.callback, rt.blocking]).then((sub) => { + worker.workerSubs[rt.__parent.__node.tag + rt.portId].sub = sub; + }); + } + if (!(rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag)) + worker.workerSubs[rt.__parent.__node.tag + rt.portId] = { sub: null, route: rt.__parent.__node.tag, portId: rt.portId, callback: rt.callback, blocking: rt.blocking }; + } + } + } + } else if (rt.__parent && rt.parentRoute) { + if (typeof rt.__parent === "string" && tree[rt.__parent]?.worker) { + tree[rt.__parent].worker.subscribe(rt.parentRoute, rt.__operator, rt.blocking); + } else if (rt.__parent?.worker) { + rt.__parent.worker.subscribe(rt.parentRoute, rt.__operator, rt.blocking); + } + } + return rt; + } + }; + this.addDefaultMessageListener = () => { + globalThis.onmessage = (ev) => { + let result = this.receive(ev.data); + if (this.__node.keepState) + this.setState({ [this.name]: result }); + }; + }; + this.postMessage = (message, target, transfer) => { + if (this.workers[target]) { + this.workers[target].send(message, transfer); + } else { + globalThis.postMessage(message, target, transfer); + } + }; + this.addWorker = (options) => { + let worker; + if (!options._id) + options._id = `worker${Math.floor(Math.random() * 1e15)}`; + if (options.url) + worker = new import_web_worker.default(options.url); + else if (options.port) { + worker = options.port; + } else if (this.workers[options._id]) { + if (this.workers[options._id].port) + worker = this.workers[options._id].port; + else + worker = this.workers[options._id].worker; + } + if (!worker) + return; + let send = (message, transfer) => { + return this.transmit(message, worker, transfer); + }; + let post = (route, args, transfer, method) => { + let message = { + route, + args + }; + if (method) + message.method = method; + return this.transmit(message, worker, transfer); + }; + let run = (route, args, transfer, method) => { + return new Promise((res, rej) => { + let callbackId = Math.random(); + let req = { route: "runRequest", args: [{ route, args }, options._id, callbackId] }; + if (method) + req.args[0].method = method; + let onmessage = (ev) => { + if (typeof ev.data === "object") { + if (ev.data.callbackId === callbackId) { + worker.removeEventListener("message", onmessage); + res(ev.data.args); + } + } + }; + worker.addEventListener("message", onmessage); + this.transmit(req, worker, transfer); + }); + }; + let request = (message, transfer, method) => { + return new Promise((res, rej) => { + let callbackId = Math.random(); + let req = { route: "runRequest", args: [message, options._id, callbackId] }; + if (method) + req.method = method; + let onmessage = (ev) => { + if (typeof ev.data === "object") { + if (ev.data.callbackId === callbackId) { + worker.removeEventListener("message", onmessage); + res(ev.data.args); + } + } + }; + worker.addEventListener("message", onmessage); + this.transmit(req, worker, transfer); + }); + }; + let workerSubs = {}; + let subscribe = (route, callback, blocking) => { + return this.subscribeToWorker(route, options._id, callback, blocking); + }; + let unsubscribe = (route, sub) => { + return run("unsubscribe", [route, sub]); + }; + let start = async (route, portId, callback, blocking) => { + if (route) + await run("subscribeToWorker", [route, portId, callback, blocking]).then((sub) => { + if (sub) + workerSubs[route + portId] = { sub, route, portId, callback, blocking }; + }); + else + for (const key in workerSubs) { + if (typeof workerSubs[key].sub !== "number") + await run("subscribeToWorker", [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].callback, workerSubs[key].blocking]).then((sub) => { + workerSubs[key].sub = sub; + }); + } + return true; + }; + let stop = async (route, portId) => { + if (route && portId && workerSubs[route + portId]) { + await run("unsubscribe", [route, workerSubs[route + portId].sub]); + workerSubs[route + portId].sub = false; + } else { + for (const key in workerSubs) { + if (typeof workerSubs[key].sub === "number") { + await run("unpipeWorkers", [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]); + } + workerSubs[key].sub = false; + } + } + return true; + }; + let terminate = () => { + for (const key in workerSubs) { + if (typeof workerSubs[key].sub === "number") { + run("unpipeWorkers", [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]); + } + workerSubs[key].sub = false; + } + return this.terminate(options._id); + }; + if (!options.onmessage) + options.onmessage = (ev) => { + this.receive(ev.data); + this.setState({ [options._id]: ev.data }); + }; + if (!options.onerror) { + options.onerror = (ev) => { + console.error(ev.data); + }; + } + worker.onmessage = options.onmessage; + worker.onerror = options.onerror; + this.workers[options._id] = { + worker, + send, + post, + run, + request, + subscribe, + unsubscribe, + terminate, + start, + stop, + postMessage: worker.postMessage, + workerSubs, + graph: this, + ...options + }; + return this.workers[options._id]; + }; + this.toObjectURL = (scriptTemplate) => { + let blob = new Blob([scriptTemplate], { type: "text/javascript" }); + return URL.createObjectURL(blob); + }; + this.transmit = (message, worker, transfer) => { + if (!transfer) { + transfer = this.getTransferable(message); + } + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) { + worker.postMessage(message, transfer); + } else if (typeof worker === "string") { + if (this.workers[worker]) { + if (this.workers[worker].port) + this.workers[worker].port.postMessage(message, transfer); + else if (this.workers[worker].worker) + this.workers[worker].worker.postMessage(message, transfer); + } + } else { + let keys = Object.keys(this.workers); + this.workers[keys[this.threadRot]].worker.postMessage(message, transfer); + this.threadRot++; + if (this.threadRot === keys.length) + this.threadRot = 0; + } + return message; + }; + this.terminate = (worker) => { + let onclose; + if (typeof worker === "string") { + let obj = this.workers[worker]; + if (obj) { + delete this.workers[worker]; + worker = obj.worker; + if (obj.onclose) + onclose = obj.onclose; + } + } + if (worker instanceof import_web_worker.default) { + worker.terminate(); + if (onclose) + onclose(worker); + return true; + } + if (worker instanceof MessagePort) { + worker.close(); + if (onclose) + onclose(worker); + return true; + } + return false; + }; + this.establishMessageChannel = (worker, worker2) => { + let workerId; + if (typeof worker === "string") { + workerId = worker; + if (this.workers[worker]) { + if (this.workers[worker].port) + worker = this.workers[worker].port; + else + worker2 = this.workers[worker].worker; + } + } else if (worker?.worker) { + worker = worker.worker; + } + if (typeof worker2 === "string") { + if (this.workers[worker2]) { + if (this.workers[worker2].port) + worker2 = this.workers[worker2].port; + else + worker2 = this.workers[worker2].worker; + } + } else if (worker2?.worker) { + worker2 = worker2.worker; + } + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) { + let channel = new MessageChannel(); + let portId = `port${Math.floor(Math.random() * 1e15)}`; + worker.postMessage({ route: "addWorker", args: { port: channel.port1, _id: portId } }, [channel.port1]); + if (worker2 instanceof import_web_worker.default || worker2 instanceof MessagePort) { + worker2.postMessage({ route: "addWorker", args: { port: channel.port2, _id: portId } }, [channel.port2]); + } else if (workerId && this.workers[workerId]) { + channel.port2.onmessage = this.workers[workerId].onmessage; + this.workers[workerId].port = channel.port2; + } + return portId; + } + return false; + }; + this.request = (message, workerId, transfer, method) => { + let worker = this.workers[workerId].worker; + return new Promise((res, rej) => { + let callbackId = Math.random(); + let req = { route: "runRequest", args: [message, callbackId] }; + if (method) + req.method = method; + let onmessage = (ev) => { + if (typeof ev.data === "object") { + if (ev.data.callbackId === callbackId) { + worker.removeEventListener("message", onmessage); + res(ev.data.args); + } + } + }; + worker.addEventListener("message", onmessage); + this.transmit(req, worker, transfer); + }); + }; + this.runRequest = (message, worker, callbackId) => { + let res = this.receive(message); + if (typeof worker === "string" && this.workers[worker]) { + if (this.workers[worker].port) + worker = this.workers[worker].port; + else + worker = this.workers[worker].worker; + } + if (res instanceof Promise) { + res.then((r) => { + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) + worker.postMessage({ args: r, callbackId }); + else if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) + globalThis.postMessage({ args: r, callbackId }); + }); + } else { + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) + worker.postMessage({ args: res, callbackId }); + else if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) + globalThis.postMessage({ args: res, callbackId }); + } + return res; + }; + this.subscribeWorker = (route, worker, blocking, key, subInput) => { + let callback; + if (blocking) { + let blocked = false; + callback = (res) => { + if (!blocked) { + blocked = true; + if (res instanceof Promise) { + res.then((r) => { + if (worker?.run) + worker.run("triggerSubscription", [route, worker._id, r]).then((ret2) => { + blocked = false; + }); + }); + } else { + if (worker?.run) + worker.run("triggerSubscription", [route, worker._id, res]).then((ret2) => { + blocked = false; + }); + } + } + }; + } else { + callback = (res) => { + if (res instanceof Promise) { + res.then((r) => { + if (worker?.postMessage) + worker.postMessage({ args: r, callbackId: route }); + else if (globalThis.postMessage) + globalThis.postMessage({ args: r, callbackId: route }); + }); + } else { + if (worker?.postMessage) + worker.postMessage({ args: res, callbackId: route }); + else if (globalThis.postMessage) + globalThis.postMessage({ args: res, callbackId: route }); + } + }; + } + if (!blocking && worker?.port) { + worker = worker.port; + } else if (!blocking && worker?.worker) { + worker = worker.worker; + } else if (typeof worker === "string" && this.workers[worker]) { + if (blocking) + worker = this.workers[worker]; + else if (this.workers[worker].port) + worker = this.workers[worker].port; + else + worker = this.workers[worker].worker; + } + return this.subscribe(route, callback, key, subInput); + }; + this.subscribeToWorker = (route, workerId, callback, blocking, key, subInput) => { + if (typeof workerId === "string" && this.workers[workerId]) { + this.__node.state.subscribeTrigger(workerId, (res) => { + if (res?.callbackId === route) { + if (!callback) + this.setState({ [workerId]: res.args }); + else if (typeof callback === "string") { + this.run(callback, res.args); + } else + callback(res.args); + } + }); + return this.workers[workerId].run("subscribeWorker", [route, workerId, blocking, key, subInput]); + } + }; + this.triggerSubscription = async (route, workerId, result) => { + if (this.__node.state.triggers[workerId]) + for (let i = 0; i < this.__node.state.triggers[workerId].length; i++) { + await this.__node.state.triggers[workerId][i].onchange({ args: result, callbackId: route }); + } + return true; + }; + this.pipeWorkers = (sourceWorker, listenerWorker, sourceRoute, listenerRoute, portId, blocking) => { + if (typeof sourceWorker === "string") + sourceWorker = this.workers[sourceWorker]; + if (typeof listenerWorker === "string") + listenerWorker = this.workers[listenerWorker]; + if (!portId) { + portId = this.establishMessageChannel(sourceWorker.worker, listenerWorker.worker); + } + return listenerWorker.run("subscribeToWorker", [sourceRoute, portId, listenerRoute, blocking]); + }; + this.unpipeWorkers = (sourceRoute, sourceWorker, sub) => { + if (typeof sourceWorker === "string") + sourceWorker = this.workers[sourceWorker]; + if (sourceWorker) + return sourceWorker.run("unsubscribe", [sourceRoute, sub]); + }; + this.connections = { + workers: this.workers + }; + if (options?.services) + this.addServices(options.services); + this.setLoaders(this.workerloader); + if (options) + this.init(options); + if (typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope) { + this.addDefaultMessageListener(); + } + } + getTransferable(message) { + let transfer; + if (typeof message === "object") { + if (message.args) { + if (message.args?.constructor?.name === "Object") { + for (const key in message.args) { + if (ArrayBuffer.isView(message.args[key])) { + if (!transfer) + transfer = [message.args[key].buffer]; + else + transfer.push(message.args[key].buffer); + } else if (message.args[key]?.constructor?.name === "ArrayBuffer") { + if (!transfer) + transfer = [message.args[key]]; + else + transfer.push(message.args[key]); + } + } + } else if (Array.isArray(message.args) && message.args.length < 11) { + message.args.forEach((arg) => { + if (ArrayBuffer.isView(arg)) { + transfer = [arg.buffer]; + } else if (arg?.constructor?.name === "ArrayBuffer") + transfer = [arg]; + }); + } else if (ArrayBuffer.isView(message.args)) { + transfer = [message.args.buffer]; + } else if (message.args?.constructor?.name === "ArrayBuffer") { + transfer = [message]; + } + } else if (message?.constructor?.name === "Object") { + for (const key in message) { + if (ArrayBuffer.isView(message[key])) { + if (!transfer) + transfer = [message[key].buffer]; + else + transfer.push(message[key].buffer); + } else if (message[key]?.constructor?.name === "ArrayBuffer") { + if (!transfer) + transfer = [message[key]]; + else + transfer.push(message[key]); + } + } + } else if (Array.isArray(message) && message.length < 11) { + message.forEach((arg) => { + if (ArrayBuffer.isView(arg)) { + transfer = [arg.buffer]; + } else if (arg.constructor?.name === "ArrayBuffer") + transfer = [arg]; + }); + } else if (ArrayBuffer.isView(message)) { + transfer = [message.buffer]; + } else if (message.constructor?.name === "ArrayBuffer") { + transfer = [message]; + } + } + return transfer; + } + transferFunction(worker, fn, fnName) { + if (!fnName) + fnName = fn.name; + return worker.request({ + route: "setRoute", + args: [ + fn.toString(), + fnName + ] + }); + } + transferClass(worker, cls, className) { + if (!className) + className = cls.name; + return worker.request({ + route: "receiveClass", + args: [ + cls.toString(), + className + ] + }); + } + }; + + // ../../services/worker/ProxyListener.ts + var mouseEventHandler = makeSendPropertiesHandler([ + "ctrlKey", + "metaKey", + "shiftKey", + "button", + "pointerType", + "clientX", + "clientY", + "pageX", + "pageY" + ]); + var wheelEventHandlerImpl = makeSendPropertiesHandler([ + "deltaX", + "deltaY" + ]); + var keydownEventHandler = makeSendPropertiesHandler([ + "ctrlKey", + "metaKey", + "shiftKey", + "keyCode" + ]); + function wheelEventHandler(event, sendFn) { + event.preventDefault(); + wheelEventHandlerImpl(event, sendFn); + } + function preventDefaultHandler(event) { + event.preventDefault(); + } + function copyProperties(src, properties, dst) { + for (const name of properties) { + dst[name] = src[name]; + } + } + function makeSendPropertiesHandler(properties) { + return function sendProperties(event, sendFn) { + const data = { type: event.type }; + copyProperties(event, properties, data); + sendFn(data); + }; + } + function touchEventHandler(event, sendFn) { + const touches = []; + const data = { type: event.type, touches }; + for (let i = 0; i < event.touches.length; ++i) { + const touch = event.touches[i]; + touches.push({ + pageX: touch.pageX, + pageY: touch.pageY + }); + } + sendFn(data); + } + var orbitKeys = { + "37": true, + "38": true, + "39": true, + "40": true + }; + function filteredKeydownEventHandler(event, sendFn) { + const { keyCode } = event; + if (orbitKeys[keyCode]) { + event.preventDefault(); + keydownEventHandler(event, sendFn); + } + } + var eventHandlers = { + contextmenu: preventDefaultHandler, + mousedown: mouseEventHandler, + mousemove: mouseEventHandler, + mouseup: mouseEventHandler, + pointerdown: mouseEventHandler, + pointermove: mouseEventHandler, + pointerup: mouseEventHandler, + touchstart: touchEventHandler, + touchmove: touchEventHandler, + touchend: touchEventHandler, + wheel: wheelEventHandler, + keydown: filteredKeydownEventHandler + }; + function initProxyElement(element, worker, id) { + if (!id) + id = "proxy" + Math.floor(Math.random() * 1e15); + const sendEvent = (data) => { + if (!worker) { + handleProxyEvent(data, id); + } else + worker.postMessage({ route: "handleProxyEvent", args: [data, id] }); + }; + let entries = Object.entries(eventHandlers); + for (const [eventName, handler2] of entries) { + element.addEventListener(eventName, function(event) { + handler2(event, sendEvent); + }); + } + const sendSize = () => { + const rect = element.getBoundingClientRect(); + sendEvent({ + type: "resize", + left: rect.left, + top: rect.top, + width: element.clientWidth, + height: element.clientHeight + }); + }; + sendSize(); + globalThis.addEventListener("resize", sendSize); + return id; + } + var EventDispatcher = class { + addEventListener(type, listener) { + if (this.__listeners === void 0) + this.__listeners = {}; + const listeners2 = this.__listeners; + if (listeners2[type] === void 0) { + listeners2[type] = []; + } + if (listeners2[type].indexOf(listener) === -1) { + listeners2[type].push(listener); + } + } + hasEventListener(type, listener) { + if (this.__listeners === void 0) + return false; + const listeners2 = this.__listeners; + return listeners2[type] !== void 0 && listeners2[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + if (this.__listeners === void 0) + return; + const listeners2 = this.__listeners; + const listenerArray = listeners2[type]; + if (listenerArray !== void 0) { + const index = listenerArray.indexOf(listener); + if (index !== -1) { + listenerArray.splice(index, 1); + } + } + } + dispatchEvent(event, target) { + if (this.__listeners === void 0) + return; + const listeners2 = this.__listeners; + const listenerArray = listeners2[event.type]; + if (listenerArray !== void 0) { + if (!target) + event.target = this; + else + event.target = target; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length; i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } + }; + function noop() { + } + var ElementProxyReceiver = class extends EventDispatcher { + constructor() { + super(); + this.__listeners = {}; + this.style = {}; + this.setPointerCapture = () => { + }; + this.releasePointerCapture = () => { + }; + this.getBoundingClientRect = () => { + return { + left: this.left, + top: this.top, + width: this.width, + height: this.height, + right: this.left + this.width, + bottom: this.top + this.height + }; + }; + this.handleEvent = (data) => { + if (data.type === "resize") { + this.left = data.left; + this.top = data.top; + this.width = data.width; + this.height = data.height; + if (typeof this.proxied === "object") { + this.proxied.style.width = this.width + "px"; + this.proxied.style.height = this.height + "px"; + this.proxied.clientWidth = this.width; + this.proxied.clientHeight = this.height; + } + } + data.preventDefault = noop; + data.stopPropagation = noop; + this.dispatchEvent(data, this.proxied); + }; + this.style = {}; + } + get clientWidth() { + return this.width; + } + get clientHeight() { + return this.height; + } + focus() { + } + }; + var ProxyManager = class { + constructor() { + this.targets = {}; + this.makeProxy = (id, addTo = void 0) => { + if (!id) + id = `proxyReceiver${Math.floor(Math.random() * 1e15)}`; + let proxy; + if (this.targets[id]) + proxy = this.targets[id]; + else { + proxy = new ElementProxyReceiver(); + this.targets[id] = proxy; + } + if (typeof addTo === "object") { + addTo.proxy = proxy; + proxy.proxied = addTo; + if (typeof WorkerGlobalScope !== "undefined") + addTo.style = proxy.style; + if (proxy.width) { + addTo.style.width = proxy.width + "px"; + addTo.clientWidth = proxy.width; + } + if (proxy.height) { + addTo.style.height = proxy.height + "px"; + addTo.clientHeight = proxy.height; + } + addTo.setPointerCapture = proxy.setPointerCapture.bind(proxy); + addTo.releasePointerCapture = proxy.releasePointerCapture.bind(proxy); + addTo.getBoundingClientRect = proxy.getBoundingClientRect.bind(proxy); + addTo.addEventListener = proxy.addEventListener.bind(proxy); + addTo.removeEventListener = proxy.removeEventListener.bind(proxy); + addTo.handleEvent = proxy.handleEvent.bind(proxy); + addTo.dispatchEvent = proxy.dispatchEvent.bind(proxy); + addTo.focus = proxy.focus.bind(proxy); + } + }; + this.getProxy = (id) => { + return this.targets[id]; + }; + this.handleEvent = (data, id) => { + if (!this.targets[id]) + this.makeProxy(id); + if (this.targets[id]) { + this.targets[id].handleEvent(data); + return true; + } + return void 0; + }; + if (!globalThis.document) + globalThis.document = {}; + } + }; + function makeProxy(id, elm) { + if (this?.__node?.graph) { + if (!this.__node.graph.ProxyManager) + this.__node.graph.ProxyManager = new ProxyManager(); + this.__node.graph.ProxyManager.makeProxy(id, elm); + } else { + if (!globalThis.ProxyManager) + globalThis.ProxyManager = new ProxyManager(); + globalThis.ProxyManager.makeProxy(id, elm); + } + return id; + } + function handleProxyEvent(data, id) { + if (this?.__node?.graph) { + if (!this.__node.graph.ProxyManager) + this.__node.graph.ProxyManager = new ProxyManager(); + if (this.__node.graph.ProxyManager.handleEvent(data, id)) + return data; + } else { + if (!globalThis.ProxyManager) + globalThis.ProxyManager = new ProxyManager(); + if (globalThis.ProxyManager.handleEvent(data, id)) + return data; + } + } + var proxyElementWorkerRoutes = { + initProxyElement, + makeProxy, + handleProxyEvent + }; + + // ../../services/worker/WorkerCanvas.ts + function Renderer(options) { + if (options.worker) { + let worker = options.worker; + let route = options.route; + if (worker instanceof Blob || typeof worker === "string") { + worker = new Worker(worker); + } + delete options.worker; + delete options.route; + return transferCanvas(worker, options, route); + } else { + initProxyElement(options.canvas, void 0, options._id); + return setupCanvas(options); + } + } + function transferCanvas(worker, options, route) { + if (!options) + return void 0; + if (!options._id) + options._id = `canvas${Math.floor(Math.random() * 1e15)}`; + let offscreen = options.canvas.transferControlToOffscreen(); + if (!options.width) + options.width = options.canvas.clientWidth; + if (!options.height) + options.height = options.canvas.clientHeight; + let message = { route: route ? route : "setupCanvas", args: { + ...options, + canvas: offscreen + } }; + if (this?.__node?.graph) + this.__node.graph.run("initProxyElement", options.canvas, worker, options._id); + else + initProxyElement(options.canvas, worker, options._id); + if (options.draw) { + if (typeof options.draw === "function") + message.args.draw = options.draw.toString(); + else + message.args.draw = options.draw; + } + if (options.update) { + if (typeof options.update === "function") + message.args.update = options.update.toString(); + else + message.args.update = options.update; + } + if (options.init) { + if (typeof options.init === "function") + message.args.init = options.init.toString(); + else + message.args.init = options.init; + } + if (options.clear) { + if (typeof options.clear === "function") + message.args.clear = options.clear.toString(); + else + message.args.clear = options.clear; + } + let transfer = [offscreen]; + if (options.transfer) { + transfer.push(...options.transfer); + delete options.transfer; + } + worker.postMessage(message, transfer); + const canvascontrols = { + _id: options._id, + width: options.width, + height: options.height, + worker, + draw: (props) => { + worker.postMessage({ route: "drawFrame", args: [props, options._id] }); + }, + update: (props) => { + worker.postMessage({ route: "updateCanvas", args: [props, options._id] }); + }, + clear: () => { + worker.postMessage({ route: "clearCanvas", args: options._id }); + }, + init: () => { + worker.postMessage({ route: "initCanvas", args: options._id }); + }, + stop: () => { + worker.postMessage({ route: "stopAnim", args: options._id }); + }, + start: () => { + worker.postMessage({ route: "startAnim", args: options._id }); + }, + set: (newDrawProps) => { + worker.postMessage({ route: "setDraw", args: [newDrawProps, options._id] }); + }, + terminate: () => { + worker.terminate(); + } + }; + return canvascontrols; + } + function setDraw(settings, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (_id) + canvasopts = this.__node.graph.CANVASES?.[settings._id]; + else if (settings._id) + canvasopts = this.__node.graph.CANVASES?.[settings._id]; + else + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + } else { + if (_id) + canvasopts = globalThis.CANVASES?.[settings._id]; + else if (settings._id) + canvasopts = globalThis.CANVASES?.[settings._id]; + else + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + } + if (canvasopts) { + if (settings.canvas) { + canvasopts.canvas = settings.canvas; + if (this?.__node?.graph) + this.__node.graph.run("makeProxy", canvasopts._id, canvasopts.canvas); + else + proxyElementWorkerRoutes.makeProxy(canvasopts._id, canvasopts.canvas); + } + if (typeof settings.context === "string") + canvasopts.context = canvasopts.canvas.getContext(settings.context); + else if (settings.context) + canvasopts.context = settings.context; + if (settings.width) + canvasopts.canvas.width = settings.width; + if (settings.height) + canvasopts.canvas.height = settings.height; + if (typeof settings.draw === "string") + settings.draw = parseFunctionFromText3(settings.draw); + if (typeof settings.draw === "function") { + canvasopts.draw = settings.draw; + } + if (typeof settings.update === "string") + settings.update = parseFunctionFromText3(settings.update); + if (typeof settings.update === "function") { + canvasopts.update = settings.update; + } + if (typeof settings.init === "string") + settings.init = parseFunctionFromText3(settings.init); + if (typeof settings.init === "function") { + canvasopts.init = settings.init; + } + if (typeof settings.clear === "string") + settings.clear = parseFunctionFromText3(settings.clear); + if (typeof settings.clear === "function") { + canvasopts.clear = settings.clear; + } + return settings._id; + } + return void 0; + } + function setupCanvas(options) { + if (this?.__node?.graph) { + if (!this.__node.graph.CANVASES) + this.__node.graph.CANVASES = {}; + } else if (!globalThis.CANVASES) + globalThis.CANVASES = {}; + let canvasOptions = options; + options._id ? canvasOptions._id = options._id : canvasOptions._id = `canvas${Math.floor(Math.random() * 1e15)}`; + typeof options.context === "string" ? canvasOptions.context = options.canvas.getContext(options.context) : canvasOptions.context = options.context; + "animating" in options ? canvasOptions.animating = options.animating : canvasOptions.animating = true; + if (this?.__node?.graph?.CANVASES[canvasOptions._id]) { + this.__node.graph.run("setDraw", canvasOptions); + } else if (globalThis.CANVASES?.[canvasOptions._id]) { + setDraw(canvasOptions); + } else { + if (this?.__node?.graph) + canvasOptions.graph = this.__node.graph; + if (this?.__node?.graph) + this.__node.graph.CANVASES[canvasOptions._id] = canvasOptions; + else + globalThis.CANVASES[canvasOptions._id] = canvasOptions; + if (this?.__node?.graph) + this.__node.graph.run("makeProxy", canvasOptions._id, canvasOptions.canvas); + else + proxyElementWorkerRoutes.makeProxy(canvasOptions._id, canvasOptions.canvas); + if (options.width) + canvasOptions.canvas.width = options.width; + if (options.height) + canvasOptions.canvas.height = options.height; + if (typeof canvasOptions.draw === "string") { + canvasOptions.draw = parseFunctionFromText3(canvasOptions.draw); + } else if (typeof canvasOptions.draw === "function") { + canvasOptions.draw = canvasOptions.draw; + } + if (typeof canvasOptions.update === "string") { + canvasOptions.update = parseFunctionFromText3(canvasOptions.update); + } else if (typeof canvasOptions.update === "function") { + canvasOptions.update = canvasOptions.update; + } + if (typeof canvasOptions.init === "string") { + canvasOptions.init = parseFunctionFromText3(canvasOptions.init); + } else if (typeof canvasOptions.init === "function") { + canvasOptions.init = canvasOptions.init; + } + if (typeof canvasOptions.clear === "string") { + canvasOptions.clear = parseFunctionFromText3(canvasOptions.clear); + } else if (typeof canvasOptions.clear === "function") { + canvasOptions.clear = canvasOptions.clear; + } + if (typeof canvasOptions.init === "function") + canvasOptions.init(canvasOptions, canvasOptions.canvas, canvasOptions.context); + canvasOptions.stop = () => { + stopAnim(canvasOptions._id); + }; + canvasOptions.start = (draw) => { + startAnim(canvasOptions._id, draw); + }; + canvasOptions.set = (settings) => { + setDraw(settings, canvasOptions._id); + }; + if (typeof canvasOptions.draw === "function" && canvasOptions.animating) { + let draw = (s, canvas, context) => { + if (s.animating) { + s.draw(s, canvas, context); + requestAnimationFrame(() => { + draw(s, canvas, context); + }); + } + }; + draw(canvasOptions, canvasOptions.canvas, canvasOptions.context); + } + } + if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) + return canvasOptions._id; + else { + const canvascontrols = { + _id: options._id, + width: options.width, + height: options.height, + draw: (props) => { + drawFrame(props, options._id); + }, + update: (props) => { + updateCanvas(props, options._id); + }, + clear: () => { + clearCanvas(options._id); + }, + init: () => { + initCanvas(options._id); + }, + stop: () => { + stopAnim(options._id); + }, + start: () => { + startAnim(options._id); + }, + set: (newDrawProps) => { + setDraw(newDrawProps, options._id); + }, + terminate: () => { + stopAnim(options._id); + } + }; + return canvascontrols; + } + } + function drawFrame(props, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts) { + if (props) + Object.assign(canvasopts, props); + if (canvasopts.draw) { + canvasopts.draw(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + } + return void 0; + } + function clearCanvas(_id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts?.clear) { + canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + function initCanvas(_id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts?.init) { + canvasopts.init(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + function updateCanvas(input, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts?.update) { + canvasopts.update(canvasopts, canvasopts.canvas, canvasopts.context, input); + return _id; + } + return void 0; + } + function setProps(props, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts) { + Object.assign(canvasopts, props); + if (props.width) + canvasopts.canvas.width = props.width; + if (props.height) + canvasopts.canvas.height = props.height; + return _id; + } + return void 0; + } + function startAnim(_id, draw) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + canvasopts.animating = true; + if (canvasopts && draw) { + if (typeof draw === "string") + draw = parseFunctionFromText3(draw); + if (typeof draw === "function") { + canvasopts.draw = draw; + } + return _id; + } + if (typeof canvasopts?.draw === "function") { + let draw2 = (s, canvas, context) => { + if (s.animating) { + s.draw(s, canvas, context); + requestAnimationFrame(() => { + draw2(s, canvas, context); + }); + } + }; + if (typeof canvasopts.clear === "function") + canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + if (typeof canvasopts.init === "function") + canvasopts.init(canvasopts, canvasopts.canvas, canvasopts.context); + draw2(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + function stopAnim(_id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts) { + canvasopts.animating = false; + if (typeof canvasopts.clear === "function") + canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + var workerCanvasRoutes = { + ...proxyElementWorkerRoutes, + Renderer, + transferCanvas, + setupCanvas, + setDraw, + drawFrame, + clearCanvas, + initCanvas, + updateCanvas, + setProps, + startAnim, + stopAnim + }; + function parseFunctionFromText3(method = "") { + let getFunctionBody = (methodString) => { + return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, "$2$3$4"); + }; + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf("=>") + 1; + if (startindex <= 0) { + startindex = methodString.indexOf("){"); + } + if (startindex <= 0) { + startindex = methodString.indexOf(") {"); + } + return methodString.slice(0, methodString.indexOf("{", startindex) + 1); + }; + let newFuncHead = getFunctionHead(method); + let newFuncBody = getFunctionBody(method); + let newFunc; + if (newFuncHead.includes("function")) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody); + } else { + if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf("{") + 1, newFuncBody.length - 1)); + } else { + try { + newFunc = (0, eval)(newFuncHead + newFuncBody + "}"); + } catch { + } + } + } + return newFunc; + } + + // ../../services/worker/Subprocess.ts + var algorithms = {}; + var loadAlgorithms = (settings) => { + return Object.assign(algorithms, settings); + }; + function createSubprocess(options, inputs) { + let ctx = { + _id: options._id ? options._id : `algorithm${Math.floor(Math.random() * 1e15)}`, + ondata: options.ondata, + run: (data) => { + return ctx.ondata(ctx, data); + } + }; + if (options.structs) + recursivelyAssign3(ctx, JSON.parse(JSON.stringify(options.structs))); + if (inputs) + recursivelyAssign3(ctx, JSON.parse(JSON.stringify(inputs))); + if (options.oncreate) { + ctx.oncreate = options.oncreate; + } + if (ctx.oncreate) { + ctx.oncreate(ctx); + } + return ctx; + } + var recursivelyAssign3 = (target, obj) => { + for (const key in obj) { + if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { + if (typeof target[key] === "object" && !Array.isArray(target[key])) + recursivelyAssign3(target[key], obj[key]); + else + target[key] = recursivelyAssign3({}, obj[key]); + } else + target[key] = obj[key]; + } + return target; + }; + var subprocessRoutes = { + ...unsafeRoutes, + loadAlgorithms, + "initSubprocesses": async function initSubprocesses(subprocesses, service) { + if (!service) + service = this.__node.graph; + if (!service) + return void 0; + for (const p in subprocesses) { + let s = subprocesses[p]; + if (!s.worker && s.url) + s.worker = service.addWorker({ url: s.url }); + if (!s.worker) + continue; + let w = s.worker; + let wpId; + wpId = service.establishMessageChannel(w.worker, s.source?.worker); + if (!s.source) + s.source = service; + if (typeof s.subprocess === "object") { + const p2 = s.subprocess; + if (!p2.name) + continue; + if (typeof p2.oncreate === "function") { + p2.oncreate = p2.oncreate.toString(); + } + if (typeof p2.ondata === "function") { + p2.ondata = p2.ondata.toString(); + } + s.worker.post("addSubprocessTemplate", [ + p2.name, + p2.structs, + p2.oncreate, + p2.ondata, + p2.props + ]); + s.subprocess = p2.name; + } + if (s.init) { + let r = await w.run(s.init, s.initArgs); + s.otherArgs = r; + } + if (s.otherArgs) { + w.run("setValue", ["otherArgsProxy", Array.isArray(s.otherArgs) ? s.otherArgs : [s.otherArgs]]); + } + if (s.pipeTo) { + w.run("setValue", ["routeProxy", s.route]); + w.run("setValue", ["pipeRoute", s.pipeTo.route]); + if (s.url && !s.pipeTo.worker) { + let w2 = service.addWorker({ url: s.url }); + s.pipeTo.portId = service.establishMessageChannel(w.worker, w2.worker); + s.pipeTo.worker = w2; + } + if (s.pipeTo.init) { + s.pipeTo.otherArgs = await s.pipeTo.worker.run(s.pipeTo.init, s.pipeTo.initArgs); + } + w.run("setValue", ["pipePort", s.pipeTo.portId]); + if (s.pipeTo.otherArgs) + w.run("setValue", ["otherPipeArgs", s.pipeTo.otherArgs]); + service.transferFunction(w, function pipeResults(data) { + let inp = data; + if (this.__node.graph.otherArgsProxy) + inp = [data, ...this.__node.graph.otherArgsProxy]; + let r = this.__node.graph.run(this.__node.graph.routeProxy, inp); + if (!s.blocking) + return new Promise((res) => { + if (r instanceof Promise) { + r.then((rr) => { + if (rr !== void 0) { + let args = rr; + if (this.__node.graph.otherPipeArgs) + args = [rr, ...this.__node.graph.otherPipeArgs]; + if (this.workers[this.__node.graph.pipePort]) { + s.blocking = true; + this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute, args).then((result) => { + s.blocking = false; + res(result); + }); + } + } + }); + } else if (r !== void 0) { + let args = r; + if (this.__node.graph.otherPipeArgs) + args = [r, ...this.__node.graph.otherPipeArgs]; + if (this.workers[this.__node.graph.pipePort]) { + s.blocking = true; + this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute, args).then((result) => { + s.blocking = false; + res(result); + }); + } + } + }); + return void 0; + }, s.route + "_pipeResults"); + s.route = s.route + "_pipeResults"; + } else { + w.run("setValue", ["routeProxy", s.route]); + service.transferFunction(w, function routeProxy(data) { + let r; + if (this.__node.graph.otherArgsProxy) + r = this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data, ...this.__node.graph.otherArgsProxy); + else + r = this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data); + if (this.__node.graph.state.triggers[this.__node.graph.routeProxy]) { + if (r instanceof Promise) { + r.then((rr) => { + this.setState({ [this.__node.graph.routeProxy]: rr }); + }); + } else + this.setState({ [this.__node.graph.routeProxy]: r }); + } + return r; + }, s.route + "_routeProxy"); + s.route = s.route + "_routeProxy"; + if (!s.stopped) + w.run("subscribeToWorker", [s.subscribeRoute, wpId, s.route]).then((sub) => { + s.sub = sub; + }); + } + s.stop = async () => { + if (s.source && typeof s.sub === "number") { + s.source.unsubscribe(s.subscribeRoute, s.sub); + return true; + } + return void 0; + }; + s.start = async () => { + if (typeof s.sub !== "number") + return w.run("subscribeToWorker", [s.subscribeRoute, wpId, s.route, s.blocking]).then((sub) => { + s.sub = sub; + }); + }; + s.setArgs = async (args) => { + if (Array.isArray(args)) + await w.run("setValue", ["otherArgsProxy", args]); + else if (typeof args === "object") { + for (const key in args) { + await w.run("setValue", [key, args[key]]); + } + } + return true; + }; + s.terminate = () => { + w.terminate(); + if (s.source?.worker && typeof s.sub === "number") { + s.source.post("unsubscribe", s.sub); + } + if (s.pipeTo?.worker) { + s.pipeTo.worker.terminate(); + } + }; + if (s.callback) + w.subscribe(s.route, (res) => { + if (typeof s.callback === "string") + this.__node.graph.run(s.callback, res); + else + s.callback(res); + }); + } + return subprocesses; + }, + "addSubprocessTemplate": function subprocesstempalte(name, structs, oncreate, ondata, props) { + if (typeof oncreate === "string") + oncreate = parseFunctionFromText(oncreate); + if (typeof ondata === "string") + ondata = parseFunctionFromText(ondata); + if (typeof ondata === "function") { + algorithms[name] = { + ondata, + oncreate: typeof oncreate === "function" ? oncreate : null, + structs + }; + if (typeof props === "object") + Object.assign(algorithms[name], props); + return true; + } + }, + "updateSubprocess": function updatesubprocess(structs, _id) { + if (!this.__node.graph.ALGORITHMS) + this.__node.graph.ALGORITHMS = {}; + if (!_id) + _id = Object.keys(this.__node.graph.ALGORITHMS)[0]; + if (!_id) + return; + Object.assign(this.__node.graph.ALGORITHMS[_id], structs); + }, + "createSubprocess": function creatsubprocess(options, inputs) { + if (!this.__node.graph.ALGORITHMS) + this.__node.graph.ALGORITHMS = {}; + if (typeof options === "string") { + options = algorithms[options]; + } + if (typeof options === "object") { + if (typeof options.ondata === "string") + options.ondata = parseFunctionFromText(options.ondata); + let ctx; + if (typeof options?.ondata === "function") + ctx = createSubprocess(options, inputs); + if (ctx) + this.__node.graph.ALGORITHMS[ctx._id] = ctx; + console.log(ctx, options); + if (ctx) + return ctx._id; + } + return false; + }, + "runSubprocess": function runsubprocess(data, _id) { + if (!this.__node.graph.ALGORITHMS) + this.__node.graph.ALGORITHMS = {}; + if (!_id) + _id = Object.keys(this.__node.graph.ALGORITHMS)[0]; + if (!_id) + return; + let res = this.__node.graph.ALGORITHMS[_id].run(data); + if (res !== void 0) { + if (Array.isArray(res)) { + let pass = []; + res.forEach((r) => { + if (r !== void 0) { + pass.push(r); + this.__node.graph.setState({ [_id]: r }); + } + }); + if (pass.length > 0) { + return pass; + } + } else { + this.__node.graph.setState({ [_id]: res }); + return res; + } + } + } + }; + + // ../../services/router/Router.ts + var Router = class extends Service { + constructor(options) { + super(options); + this.name = "router"; + this.connections = {}; + this.sources = {}; + this.services = {}; + this.serviceConnections = {}; + this.users = {}; + this.addUser = async (info2, connections, config, receiving) => { + if (!info2._id) { + info2._id = `user${Math.floor(Math.random() * 1e15)}`; + } + let user = Object.assign({}, info2); + if (connections) { + for (const key in connections) { + if (typeof connections[key] === "object") { + if (!connections[key].connection._id) { + await new Promise((res, rej) => { + let start = performance.now(); + let checker = () => { + if (!connections[key].connection._id) { + if (performance.now() - start > 3e3) { + delete connections[key]; + rej(false); + } else { + setTimeout(() => { + checker(); + }, 100); + } + } else { + res(true); + } + }; + checker(); + }).catch((er) => { + console.error("Connections timed out:", er); + }); + } + } + } + for (const key in connections) { + connections[key] = this.addConnection(connections[key], user._id); + } + } + if (config) { + for (const c in config) { + this.openConnection(config[c].service, config[c], user._id, config[c].args); + } + } + let send = (message, ...a) => { + let connection = this.getConnection(user._id, "send"); + if (connection?.send) + return connection.send(message, ...a); + }; + let request = (message, method, ...a) => { + let connection = this.getConnection(user._id, "request"); + if (connection?.request) + return connection.request(message, method, ...a); + }; + let post = (route, args, method, ...a) => { + let connection = this.getConnection(user._id, "post"); + if (connection?.post) + return connection.post(route, args, method, ...a); + }; + let run = (route, args, method, ...a) => { + let connection = this.getConnection(user._id, "run"); + if (connection?.run) + return connection.run(route, args, method, ...a); + }; + let subscribe = (route, callback, ...a) => { + let connection = this.getConnection(user._id, "subscribe"); + if (connection?.subscribe) + return connection.subscribe(route, callback, ...a); + }; + let unsubscribe = (route, sub, ...a) => { + let connection = this.getConnection(user._id, "unsubscribe"); + if (connection?.unsubscribe) + return connection.unsubscribe(route, sub, ...a); + }; + let terminate = () => { + return this.removeUser(user); + }; + user.send = send; + user.request = request; + user.post = post; + user.run = run; + user.subscribe = subscribe; + user.unsubscribe = unsubscribe; + user.terminate = terminate; + this.users[user._id] = user; + if (connections && !receiving) { + let connectionIds = {}; + let pass = false; + Object.keys(connections).map((k, i) => { + if (connections[k]?._id) { + connectionIds[`${i}`] = connections[k]?._id; + pass = true; + } + }); + if (pass) { + user.send({ + route: "addUser", + args: [ + { _id: user._id }, + connectionIds, + void 0, + true + ] + }); + } + } + return user; + }; + this.getConnection = (sourceId, hasMethod) => { + if (this.sources[sourceId]) { + if (this.order) { + for (let i = 0; i < this.order.length; i++) { + let k = this.order[i]; + for (const key in this.sources[sourceId]) { + if (this.sources[sourceId][key].service) { + if (typeof this.sources[sourceId][key].service === "object") { + if (this.sources[sourceId][key].service.__node.tag === k) { + if (this.sources[sourceId][key].connectionType && this.sources[sourceId][key].service?.name) { + if (!this.serviceConnections[this.sources[sourceId][key].service.name]) { + this.removeConnection(this.sources[sourceId][key]); + continue; + } + } + return this.sources[sourceId][key]; + } + } else if (this.sources[sourceId][key].service === k) { + if (this.sources[sourceId][key].connectionType && this.sources[sourceId][key].service?.name) { + if (!this.serviceConnections[this.sources[sourceId][key].service.name]) + this.removeConnection(this.sources[sourceId][key]); + continue; + } + return this.sources[sourceId][key]; + } + } + } + } + } else { + for (const k in this.sources[sourceId]) { + if (this.sources[sourceId][k].connectionType && this.sources[sourceId][k].service?.name) { + if (!this.serviceConnections[this.sources[sourceId][k].service.name]) { + this.removeConnection(this.sources[sourceId][k]); + continue; + } + } + if (hasMethod && this.sources[sourceId][k][hasMethod]) { + return this.sources[sourceId][k]; + } else { + return this.sources[sourceId][k]; + } + } + } + } else if (this.order) { + for (let i = 0; i < this.order.length; i++) { + let k = this.order[i]; + if (this.sources[k]?.[sourceId]) { + if (this.sources[k][sourceId].connectionType && this.sources[k][sourceId].service?.name) { + if (!this.serviceConnections[this.sources[k][sourceId].service.service.name]) { + this.removeConnection(this.sources[k][sourceId].service); + continue; + } + } + if (hasMethod && this.sources[k][sourceId]?.[hasMethod]) { + return this.sources[k][sourceId]; + } else { + return this.sources[k][sourceId]; + } + } + } + } + if (typeof sourceId === "string" && this.connections[sourceId] && this.connections[sourceId].send) { + return this.connections[sourceId]; + } + }; + this.getConnections = (sourceId, hasMethod, props) => { + if (this.sources[sourceId]) { + if (!props && !hasMethod) + return this.sources[sourceId]; + let found = {}; + for (const key in this.sources[sourceId]) { + if (typeof this.sources[sourceId][key] === "object") { + if (!this.sources[sourceId][key]._id) { + for (const k in this.sources[sourceId][key]) { + if (typeof this.sources[sourceId][key][k] === "object") { + let pass = true; + if (hasMethod && !this.sources[sourceId][key][k][hasMethod]) + pass = false; + for (const p in props) { + if (typeof this.sources[sourceId][key][k][p] === "object" && typeof props[p] === "object") { + for (const pp in props[p]) { + if (props[p][pp] !== this.sources[sourceId][key][k][p][pp]) { + pass = false; + break; + } + } + } else if (this.sources[sourceId][key][k][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; + } + } + if (pass) { + found[this.sources[sourceId][key][k]._id] = this.sources[sourceId][key][k]; + } + } + } + } else { + let pass = true; + if (hasMethod && !this.sources[sourceId][key][hasMethod]) + pass = false; + for (const p in props) { + if (typeof this.sources[sourceId][key][p] === "object" && typeof props[p] === "object") { + for (const pp in props[p]) { + if (props[p][pp] !== this.sources[sourceId][key][p][pp]) { + pass = false; + break; + } + } + } else if (this.sources[sourceId][key][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; + } + } + if (pass) { + if (this.getConnection(this.sources[sourceId][key], hasMethod)) + found[this.sources[sourceId][key]._id] = this.sources[sourceId][key]; + } + } + } + } + } + }; + this.addConnection = (options, source) => { + let settings = {}; + if (typeof options === "string") { + if (this.connections[options]) { + options = this.connections[options]; + } else { + for (const j in this.serviceConnections) { + for (const k in this.serviceConnections[j]) { + if (this.serviceConnections[j][k][options]) { + options = { connection: this.serviceConnections[j][k][options] }; + options.service = j; + settings.connectionType = j; + settings.connectionsKey = k; + break; + } + } + } + } + if (typeof options === "string" && this.__node.nodes.get(options)) + options = { connection: this.__node.nodes.get(options) }; + } + if (!options || typeof options === "string") + return void 0; + if (source) + settings.source = source; + if (options.connection instanceof GraphNode) { + settings.connection = options.connection; + let node = settings.connection; + settings.send = async (message) => { + if (message.method) { + if (Array.isArray(message.args)) { + return node[message.method]?.(...message.args); + } else + return node[message.method]?.(message.args); + } else { + if (!node.__operator) + return; + if (Array.isArray(message.args)) { + return node.__operator(...message.args); + } else + return node.__operator(message.args); + } + }; + settings.request = async (message, method) => { + if (method) { + if (Array.isArray(message.args)) { + return node[method]?.(...message.args); + } else + return node[method]?.(message.args); + } else { + if (!node.__operator) + return; + if (Array.isArray(message.args)) { + return node.__operator(...message.args); + } else + return node.__operator(message.args); + } + }; + settings.post = async (route, args, method) => { + if (route && node.__node.graph.get(route)) { + let n = node.__node.graph.get(route); + if (method) { + if (Array.isArray(args)) { + return n[method]?.(...args); + } else + return n[method]?.(args); + } else { + if (Array.isArray(args)) { + return n.__operator(...args); + } else + return n.__operator(args); + } + } else { + if (method) { + if (Array.isArray(args)) { + return node[method]?.(...args); + } else + return node[method]?.(args); + } else { + if (Array.isArray(args)) { + return node.__operator(...args); + } else + return node.__operator(args); + } + } + }; + settings.run = settings.post; + settings.subscribe = async (callback) => { + return node.__subscribe(callback); + }; + settings.unsubscribe = async (sub) => { + return node.__unsubscribe(sub); + }; + settings.terminate = () => { + node.__node.graph.remove(node); + return true; + }; + settings.onclose = options.onclose; + if (settings.onclose) { + node.__addOndisconnected((n) => { + if (settings.onclose) + settings.onclose(settings, n); + }); + } + } else if (options.connection instanceof Graph) { + if (options.connection.__node.nodes.get("open")) + settings.service = options.connection; + let graph = settings.connection; + settings.send = async (message) => { + if (Array.isArray(message.args)) + graph.run(message.route, ...message.args); + else + graph.run(message.route, message.args); + }; + settings.request = async (message, method) => { + if (!message.route) + return void 0; + if (method) { + if (Array.isArray(message.args)) { + return graph.__node.nodes.get(message.route)[method]?.(...message.args); + } else + return graph.__node.nodes.get(message.route)[method]?.(message.args); + } else { + if (Array.isArray(message.args)) { + return graph.run(message.route, ...message.args); + } else + return graph.run(message.route, message.args); + } + }; + settings.post = async (route, args, method) => { + if (route && graph.get(route)) { + let n = graph.get(route); + if (method) { + if (Array.isArray(args)) { + return n[method]?.(...args); + } else + return n[method]?.(args); + } else { + if (Array.isArray(args)) { + return n.run(...args); + } else + return n.run(args); + } + } + }; + settings.run = settings.post; + settings.subscribe = async (route, callback) => { + return graph.subscribe(route, callback); + }; + settings.unsubscribe = async (route, sub) => { + return graph.unsubscribe(route, sub); + }; + settings.terminate = (n) => { + graph.remove(n); + return true; + }; + } else if (!(options._id && this.connections[options._id])) { + let c = options.connection; + if (typeof c === "string") { + if (this.connections[c]) + c = this.connections[c]; + else if (options.service) { + if (typeof options.service === "string") { + options.service = this.services[options.service]; + } + if (typeof options.service === "object") { + if (options.service.connections) { + for (const key in options.service.connections) { + if (options.service.connections[key][c]) { + c = options.service.connections[key][c]; + settings.connectionType = key; + settings.connectionsKey = c; + break; + } + } + } + } + } else { + for (const j in this.serviceConnections) { + for (const k in this.serviceConnections[j]) { + if (this.serviceConnections[j][k][c]) { + c = this.serviceConnections[j][k][c]; + options.service = j; + settings.connectionType = j; + settings.connectionsKey = k; + break; + } + } + } + } + } + if (typeof c !== "object") + return void 0; + settings._id = c._id; + settings.send = c.send; + settings.request = c.request; + settings.run = c.run; + settings.post = c.post; + settings.subscribe = c.subscribe; + settings.unsubscribe = c.unsubscribe; + settings.terminate = c.terminate; + settings.onclose = options.onclose; + if (settings.onclose) { + if (!(c.onclose && settings.onclose.toString() === c.onclose.toString())) { + let oldonclose = c.onclose; + c.onclose = (...args) => { + if (settings.onclose) + settings.onclose(settings, ...args); + if (this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { + this.removeUser(settings.source, false); + } + if (oldonclose) + oldonclose(...args); + }; + } + } else { + let oldonclose = c.onclose; + c.onclose = (...args) => { + this.removeConnection(settings); + if (this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { + this.removeUser(settings.source, false); + } + if (oldonclose) + oldonclose(...args); + }; + } + if (options.service) { + if (typeof options.service === "string") + options.service = this.services[options.service]; + settings.service = options.service; + } else if (c.graph) + settings.service = c.graph; + } + if (!settings.source && options.source) { + settings.source = options.source; + } else if (!settings.source && options.service) { + settings.source = typeof options.service === "object" ? options.service?.name : void 0; + } else if (!settings.source && (settings.connection instanceof GraphNode || settings.connection instanceof Graph)) { + settings.source = "local"; + if (!this.order.indexOf("local")) + this.order.unshift("local"); + } + if (!settings._id) + settings._id = `connection${Math.floor(Math.random() * 1e15)}`; + if (settings.source) { + if (!this.sources[settings.source]) + this.sources[settings.source] = {}; + this.sources[settings.source][settings._id] = settings; + } + if (!this.connections[settings._id]) + this.connections[settings._id] = settings; + return settings; + }; + this.removeConnection = (connection, terminate = false) => { + if (typeof connection === "object" && connection._id) + connection = connection._id; + if (typeof connection === "string") { + if (this.connections[connection]) { + if (terminate && this.connections[connection]) + this.connections[connection].terminate(); + delete this.connections[connection]; + for (const key in this.sources) { + if (this.sources[key][connection]) + delete this.sources[key][connection]; + else { + for (const k in this.sources[key]) { + if (this.sources[key][k]?.[connection]) { + delete this.sources[key][connection]; + } + } + } + } + return true; + } else if (this.sources[connection]) { + for (const key in this.sources[connection]) { + this.removeConnection(this.sources[connection][key], terminate); + } + return true; + } + } + }; + this.routeService = (service, connections, source, order) => { + this.services[service.name] = service; + if (service.__node?.nodes) + this.__node.nodes.forEach((n, k) => { + if (!service.__node?.nodes.get(k)) { + service.__node?.nodes.set(k, n); + } else + service.__node?.nodes.set(this.name + "." + k, n); + }); + if (service.users) + service.users = this.users; + if (connections) { + if (typeof connections === "string") + this.addServiceConnections(service, connections, source); + else { + for (const c in connections) { + this.addServiceConnections(service, c, source); + } + } + } + if (order) + this.order = order; + else { + if (!this.order) + this.order = []; + this.order.push(service.name); + } + }; + this.addServiceConnections = (service, connectionsKey, source) => { + if (typeof service === "string") { + service = this.services[service]; + } + if (connectionsKey && service[connectionsKey]) { + let newConnections = {}; + if (!this.serviceConnections[service.name]) + this.serviceConnections[service.name] = {}; + this.serviceConnections[service.name][connectionsKey] = service[connectionsKey]; + for (const key in service[connectionsKey]) { + if (!this.connections[key]) { + const res = this.addConnection({ connection: service[connectionsKey][key], service }, source); + if (res) { + newConnections[key] = res; + newConnections[key].connectionType = connectionsKey; + } else { + console.log("Could not make connection", service[connectionsKey][key], service, source); + } + } + } + return newConnections; + } + }; + this.openConnection = async (service, options, source, ...args) => { + if (typeof service === "string") { + service = this.services[service]; + } + if (service?.__node.nodes) { + let connection = service.run("open", options, ...args); + if (connection instanceof Promise) { + return connection.then(async (info2) => { + if (!info2._id) { + await new Promise((res, rej) => { + let start = performance.now(); + let checker = () => { + if (!info2._id) { + if (performance.now() - start > 3e3) { + rej(false); + } else { + setTimeout(() => { + checker(); + }, 100); + } + } else { + res(true); + } + }; + checker(); + }).catch((er) => { + console.error("Connections timed out:", er); + }); + } + if (info2._id) + this.addConnection({ connection: info2, service }, source); + }); + } else if (connection) { + if (!connection._id) { + await new Promise((res, rej) => { + let start = performance.now(); + let checker = () => { + if (!connection._id) { + if (performance.now() - start > 3e3) { + rej(false); + } else { + setTimeout(() => { + checker(); + }, 100); + } + } else { + res(true); + } + }; + checker(); + }).catch((er) => { + console.error("Connections timed out:", er); + }); + } + if (connection._id) + return this.addConnection({ connection, service }, source); + } + } + }; + this.terminate = (connection) => { + if (typeof connection === "string") + connection = this.connections[connection]; + return connection.terminate(); + }; + this.subscribeThroughConnection = (route, relay, endpoint, callback, ...args) => { + if (typeof relay === "string") { + relay = this.getConnection(relay, "run"); + } + if (typeof relay === "object") + return new Promise((res, rej) => { + relay.run("routeConnections", [route, endpoint, relay._id, ...args]).then((sub) => { + this.__node.state.subscribeTrigger(endpoint, (res2) => { + if (res2?.callbackId === route) { + if (!callback) + this.setState({ [endpoint]: res2.args }); + else if (typeof callback === "string") { + this.setState({ [callback]: res2.args }); + } else + callback(res2.args); + } + }); + res(sub); + }).catch(rej); + }); + }; + this.routeConnections = (route, transmitter, receiver, ...args) => { + let rxsrc; + if (typeof receiver === "string") { + if (this.sources[receiver]) { + rxsrc = receiver; + } + receiver = this.getConnection(receiver, "send"); + } + if (typeof transmitter === "string") { + transmitter = this.getConnection(transmitter, "subscribe"); + } + if (transmitter?.subscribe && receiver?.send) { + let res = new Promise((res2, rej) => { + transmitter.subscribe(route, transmitter._id, (res3) => { + if (!this.connections[receiver._id] && rxsrc) { + if (this.sources[rxsrc]) { + rxsrc = receiver; + Object.keys(this.sources[rxsrc]).forEach((k) => { + if (this.sources[receiver][k].send) { + receiver = this.sources[receiver][k]; + } + }); + } + } + if (this.connections[receiver._id]) + receiver.send({ callbackId: route, args: res3 }); + }, ...args).then((sub) => { + res2(sub); + }); + }); + return res; + } + }; + this.setUserData = (user, data) => { + if (user) { + if (typeof user === "string") { + user = this.users[user]; + if (!user) + return false; + } + } + if (data) { + if (typeof data === "string") { + data = JSON.parse(data); + } + } + if (typeof data === "object") { + this.recursivelyAssign(user, data); + return true; + } + }; + this.setTree(this); + if (options) { + if (options.order) + this.order = options.order; + if (options.graph) { + for (const key in options.graph) { + let opt = options.graph[key]; + if (typeof opt === "function") + opt = new opt(); + if (opt?.__node?.nodes) { + opt.name = key; + opt.__node.tag = key; + this.addServices({ [opt.name]: opt }); + this.routeService(opt, opt.connections); + } else { + if (typeof opt?.service === "function") + opt.service = new opt.service(); + if (opt?.service?.__node?.nodes) { + opt.service.name = key; + opt.service.__node.tag = key; + this.addServices({ [opt.service.name]: opt.service }); + this.routeService(opt.service); + } + if (typeof opt?.service === "object") { + if (opt.connections) { + if (Array.isArray(opt.connections)) { + opt.connections.forEach((k) => { + this.addServiceConnections(opt[key].service, k); + }); + } else + this.addServiceConnections(opt.service, opt.connections); + } + if (opt.config) { + for (const c in opt.config) { + this.openConnection(opt.service, opt.config[c], opt.config[c].source, opt.config[c].args); + } + } + } + } + } + } + } + } + removeUser(profile, terminate) { + if (terminate) + this.removeConnection(profile, terminate); + if (typeof profile === "string") + profile = this.users[profile]; + if (typeof profile === "object" && profile._id) { + delete this.users[profile._id]; + if (profile.onclose) + profile.onclose(profile); + } + return true; + } + }; + + // worker.ts + var url = URL.createObjectURL(new Blob([String('(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error(\'Dynamic require of "\'+x2+\'" is not supported\')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __accessCheck=(obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)};var __privateGet=(obj,member,getter)=>{__accessCheck(obj,member,"read from private field");return getter?getter.call(obj):member.get(obj)};var __privateAdd=(obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)};var __privateSet=(obj,member,value,setter)=>{__accessCheck(obj,member,"write to private field");setter?setter.call(obj,value):member.set(obj,value);return value};var require_sjcl=__commonJS({"../../services/e2ee/sjcl.js"(exports,module){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x2=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x2[e>>>24]<<24^x2[f>>16&255]<<16^x2[g>>8&255]<<8^x2[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn\'t "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn\'t base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn\'t match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn\'t match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can\'t attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto[\'randomBytes\']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto[\'getRandomValues\']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{if(node.__properties.__props)node.____apply(node.__properties.__props,true)};var __defProp3=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp3(target,name,{get:all[name],enumerable:true})};var moduleStringTag="[object Module]";var esm=object=>{const res=object&&(!!Object.keys(object).reduce((a,b)=>{const desc=Object.getOwnPropertyDescriptor(object,b);const isModule=desc&&desc.get&&!desc.set?1:0;return a+isModule},0)||Object.prototype.toString.call(object)===moduleStringTag);return!!res};var isSame=(a,b)=>{if(a&&typeof a==="object"&&b&&typeof b==="object"){const jA=JSON.stringify(a);const jB=JSON.stringify(b);return jA===jB}else return a===b};var iterateSymbols=(obj,callback)=>{return Promise.all(Object.getOwnPropertySymbols(obj).map(sym=>callback(sym,obj[sym])))};var getPath=(type,info2)=>{const pathType=info2.path[type];if(!pathType)throw new Error("Invalid Path Type");const filtered=pathType.filter(v=>typeof v==="string");return filtered.join(info2.keySeparator)};var getPathInfo=(path,options)=>{let splitPath=path;if(typeof path==="string")splitPath=path.split(options.keySeparator);else if(typeof path==="symbol")splitPath=[path];return{id:splitPath[0],path:splitPath.slice(1)}};var runCallback=(callback,path,info2,output,setGlobal=true)=>{if(callback instanceof Function){if(output&&typeof output==="object"&&typeof output.then==="function")output.then(value=>callback(path,info2,value));else callback(path,info2,output)}if(setGlobal&&globalThis.ESMonitorState){const callback2=globalThis.ESMonitorState.callback;globalThis.ESMonitorState.state[path]={output,value:info2};runCallback(callback2,path,info2,output,false)}};var defaultSamplingRate=60;var _pollingId,_sps,_a;var Poller=(_a=class{constructor(listeners2,sps){__privateAdd(this,_pollingId,void 0);__privateAdd(this,_sps,void 0);this.listeners={};this.setOptions=(opts={})=>{for(let key in opts)this[key]=opts[key]};this.add=info2=>{const sub=info2.sub;this.listeners[sub]=info2;this.start();return true};this.get=sub=>this.listeners[sub];this.remove=sub=>{delete this.listeners[sub];if(!Object.keys(this.listeners).length)this.stop()};this.poll=listeners22=>{iterateSymbols(listeners22,(sym,o)=>{let{callback,current,history}=o;if(!o.path.resolved)o.path.resolved=getPath("output",o);if(!isSame(current,history)){runCallback(callback,o.path.resolved,{},current);if(typeof current==="object"){if(Array.isArray(current))history=[...current];else history={...current}}else listeners22[sym].history=current}})};this.start=(listeners22=this.listeners)=>{if(!this.sps)this.sps=defaultSamplingRate;else if(!__privateGet(this,_pollingId)){console.warn("[escode]: Starting Polling!");__privateSet(this,_pollingId,setInterval(()=>this.poll(listeners22),1e3/this.sps))}};this.stop=()=>{if(__privateGet(this,_pollingId)){console.warn("[escode]: Stopped Polling!");clearInterval(__privateGet(this,_pollingId));__privateSet(this,_pollingId,void 0)}};if(listeners2)this.listeners=listeners2;if(sps)this.sps=sps}get sps(){return __privateGet(this,_sps)}set sps(sps){__privateSet(this,_sps,sps);const listeners2=this.listeners;const nListeners=Object.keys(listeners2).length;if(nListeners){this.stop();this.start()}}},_pollingId=new WeakMap,_sps=new WeakMap,_a);var listeners_exports={};__export(listeners_exports,{functionExecution:()=>functionExecution,functions:()=>functions2,getProxyFunction:()=>getProxyFunction,info:()=>info,register:()=>register,set:()=>set,setterExecution:()=>setterExecution,setters:()=>setters});globalThis.ESMonitorState={state:{},callback:void 0,info:{}};var global_default=globalThis.ESMonitorState;var performance2=async(callback,args)=>{const tic=globalThis.performance.now();const output=await callback(...args);const toc=globalThis.performance.now();return{output,value:toc-tic}};var infoFunctions={performance:performance2};var get=(func,args,info2)=>{let result={value:{},output:void 0};const infoToGet={...global_default.info,...info2};for(let key in infoToGet){if(infoToGet[key]&&infoFunctions[key]){const ogFunc=func;func=async(...args2)=>{const o=await infoFunctions[key](ogFunc,args2);result.value[key]=o.value;return o.output}}}result.output=func(...args);return result};var isProxy=Symbol("isProxy");var fromInspectable=Symbol("fromInspectable");var fromInspectableHandler=Symbol("fromInspectableHandler");var keySeparator=".";var hasKey=(key,obj)=>key in obj;var getShortcut=(path,shortcuts,keySeparator2)=>{const sc=shortcuts[path[0]];if(sc){const value=sc[path.slice(1).join(keySeparator2)];if(value)return value}};var getFromPath=(baseObject,path,opts={})=>{const fallbackKeys=opts.fallbacks??[];const keySeparator2=opts.keySeparator??keySeparator;if(opts.shortcuts){const shortcut=getShortcut(path,opts.shortcuts,keySeparator2);if(shortcut){if(opts.output==="info")return{value:shortcut,exists:true,shortcut:true};else return shortcut}}if(typeof path==="string")path=path.split(keySeparator2).flat();else if(typeof path=="symbol")path=[path];let exists;path=[...path];path=path.map(o=>typeof o==="string"?o.split(keySeparator2):o).flat();let ref=baseObject;for(let i=0;i{const create=opts?.create??false;const keySeparator2=opts?.keySeparator??keySeparator;if(typeof path==="string")path=path.split(keySeparator2);else if(typeof path=="symbol")path=[path];path=[...path];const copy=[...path];const last=copy.pop();if(ref.__children)ref=ref.__children;for(let i=0;ifunctions,objects:()=>objects});function define2(key,registerAsNewKey){const inspectable=this;const target=this.target;if(!this.parent){let value=target[key];if(typeof value==="function"){target[key]=async(...args)=>await this.proxy[key]({[fromInspectable]:true,value},...args)}else{try{Object.defineProperty(target,key,{get:()=>value,set:function(val){value=val;inspectable.proxy[key]={[isProxy]:this[isProxy],[fromInspectable]:true,value:val}},enumerable:true,configurable:true})}catch(e){console.error(`Could not reassign ${key} to a top-level setter...`)}}}if(registerAsNewKey)this.newKeys.add(key);this.create(key,target,void 0,true)}var define_default=define2;var functions=function(){const inspectable=this;return{apply:async function(target,thisArg,argumentsList){try{let foo=target;const isFromInspectable=argumentsList[0]?.[fromInspectable];if(isFromInspectable){foo=argumentsList[0].value;argumentsList=argumentsList.slice(1)}let listeners2=inspectable.listeners.functions;const pathStr=inspectable.path.join(inspectable.options.keySeparator);const toActivate=listeners2?listeners2[pathStr]:void 0;let output,executionInfo={};if(toActivate){executionInfo=functionExecution(thisArg,toActivate,foo,argumentsList);output=executionInfo.output}else{output=foo.apply(thisArg,argumentsList);executionInfo=inspectable?.state?.[pathStr]?.value??{}}const callback=inspectable.options.callback;runCallback(callback,pathStr,executionInfo,output);return output}catch(e){console.warn(`Function failed:`,e,inspectable.path)}}}};var objects=function(){const inspectable=this;return{get(target,prop,receiver){if(prop===isProxy)return true;return Reflect.get(target,prop,receiver)},set(target,prop,newVal,receiver){if(prop===isProxy)return true;const pathStr=[...inspectable.path,prop].join(inspectable.options.keySeparator);const isFromProxy=newVal?.[isProxy];const isFromInspectable=newVal?.[fromInspectable];if(isFromInspectable)newVal=newVal.value;const listeners2=inspectable.listeners.setters;const desc=Object.getOwnPropertyDescriptor(target,prop);const createListener=desc&&!desc.get&&!desc.set;if(createListener){if(typeof inspectable.options.globalCallback==="function"){const id=inspectable.path[0];define_default.call(inspectable,prop,true);set("setters",pathStr,newVal,inspectable.options.globalCallback,{[id]:inspectable.root},inspectable.listeners,inspectable.options)}}if(newVal){const newProxy=inspectable.create(prop,target,newVal);if(newProxy)newVal=newProxy}const toActivate=!isFromProxy;if(listeners2&&toActivate&&!inspectable.newKeys.has(prop)){const toActivate2=listeners2[pathStr];if(toActivate2)setterExecution(toActivate2,newVal)}const callback=inspectable.options.callback;const info2=inspectable?.state?.[pathStr]?.value??{};runCallback(callback,pathStr,info2,newVal);if(isFromInspectable||!toActivate)return true;else return Reflect.set(target,prop,newVal,receiver)}}};var canCreate=(parent,key,val)=>{try{if(val===void 0)val=parent[key]}catch(e){return e}const alreadyIs=parent[key]&&parent[key][isProxy];if(alreadyIs)return false;const type=typeof val;const isObject=type==="object";const isFunction=type=="function";const notObjOrFunc=!val||!(isObject||isFunction);if(notObjOrFunc)return false;if(val instanceof Element)return false;if(val instanceof EventTarget)return false;const isESM=isObject&&esm(val);if(isFunction)return true;else{const desc=Object.getOwnPropertyDescriptor(parent,key);if(desc&&(desc.value&&desc.writable||desc.set)){if(!isESM)return true}else if(!parent.hasOwnProperty(key))return true}return false};var Inspectable=class{constructor(target={},opts={},name,parent){this.path=[];this.listeners={};this.newKeys=new Set;this.state={};this.set=(path,info2,update)=>{this.state[path]={output:update,value:info2};setFromPath(path,update,this.proxy,{create:true})};this.check=canCreate;this.create=(key,parent2,val,set2=false)=>{const create=this.check(parent2,key,val);if(val===void 0)val=parent2[key];if(create&&!(create instanceof Error)){parent2[key]=new Inspectable(val,this.options,key,this);return parent2[key]}if(set2){try{this.proxy[key]=val??parent2[key]}catch(e){const isESM=esm(parent2);const path=[...this.path,key];console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM?" because the parent is an ESM.":""}`,isESM?"":e)}}return};if(!opts.pathFormat)opts.pathFormat="relative";if(!opts.keySeparator)opts.keySeparator=keySeparator;if(target.__proxy)this.proxy=target.__proxy;else if(target[isProxy])this.proxy=target;else{this.target=target;this.options=opts;this.parent=parent;if(this.parent){this.root=this.parent.root;this.path=[...this.parent.path];this.state=this.parent.state??{}}else this.root=target;if(name)this.path.push(name);if(this.options.listeners)this.listeners=this.options.listeners;if(this.options.path){if(this.options.path instanceof Function)this.path=this.options.path(this.path);else if(Array.isArray(this.options.path))this.path=this.options.path;else console.log("Invalid path",this.options.path)}if(this.path)this.path=this.path.filter(str=>typeof str==="string");if(!this.options.keySeparator)this.options.keySeparator=keySeparator;let type=this.options.type;if(type!="object")type=typeof target==="function"?"function":"object";const handler2=handlers_exports[`${type}s`].call(this);this.proxy=new Proxy(target,handler2);Object.defineProperty(target,"__proxy",{value:this.proxy,enumerable:false});Object.defineProperty(target,"__esInspectable",{value:this,enumerable:false});for(let key in target)define_default.call(this,key)}return this.proxy}};var setFromOptions=(path,value,baseOptions,opts)=>{const ref=opts.reference;const id=Array.isArray(path)?path[0]:typeof path==="string"?path.split(baseOptions.keySeparator)[0]:path;let isDynamic=opts.hasOwnProperty("static")?!opts.static:false;if(isDynamic&&!globalThis.Proxy){isDynamic=false;console.warn("Falling back to using function interception and setters...")}if(isDynamic){value=new Inspectable(value,{pathFormat:baseOptions.pathFormat,keySeparator:baseOptions.keySeparator,listeners:opts.listeners,path:path2=>path2.filter(str=>!baseOptions.fallbacks||!baseOptions.fallbacks.includes(str))},id)}let options={keySeparator:baseOptions.keySeparator,...opts};setFromPath(path,value,ref,options);return value};var info=(id,callback,path,originalValue,base,listeners2,options,refShortcut={})=>{if(typeof path==="string")path=path.split(options.keySeparator);const relativePath=path.join(options.keySeparator);const refs=base;const shortcutRef=refShortcut.ref;const shortcutPath=refShortcut.path;const get3=path2=>{const thisBase=shortcutRef??base;const res=getFromPath(thisBase,path2,{keySeparator:options.keySeparator,fallbacks:options.fallbacks});return res};const set2=(path2,value)=>{const thisBase=shortcutRef??base;setFromOptions(path2,value,options,{reference:thisBase,listeners:listeners2})};let onUpdate=options.onUpdate;let infoToOutput={};if(onUpdate&&typeof onUpdate==="object"&&onUpdate.callback instanceof Function){infoToOutput=onUpdate.info??{};onUpdate=onUpdate.callback}const absolute=[id,...path];let pathInfo={absolute,relative:relativePath.split(options.keySeparator),parent:absolute.slice(0,-1)};pathInfo.output=pathInfo[options.pathFormat];const completePathInfo=pathInfo;const info2={id,path:completePathInfo,keySeparator:options.keySeparator,infoToOutput,callback:(...args)=>{const output=callback(...args);if(onUpdate instanceof Function)onUpdate(...args);return output},get current(){return get3(shortcutPath??info2.path.absolute)},set current(val){set2(shortcutPath??info2.path.absolute,val)},get parent(){return get3(shortcutPath?shortcutPath?.slice(0,-1):info2.path.parent)},get reference(){return refs[id]},set reference(val){refs[id]=val},original:originalValue,history:typeof originalValue==="object"?Object.assign({},originalValue):originalValue,sub:Symbol("subscription"),last:path.slice(-1)[0]};return info2};var registerInLookup=(name,sub,lookups)=>{if(lookups){const id=Math.random();lookups.symbol[sub]={name,id};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id]=sub}};var register=(info2,collection,lookups)=>{const absolute=getPath("absolute",info2);if(!collection[absolute])collection[absolute]={};collection[absolute][info2.sub]=info2;registerInLookup(absolute,info2.sub,lookups);return true};var listeners={functions:functions2,setters};var set=(type,absPath,value,callback,base,allListeners,options)=>{const{id,path}=getPathInfo(absPath,options);const fullInfo=info(id,callback,path,value,base,listeners,options);if(listeners[type])listeners[type](fullInfo,allListeners[type],allListeners.lookup);else{const path2=getPath("absolute",fullInfo);allListeners[type][path2][fullInfo.sub]=fullInfo;if(allListeners.lookup)registerInLookup(path2,fullInfo.sub,allListeners.lookup)}};var get2=(info2,collection)=>collection[getPath("absolute",info2)];var handler=(info2,collection,subscribeCallback,lookups)=>{let success=!!get2(info2,collection);if(!success){let parent=info2.parent;let val=parent?.[info2.last];success=subscribeCallback(val,parent)}return register(info2,collection,lookups)};var setterExecution=(listeners2,value)=>{return iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,{},value)})};function setters(info2,collection,lookups){const thisValue=this;return handler(info2,collection["setters"],(value,parent)=>{let val=value;if(!parent)return;if(!parent[isProxy]){let redefine=true;try{delete parent[info2.last]}catch(e){console.error("Unable to redeclare setters. May already be a dynamic object...");redefine=false}if(redefine){try{Object.defineProperty(parent,info2.last,{get:()=>val,set:async v=>{const isFunction=typeof val==="function";val=v;if(!isFunction){const listeners2=Object.assign({},collection["setters"][getPath("absolute",info2)]);setterExecution(listeners2,v)}else val=getProxyFunction.call(thisValue,info2,collection,val)},enumerable:true,configurable:true})}catch(e){throw e}}}},lookups)}function getProxyFunction(info2,collection,fn){return function(...args){const listeners2=collection["functions"][getPath("absolute",info2)];return functionExecution(this,listeners2,fn??info2.original,args)}}var functionExecution=(context,listeners2,func,args)=>{listeners2=Object.assign({},listeners2);const keys=Object.getOwnPropertySymbols(listeners2);const infoTemplate=listeners2[keys[0]]??{};const executionInfo=get((...args2)=>func.call(context,...args2),args,infoTemplate.infoToOutput);iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,executionInfo.value,executionInfo.output)});return executionInfo};function functions2(info2,collection,lookups){return handler(info2,collection["functions"],(_,parent)=>{if(!parent[isProxy]){parent[info2.last]=getProxyFunction.call(this,info2,collection);return setters(info2,collection,lookups)}},lookups)}var drillSimple=(obj,callback,options)=>{let accumulator=options.accumulator;if(!accumulator)accumulator=options.accumulator={};const ignore=options.ignore||[];const path=options.path||[];const condition=options.condition||true;const seen=[];const fromSeen=[];let drill=(obj2,acc={},globalInfo)=>{for(let key in obj2){if(ignore.includes(key))continue;const val=obj2[key];const newPath=[...globalInfo.path,key];const info2={typeof:typeof val,name:val?.constructor?.name,simple:true,object:val&&typeof val==="object",path:newPath};if(info2.object){const name=info2.name;const isESM=esm(val);if(isESM||name==="Object"||name==="Array"){info2.simple=true;const idx=seen.indexOf(val);if(idx!==-1)acc[key]=fromSeen[idx];else{seen.push(val);const pass=condition instanceof Function?condition(key,val,info2):condition;info2.pass=pass;acc[key]=callback(key,val,info2);if(pass){fromSeen.push(acc[key]);acc[key]=drill(val,acc[key],{...globalInfo,path:newPath})}}}else{info2.simple=false;acc[key]=callback(key,val,info2)}}else acc[key]=callback(key,val,info2)}return acc};return drill(obj,accumulator,{path})};var createLookup=()=>{return{symbol:{},name:{}}};var Monitor=class{constructor(opts={}){this.poller=new Poller;this.options={pathFormat:"relative",keySeparator};this.listeners={polling:this.poller.listeners,functions:{},setters:{},lookup:createLookup()};this.references={};this.get=(path,output,reference=this.references,throwError=true)=>{return getFromPath(reference,path,{keySeparator:this.options.keySeparator,fallbacks:this.options.fallbacks,output},throwError)};this.set=(path,value,opts2={})=>{const optsCopy={...opts2};if(!optsCopy.reference)optsCopy.reference=this.references;if(!optsCopy.listeners)optsCopy.listeners=this.listeners;return setFromOptions(path,value,this.options,optsCopy)};this.on=(absPath,callback)=>{const info2=getPathInfo(absPath,this.options);return this.listen(info2.id,callback,info2.path)};this.getInfo=(label,callback,path,original)=>{const info2=info(label,callback,path,original,this.references,this.listeners,this.options);const id=Math.random();const lookups=this.listeners.lookup;const name=getPath("absolute",info2);lookups.symbol[info2.sub]={name,id};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id]=info2.sub;return info2};this.listen=(id,callback,path=[],__internal={})=>{if(typeof path==="string")path=path.split(this.options.keySeparator);else if(typeof path==="symbol")path=[path];const arrayPath=path;let baseRef=this.get(id);if(!baseRef){console.error(`Reference does not exist.`,id);return}if(!__internal.poll)__internal.poll=esm(baseRef);if(!__internal.seen)__internal.seen=[];const __internalComplete=__internal;const thisPath=[id,...arrayPath];const ref=this.get(thisPath);const toMonitorInternally=(val,allowArrays=false)=>{const first=val&&typeof val==="object";if(!first)return false;const isEl=val instanceof Element;if(isEl)return false;if(allowArrays)return true;else return!Array.isArray(val)};let subs={};const subscribeAll=toMonitorInternally(ref,true);if(subscribeAll){if(ref.__esInspectable)ref.__esInspectable.options.globalCallback=callback;drillSimple(ref,(_,__,drillInfo)=>{if(drillInfo.pass)return;else{const fullPath=[...arrayPath,...drillInfo.path];const internalSubs=this.listen(id,callback,fullPath,__internalComplete);Object.assign(subs,internalSubs)}},{condition:(_,val)=>toMonitorInternally(val)})}let info2;let success=false;try{info2=this.getInfo(id,callback,arrayPath,ref);if(info2){if(__internalComplete.poll)success=this.poller.add(info2);else{let type="setters";if(typeof ref==="function")type="functions";success=this.add(type,info2)}}}catch(e){console.error("Fallback to polling:",path,e);success=this.poller.add(info2)}if(success){subs[getPath("absolute",info2)]=info2.sub;if(this.options.onInit instanceof Function){const executionInfo={};for(let key in info2.infoToOutput)executionInfo[key]=void 0;this.options.onInit(getPath("output",info2),executionInfo)}return subs}else{console.error("Failed to subscribe to:",path);return}};this.add=(type,info2)=>{if(listeners_exports[type])return listeners_exports[type](info2,this.listeners,this.listeners.lookup);else{this.listeners[type][getPath("absolute",info2)][info2.sub]=info2;return true}};this.remove=subs=>{if(!subs){subs={...this.listeners.functions,...this.listeners.setters,...this.listeners.polling}}if(typeof subs!=="object")subs={sub:subs};for(let key in subs){let innerSub=subs[key];const handleUnsubscribe=sub=>{const res=this.unsubscribe(sub);if(res===false)console.warn(`Subscription for ${key} does not exist.`,sub)};if(typeof innerSub!=="symbol")iterateSymbols(innerSub,handleUnsubscribe);else handleUnsubscribe(innerSub)}return true};this.unsubscribe=sub=>{const info2=this.listeners.lookup.symbol[sub];const absPath=info2.name;const polling=this.poller.get(sub);const funcs=this.listeners.functions[absPath];const func=funcs?.[sub];const setters2=this.listeners.setters[absPath];const setter=setters2?.[sub];if(polling)this.poller.remove(sub);else if(func){delete funcs[sub];if(!Object.getOwnPropertySymbols(funcs).length){Object.defineProperty(func.parent,func.last,{value:func.original,writable:true});delete this.listeners.functions[absPath]}}else if(setter){delete setters2[sub];if(!Object.getOwnPropertySymbols(setters2).length){const parent=setter.parent;if(parent){const last=setter.last;const value=parent[last];Object.defineProperty(parent,last,{value,writable:true})}delete this.listeners.setters[absPath]}}else return false;delete this.listeners.lookup.symbol[sub];const nameLookup=this.listeners.lookup.name[info2.name];delete nameLookup[info2.id];if(!Object.getOwnPropertyNames(nameLookup).length)delete this.listeners.lookup.name[info2.name]};Object.defineProperty(this.listeners,"lookup",{value:createLookup(),enumerable:false,configurable:false});Object.assign(this.options,opts);this.poller.setOptions(opts.polling)}};var src_default=Monitor;var defaultPath="default";var operatorPath="__operator";var specialKeys={path:"__path",isGraphScript:"__",listeners:{value:"__listeners",branch:"__branch",bind:"__bind",trigger:"__trigger",format:"__format"}};var listenerObject=Symbol("listenerObject");var toSet=Symbol("toSet");var subscriptionKey=Symbol("subscriptionKey");var configKey=Symbol("configKey");var toResolveWithKey=Symbol("toResolveWithKey");var isConfigObject=o=>specialKeys.listeners.format in o||specialKeys.listeners.branch in o||specialKeys.listeners.trigger in o||specialKeys.listeners.bind in o;var initializedStatus="INITIALIZED";var registeredStatus="REGISTERED";var globalFrom={};var globalTo={};var globalActive={};var _triggers,_queue,_toResolveWith,_initialize,_getAbsolutePath,_getPathInfo;var Edgelord=class{constructor(listeners2,root,context){this.original={};this.active={};this.globals={};this.context={options:{}};this.rootPath="";this.status="";__privateAdd(this,_triggers,[]);__privateAdd(this,_queue,[]);__privateAdd(this,_toResolveWith,void 0);this.setInitialProperties=(listeners2={},root,context={})=>{Object.assign(this.context,context);if(root)this.rootPath=root;if(!this.context.options.keySeparator)this.context.options.keySeparator=this.context.monitor.options.keySeparator;this.original=listeners2;const globals=[{name:"active",ref:globalActive},{name:"from",ref:globalFrom},{name:"to",ref:globalTo}];globals.forEach(o=>{if(!o.ref[this.context.id])o.ref[this.context.id]={};this.globals[o.name]=o.ref[this.context.id]});__privateSet(this,_toResolveWith,this.getManager());this.runEachListener(listeners2,this.addToGlobalLog)};this.getManager=(mode="from")=>{let target=mode==="to"?this.globals.to:this.globals.from;this.rootPath.split(this.context.options.keySeparator).forEach(key=>{if(!target[key])target[key]={};target=target[key]});return target[toResolveWithKey]??this};this.onStart=f=>{const res=__privateGet(this,_toResolveWith);const isSame2=res===this;if(isSame2){if(this.status===initializedStatus)f();else __privateGet(this,_queue).push(f)}else res.onStart(f)};this.runEachListener=(listeners2,callback)=>{if(!callback)return;for(const first in listeners2){const second=listeners2[first];if(!second){console.warn("Skipping empty listener:",first);continue}if(second&&typeof second==="object"){const from=second;const to=first;for(let fromPath in from){callback(fromPath,to,from[fromPath])}}else{const from=first;const to=second;const typeOf=typeof to;if(typeOf==="function")callback(from,"",to);else if(typeOf==="string")callback(from,to,to);else console.error("Improperly Formatted Listener",to)}}};this.register=(listeners2=this.original)=>{this.runEachListener(listeners2,this.add);this.status=registeredStatus};__privateAdd(this,_initialize,o=>{const res=this.context.monitor.get(o.path,"info");if(typeof res.value==="function"){const args=Array.isArray(o.args)?o.args:[o.args];res.value(...args)}else console.error("Cannot yet trigger values...",o)});this.initialize=o=>{if(!this.status)__privateGet(this,_triggers).push(o);else if(this.status===registeredStatus){this.status=initializedStatus;__privateGet(this,_triggers).forEach(__privateGet(this,_initialize));__privateGet(this,_queue).forEach(f=>f());__privateSet(this,_queue,[]);__privateSet(this,_triggers,[])}else __privateGet(this,_initialize).call(this,o)};this.start=()=>{this.register();this.initialize()};__privateAdd(this,_getAbsolutePath,name=>{const sep=this.context.monitor.options.keySeparator;return!name||!this.rootPath||this.rootPath===name.slice(0,this.rootPath.length)&&name[this.rootPath.length]===sep?name:[this.rootPath,name].join(sep)});__privateAdd(this,_getPathInfo,path=>{const output={absolute:{},relative:{}};path=__privateGet(this,_getAbsolutePath).call(this,path);let rel=this.rootPath?path.replace(`${this.rootPath}.`,""):path;const baseArr=path.split(this.context.options.keySeparator);output.absolute.array=[this.context.id,...baseArr];output.relative.array=rel.split(this.context.options.keySeparator);let obj=this.context.monitor.get(output.relative.array,void 0,this.context.instance,false);if(this.context.graph){if(obj&&this.context.bound){output.absolute.array=[this.context.id,this.context.bound,...output.absolute.array.slice(1)];output.relative.array.unshift(this.context.bound)}else if(!obj){const rel2=output.relative.array.join(this.context.options.keySeparator);obj=this.context.graph.get(rel2)}}const isGraphScript=obj&&typeof obj==="object"&&specialKeys.isGraphScript in obj;if(isGraphScript){if(obj[operatorPath]){output.absolute.array.push(operatorPath);output.relative.array.push(operatorPath)}else if(obj[defaultPath]){output.absolute.array.push(defaultPath);output.relative.array.push(defaultPath)}}output.absolute.value=output.absolute.array.slice(1).join(this.context.options.keySeparator);output.relative.value=output.relative.array.join(this.context.options.keySeparator);return output});this.add=(from,to,value=true,subscription)=>{if(typeof to=="function"){value=to;to=""}else if(typeof to!=="string"){console.error("Improperly Formatted Listener",from,to,value);return}if(!value)return;const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const absPath=fromInfo.absolute.value;if(!subscription)subscription=this.globals.active[absPath]?.[subscriptionKey];if(!subscription){subscription=this.context.monitor.on(fromInfo.absolute.array,(path,_,update)=>this.activate(path,update),{ref:this.context.instance,path:fromInfo.relative.array})}if(typeof value=="string")value=toInfo.absolute.array.slice(1).join(this.context.options.keySeparator);const info2={value,[listenerObject]:true};const refs=[this.active,this.globals.active];refs.forEach(ref=>{if(!ref[absPath])ref[absPath]={};const base=ref[absPath];if(!base[subscriptionKey]){Object.defineProperty(base,subscriptionKey,{value:subscription,configurable:true})}base[toInfo.absolute.value]=info2});const args=value[specialKeys.listeners.trigger];if(args)__privateGet(this,_toResolveWith).initialize({path:fromInfo.absolute.array,args});this.addToGlobalLog(absPath);return info2};this.addToGlobalLog=(path,mode="from")=>{const absolutePath=__privateGet(this,_getAbsolutePath).call(this,path);let target=mode==="to"?this.globals.to:this.globals.from;const globalPath=absolutePath.split(this.context.options.keySeparator);globalPath.forEach(key=>{if(!target[key])target[key]={};target=target[key];if(!target[toResolveWithKey])target[toResolveWithKey]=this})};this.remove=(from,to)=>{const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const path=[fromInfo.absolute.value,toInfo.absolute.value];const toRemove=[{ref:this.active,path},{ref:this.globals.active,path,unlisten:true}];toRemove.forEach(o=>{const{ref,path:path2,unlisten}=o;let base=ref[path2[0]];if(typeof base==="object"){delete base[path2[1]];if(Object.keys(base).length===0){delete ref[path2[0]];const sub=base[subscriptionKey];if(unlisten&&sub){this.context.monitor.remove(sub)}delete base[subscriptionKey]}}else delete ref[path2[0]]})};this.clear=name=>{const value=__privateGet(this,_getAbsolutePath).call(this,name);Object.keys(this.active).forEach(from=>{Object.keys(this.active[from]).forEach(to=>{if(!value||from.slice(0,value.length)===value||to.slice(0,value.length)===value)this.remove(from,to)})})};this.has=(from,ref=this.active)=>!!ref[from];this.get=(from,ref=this.active)=>ref[from];this.activate=(from,update)=>{const listenerGroups=[{info:this.get(from,this.globals.active),name:from}];listenerGroups.forEach(group=>{const info2=group.info;if(info2){if(info2[listenerObject]){this.pass(from,{value:info2.value,parent:this.active,key:group.name,subscription:info2.subscription,__value:true},update)}else if(typeof info2==="object"){for(let key in info2){this.pass(from,{parent:info2,key,subscription:info2[key].subscription,value:info2[key].value},update)}}else console.error("Improperly Formatted Listener",info2)}})};this.pass=(from,target,update)=>{const id=this.context.id;const isValue=target?.__value;let parent=target.parent;let to=target.key;const info2=target.parent[to];target=info2.value;let config=info2?.[configKey];let ogValue=target;const type=typeof target;const checkIfSetter=(path,willSet)=>{const info3=this.context.monitor.get(path,"info");if(info3.exists){const val=info3.value;const noDefault=typeof val!=="function"&&!val?.default;const value=noDefault?toSet:val;const res={value};if(willSet){target=res.value;parent[to]=res}return res}else return{value:void 0}};const transform=willSet=>{const fullPath=[id];fullPath.push(...to.split(this.context.options.keySeparator));return checkIfSetter(fullPath,willSet)};const getPathArray=latest=>{const path=[id];const topPath=[];if(this.rootPath)topPath.push(...this.rootPath.split(this.context.options.keySeparator));topPath.push(...latest.split(this.context.options.keySeparator));path.push(...topPath);return path};if(typeof target==="boolean"){if(!isValue)transform(true);else console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`)}else if(type==="string"){const path=getPathArray(ogValue);checkIfSetter(path,true);if(isValue){parent[to]={[ogValue]:parent[to]};to=ogValue}}else if(target&&type==="object"){const isConfig=isConfigObject(ogValue);if(isConfig){if("value"in ogValue){if(isValue){target=parent[to]=ogValue.value}else{target=parent[to].value=ogValue.value}}else transform(true);if(ogValue){if(ogValue)config=ogValue}Object.defineProperty(parent[to],configKey,{value:config})}}let isValidInput=true;if(config){const bindKey=specialKeys.listeners.value;if(bindKey in config){const path=getPathArray(config[bindKey].original??config[bindKey]);if(typeof config[bindKey]==="string"){const res=this.context.monitor.get(path);if(!res)target=`because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.`;else{config[bindKey]={value:res,original:config[bindKey]}}}else if(!config[bindKey].value.__parent){target=`because ${config[bindKey].original??id.toString()} has become unparented.`}}else{const branchKey=specialKeys.listeners.branch;const formatKey=specialKeys.listeners.format;if(branchKey in config){const isValid=config[branchKey].find(o=>{let localValid=[];if("if"in o)localValid.push(o.if(update));if("is"in o)localValid.push(o.is===update);const isValidLocal=localValid.length>0&&localValid.reduce((a,b)=>a&&b,true);if(isValidLocal){if("value"in o)update=o.value}return isValidLocal});if(!isValid)isValidInput=false}if(formatKey in config){try{update=config[formatKey](update);if(update===void 0)isValidInput=false}catch(e){console.error("Failed to format arguments",e)}}}}if(isValidInput&&update!==void 0){const arrayUpdate=Array.isArray(update)?update:[update];if(target===toSet){const parentPath=[id];parentPath.push(...to.split(this.context.options.keySeparator));const idx=parentPath.pop();const info3=this.context.monitor.get(parentPath,"info");if(info3.value)info3.value[idx]=update;else console.error(`Cannot set value on ${parentPath.filter(str=>typeof str!=="symbol").join(this.context.options.keySeparator)} from ${from}`)}else if(target?.default)target.default.call(target,...arrayUpdate);else if(typeof target==="function"){const noContext=parent[to][listenerObject];if(noContext)target.call(config?.[specialKeys.listeners.bind]?.value??this.context.instance,...arrayUpdate);else target(...arrayUpdate)}else{let baseMessage=to?`listener: ${from} \\u2014> ${to}`:`listener from ${from}`;if(parent){console.warn(`Deleting ${baseMessage}`,target);delete parent[to]}else console.error(`Failed to add ${baseMessage}`,target)}}};if(listeners2||root||context)this.setInitialProperties(listeners2,root,context)}};_triggers=new WeakMap;_queue=new WeakMap;_toResolveWith=new WeakMap;_initialize=new WeakMap;_getAbsolutePath=new WeakMap;_getPathInfo=new WeakMap;var edgelord_default=Edgelord;function applyLoader(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loader){const args=[node,parent,graph,tree,properties,tag];if(typeof loader==="object"){if(loader.init)loader(...args);if(loader.connected)node.__addOnconnected(loader.connect);if(loader.disconnected)node.__addOndisconnected(loader.disconnect)}else if(typeof loader==="function")loader(...args)}function applyLoaders(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loaders2=this.__node.loaders){for(const l in loaders2)applyLoader(node,parent,graph,tree,properties,tag,loaders2[l])}var _parent,_graph,_properties,_options,_applied,_applySetters;var GraphNode=class{constructor(properties,parent,graph,options){this.__=Symbol("graphscript");this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,ref:this,flow:new edgelord_default};__privateAdd(this,_parent,void 0);__privateAdd(this,_graph,void 0);__privateAdd(this,_properties,{});__privateAdd(this,_options,{});__privateAdd(this,_applied,[]);__privateAdd(this,_applySetters,(properties=__privateGet(this,_properties),proxy=__privateGet(this,_properties),ignore=[])=>{const isProxy2=proxy===true;let keys=Object.getOwnPropertyNames(properties);if(isProxy2){proxy=properties;keys=getAllPropertyNames(properties)}for(const key of keys){if(ignore.includes(key))continue;if(__privateGet(this,_applied).includes(key))continue;__privateGet(this,_applied).push(key);if(key==="__properties")Object.defineProperty(this,key,{get:()=>__privateGet(this,_properties),enumerable:true});else if(key==="__props"){Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>{proxy[key]=value;__privateGet(this,_applySetters).call(this,value,true)},enumerable:true,configurable:true})}else{Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>proxy[key]=value,enumerable:true,configurable:false})}}});this.____apply=__privateGet(this,_applySetters);this.__init=(properties,parent=__privateGet(this,_parent),graph=__privateGet(this,_graph),options=__privateGet(this,_options))=>{__privateSet(this,_parent,parent);__privateSet(this,_graph,graph);__privateSet(this,_options,options);if(properties){let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(typeof properties==="object"){if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}properties=properties.__node.tree}__privateSet(this,_properties,properties);if(!properties.__node)properties.__node={};if(!properties.__node.initial)this.__node.initial=orig;if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph)properties.__node.graph=graph;if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;properties.__node=Object.assign(this.__node,properties.__node);const ogProperties=properties;__privateGet(this,_applySetters).call(this);applyLoaders.call(graph,this,parent,graph,graph?.__node?.tree,properties);__privateGet(this,_applySetters).call(this,void 0,void 0,["__props"]);if(properties instanceof Graph)this.__node.source=properties;if(typeof options.onInit==="function")options.onInit();if(graph){const symbol=(graph.__node.ref??this).__;const monitor=graph.monitor;this.__node.flow.setInitialProperties(this.__listeners,void 0,{id:symbol,instance:this,monitor,graph,bound:this.__node.tag})}else console.error("No flow manager created for "+this.__node.tag)}}};this.__init(properties,parent,graph,options)}get __properties(){return __privateGet(this,_properties)}__addOnconnected(callback){if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o.call(this,this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o.call(this,this)})}}};_parent=new WeakMap;_graph=new WeakMap;_properties=new WeakMap;_options=new WeakMap;_applied=new WeakMap;_applySetters=new WeakMap;var _init;var _Graph=class{constructor(options){this.monitor=new src_default({keySeparator:".",fallbacks:["__children"]});this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,ref:new GraphNode,loaders:[props_loader_default]};this.init=options=>{if(options){if(options.loaders){this.setLoaders(options.loaders);delete options.loaders}recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};__privateAdd(this,_init,properties=>{const node=this.__node.ref;node.__init(properties,this,this,{onInit:()=>{this.monitor.set(node.__,node.__properties)}});return node});this.setTree=tree=>{const hasGraphscriptProperties=Object.keys(tree).find(str=>{const slice=str.slice(0,2);return slice==="__"&&str!=="__node"});if(!hasGraphscriptProperties)tree={__children:tree};if(!tree.__node)tree.__node={};this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners2=this.recursiveSet(cpy,this,void 0,tree);if(!tree.__node.tag)tree.__node.tag=this.__node.tag;const node=__privateGet(this,_init).call(this,tree);const children=node.__children;const copy=Object.assign({},children);if(children)listeners2=this.recursiveSet(copy,this,void 0,children);if(node.__listeners)listeners2[node.__node.tag]=node.__listeners;this.__node.nodes.forEach(n=>n.__node.flow.start());node.__callConnected();return cpy};this.setLoaders=(loaders2,replace)=>{console.error("Setting loaders",loaders2);if(replace)this.__node.loaders=loaders2;else{if(Array.isArray(this.__node.loaders)){if(Array.isArray(loaders2))this.__node.loaders=[...this.__node.loaders,...loaders2];else this.__node.loaders=[...this.__node.loaders,...Object.values(loaders2)]}else Object.assign(this.__node.loaders,loaders2)}return this.__node.loaders};this.add=(properties,parent)=>{let listeners2={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}node.__callConnected();return node}return};this.recursiveSet=(t,parent,listeners2={},origin=t)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent,this);this.set(node.__node.tag,node);t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}let parentNode=parent instanceof _Graph?parent.__node.ref:parent;parentNode.__addOnconnected(()=>node.__callConnected())}}return listeners2};this.remove=node=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];this.clearListeners(node);node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){const node2=t[key].__node.ref;this.clearListeners(node2);this.delete(node2.__node.tag);delete this.__node.tree[node2.__node.tag];this.delete(key);delete this.__node.tree[key];node2.__node.tag=node2.__node.tag.substring(node2.__node.tag.lastIndexOf(".")+1);this.clearListeners(node2);node2.__callDisconnected();if(node2.__children)recursiveRemove(node2.__children)}};if(node.__children)recursiveRemove(node.__children)}if(node?.__node.tag&&node?.__parent){node.__parent=void 0;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.clearListeners=node=>{this.unsubscribe(node);this.clear(node)};this.get=(tag,base)=>{if(base instanceof GraphNode)base=base.__node.tag;if(tag===this.__node.tag)return this.__node.ref;if(base){const relFrom=[base,tag].join(".");const got=this.get(relFrom);if(got)return got}return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(from,to,value=true,bound=this.__node.ref)=>{if(typeof from!=="string")from=from.__node.tag;if(typeof bound==="string")bound=this.get(bound);if(bound)bound.__node.flow.add(from,to,value)};this.unsubscribe=(node,from,to)=>this.clear(from,to,node);this.clear=(from,to,bound)=>{const nd=typeof bound==="string"?this.get(bound):bound;if(typeof from==="symbol")return this.__node.flow.remove(from);let fromString=from instanceof GraphNode?from.__node.tag:from;let toString=to instanceof GraphNode?to.__node.tag:to;const remove=n=>{const flow=n.__node.flow;toString?flow.remove(fromString,toString):flow.clear(fromString)};if(nd)remove(nd);else{remove(this.__node.ref);this.__node.nodes.forEach(remove)}};this.activate=(from,value)=>this.__node.ref.__node.flow.activate(from,value);this.setState=update=>{for(let key in update)this.activate(key,update)};this.init(options)}};var Graph=_Graph;_init=new WeakMap;function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllPropertyNames(obj){var props=[];do{if(obj.constructor.name==="Object")props.push(...Object.keys(obj));else Object.getOwnPropertyNames(obj).forEach(function(prop){if(props.indexOf(prop)===-1)props.push(prop)})}while(obj=Object.getPrototypeOf(obj));return props}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode)graph.subscribe(parent.__node.tag,node.__node.tag)};var loop=(node,parent,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;const delay=(...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})};node.__operator=delay}else if(node.__node.frame===true){let fn=node.__operator;const frame=(...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})};node.__operator=frame}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;const repeat=async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result};node.__operator=repeat}if(node.__node.loop&&typeof node.__node.loop==="number"){let ogFunction=node.__operator;const looper=function(...args){if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){const res=ogFunction.call(node,...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop);return res}};node.__operator=looper;node.__addOnconnected(node2=>{if(node2.__node.looping)node2.__operator()});let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;const animate2=(...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn.call(node,...args);requestAnimationFrame(()=>{node.__operator(...args)})}return true};node.__operator=animate2;node.__addOnconnected(node2=>{if(node2.__node.animating||(!("animating"in node2.__node)||node2.__node.animating)&&node2.__animation)setTimeout(()=>{requestAnimationFrame(node2.__operator)},10)});node.__addOndisconnected(node2=>{if(node2.__node.animating)node2.__node.animating=false})}};var branching=(node,parent,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__operator=node.post}else if(!node.__operator&&typeof node.get=="function"){node.__operator=node.get}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set2=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set2(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\\\"))args[0]=args[0].replace(/\\\\/g,"");if(args[0][0]===\'"\'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var import_sjcl=__toESM(require_sjcl());var _HTTPfrontend=class extends Service{constructor(options,path,fetched){super(options);this.name="http";this.fetchProxied=false;this.listening={};this.GET=(url="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{let obj=message;if(typeof obj==="object"){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url);return this.POST(message,url)};this.transponder=(url,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url,data:message,responseType:type,onload:ev2=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\\\"))body=body.replace(/\\\\/g,"");if(body[0]===\'"\'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};this.listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};this.stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}};this.setTree(this);this.listen(path,fetched)}};var HTTPfrontend=_HTTPfrontend;HTTPfrontend.request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler2]of entries){element.addEventListener(eventName,function(event){handler2(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners2=this.__listeners;if(listeners2[type]===void 0){listeners2[type]=[]}if(listeners2[type].indexOf(listener)===-1){listeners2[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners2=this.__listeners;return listeners2[type]!==void 0&&listeners2[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText2(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText2(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText2(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText2(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText2(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText2(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText2(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText2(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText2(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w=s.worker;let wpId;wpId=service.establishMessageChannel(w.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w.run("setValue",["routeProxy",s.route]);w.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w2=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w.worker,w2.worker);s.pipeTo.worker=w2}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w.run("setValue",["routeProxy",s.route]);service.transferFunction(w,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;Object.assign(this.__node.graph.ALGORITHMS[_id],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;let res=this.__node.graph.ALGORITHMS[_id].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id]:res});return res}}}};if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope){const worker=new WorkerService({services:{workerCanvasRoutes,unsafeRoutes,Math,Math2}});console.log(worker)}var worker_default=self;})();\n')], { type: "text/javascript" })); + var worker_default = url; + + // index.ts + var workers = new WorkerService(); + var router = new Router({ + services: { + workers, + workerCanvasRoutes + }, + loaders: { + htmlloader + } + }); + console.log(router); + var ret = router.setTree({ + "main": { + tagName: "div", + __children: { + "div": { + tagName: "div", + innerText: "Multithreaded canvases!" + }, + "canvas": { + tagName: "canvas", + style: { width: "100%", height: "100%" }, + __onrender: function(elm) { + const renderer = workers.addWorker({ url: worker_default }); + this.worker = renderer; + if (renderer) { + console.log("renderer", renderer); + const controls = router.run("transferCanvas", renderer.worker, { + canvas: elm, + context: "2d", + _id: elm.id, + init: (self2, canvas, context) => { + console.log("canvas", canvas); + canvas.addEventListener("mousedown", (ev) => { + console.log("clicked!", ev, canvas); + }); + }, + draw: (self2, canvas, context) => { + context.clearRect(0, 0, canvas.width, canvas.height); + context.fillStyle = `rgb(0,${Math.sin(Date.now() * 1e-3) * 255},${Math.cos(Date.now() * 1e-3) * 255})`; + context.fillRect(0, 0, canvas.width, canvas.height); + } + }); + } + }, + __onremove: function(elm) { + workers.terminate(this.worker._id); + } + } + } + } + }); +})(); diff --git a/examples/workercanvas/dist/worker.js b/examples/workercanvas/dist/worker.js new file mode 100644 index 00000000..f9353ca5 --- /dev/null +++ b/examples/workercanvas/dist/worker.js @@ -0,0 +1 @@ +(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __accessCheck=(obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)};var __privateGet=(obj,member,getter)=>{__accessCheck(obj,member,"read from private field");return getter?getter.call(obj):member.get(obj)};var __privateAdd=(obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)};var __privateSet=(obj,member,value,setter)=>{__accessCheck(obj,member,"write to private field");setter?setter.call(obj,value):member.set(obj,value);return value};var require_sjcl=__commonJS({"../../services/e2ee/sjcl.js"(exports,module){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x2=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x2[e>>>24]<<24^x2[f>>16&255]<<16^x2[g>>8&255]<<8^x2[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{if(node.__properties.__props)node.____apply(node.__properties.__props,true)};var __defProp3=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp3(target,name,{get:all[name],enumerable:true})};var moduleStringTag="[object Module]";var esm=object=>{const res=object&&(!!Object.keys(object).reduce((a,b)=>{const desc=Object.getOwnPropertyDescriptor(object,b);const isModule=desc&&desc.get&&!desc.set?1:0;return a+isModule},0)||Object.prototype.toString.call(object)===moduleStringTag);return!!res};var isSame=(a,b)=>{if(a&&typeof a==="object"&&b&&typeof b==="object"){const jA=JSON.stringify(a);const jB=JSON.stringify(b);return jA===jB}else return a===b};var iterateSymbols=(obj,callback)=>{return Promise.all(Object.getOwnPropertySymbols(obj).map(sym=>callback(sym,obj[sym])))};var getPath=(type,info2)=>{const pathType=info2.path[type];if(!pathType)throw new Error("Invalid Path Type");const filtered=pathType.filter(v=>typeof v==="string");return filtered.join(info2.keySeparator)};var getPathInfo=(path,options)=>{let splitPath=path;if(typeof path==="string")splitPath=path.split(options.keySeparator);else if(typeof path==="symbol")splitPath=[path];return{id:splitPath[0],path:splitPath.slice(1)}};var runCallback=(callback,path,info2,output,setGlobal=true)=>{if(callback instanceof Function){if(output&&typeof output==="object"&&typeof output.then==="function")output.then(value=>callback(path,info2,value));else callback(path,info2,output)}if(setGlobal&&globalThis.ESMonitorState){const callback2=globalThis.ESMonitorState.callback;globalThis.ESMonitorState.state[path]={output,value:info2};runCallback(callback2,path,info2,output,false)}};var defaultSamplingRate=60;var _pollingId,_sps,_a;var Poller=(_a=class{constructor(listeners2,sps){__privateAdd(this,_pollingId,void 0);__privateAdd(this,_sps,void 0);this.listeners={};this.setOptions=(opts={})=>{for(let key in opts)this[key]=opts[key]};this.add=info2=>{const sub=info2.sub;this.listeners[sub]=info2;this.start();return true};this.get=sub=>this.listeners[sub];this.remove=sub=>{delete this.listeners[sub];if(!Object.keys(this.listeners).length)this.stop()};this.poll=listeners22=>{iterateSymbols(listeners22,(sym,o)=>{let{callback,current,history}=o;if(!o.path.resolved)o.path.resolved=getPath("output",o);if(!isSame(current,history)){runCallback(callback,o.path.resolved,{},current);if(typeof current==="object"){if(Array.isArray(current))history=[...current];else history={...current}}else listeners22[sym].history=current}})};this.start=(listeners22=this.listeners)=>{if(!this.sps)this.sps=defaultSamplingRate;else if(!__privateGet(this,_pollingId)){console.warn("[escode]: Starting Polling!");__privateSet(this,_pollingId,setInterval(()=>this.poll(listeners22),1e3/this.sps))}};this.stop=()=>{if(__privateGet(this,_pollingId)){console.warn("[escode]: Stopped Polling!");clearInterval(__privateGet(this,_pollingId));__privateSet(this,_pollingId,void 0)}};if(listeners2)this.listeners=listeners2;if(sps)this.sps=sps}get sps(){return __privateGet(this,_sps)}set sps(sps){__privateSet(this,_sps,sps);const listeners2=this.listeners;const nListeners=Object.keys(listeners2).length;if(nListeners){this.stop();this.start()}}},_pollingId=new WeakMap,_sps=new WeakMap,_a);var listeners_exports={};__export(listeners_exports,{functionExecution:()=>functionExecution,functions:()=>functions2,getProxyFunction:()=>getProxyFunction,info:()=>info,register:()=>register,set:()=>set,setterExecution:()=>setterExecution,setters:()=>setters});globalThis.ESMonitorState={state:{},callback:void 0,info:{}};var global_default=globalThis.ESMonitorState;var performance2=async(callback,args)=>{const tic=globalThis.performance.now();const output=await callback(...args);const toc=globalThis.performance.now();return{output,value:toc-tic}};var infoFunctions={performance:performance2};var get=(func,args,info2)=>{let result={value:{},output:void 0};const infoToGet={...global_default.info,...info2};for(let key in infoToGet){if(infoToGet[key]&&infoFunctions[key]){const ogFunc=func;func=async(...args2)=>{const o=await infoFunctions[key](ogFunc,args2);result.value[key]=o.value;return o.output}}}result.output=func(...args);return result};var isProxy=Symbol("isProxy");var fromInspectable=Symbol("fromInspectable");var fromInspectableHandler=Symbol("fromInspectableHandler");var keySeparator=".";var hasKey=(key,obj)=>key in obj;var getShortcut=(path,shortcuts,keySeparator2)=>{const sc=shortcuts[path[0]];if(sc){const value=sc[path.slice(1).join(keySeparator2)];if(value)return value}};var getFromPath=(baseObject,path,opts={})=>{const fallbackKeys=opts.fallbacks??[];const keySeparator2=opts.keySeparator??keySeparator;if(opts.shortcuts){const shortcut=getShortcut(path,opts.shortcuts,keySeparator2);if(shortcut){if(opts.output==="info")return{value:shortcut,exists:true,shortcut:true};else return shortcut}}if(typeof path==="string")path=path.split(keySeparator2).flat();else if(typeof path=="symbol")path=[path];let exists;path=[...path];path=path.map(o=>typeof o==="string"?o.split(keySeparator2):o).flat();let ref=baseObject;for(let i=0;i{const create=opts?.create??false;const keySeparator2=opts?.keySeparator??keySeparator;if(typeof path==="string")path=path.split(keySeparator2);else if(typeof path=="symbol")path=[path];path=[...path];const copy=[...path];const last=copy.pop();if(ref.__children)ref=ref.__children;for(let i=0;ifunctions,objects:()=>objects});function define2(key,registerAsNewKey){const inspectable=this;const target=this.target;if(!this.parent){let value=target[key];if(typeof value==="function"){target[key]=async(...args)=>await this.proxy[key]({[fromInspectable]:true,value},...args)}else{try{Object.defineProperty(target,key,{get:()=>value,set:function(val){value=val;inspectable.proxy[key]={[isProxy]:this[isProxy],[fromInspectable]:true,value:val}},enumerable:true,configurable:true})}catch(e){console.error(`Could not reassign ${key} to a top-level setter...`)}}}if(registerAsNewKey)this.newKeys.add(key);this.create(key,target,void 0,true)}var define_default=define2;var functions=function(){const inspectable=this;return{apply:async function(target,thisArg,argumentsList){try{let foo=target;const isFromInspectable=argumentsList[0]?.[fromInspectable];if(isFromInspectable){foo=argumentsList[0].value;argumentsList=argumentsList.slice(1)}let listeners2=inspectable.listeners.functions;const pathStr=inspectable.path.join(inspectable.options.keySeparator);const toActivate=listeners2?listeners2[pathStr]:void 0;let output,executionInfo={};if(toActivate){executionInfo=functionExecution(thisArg,toActivate,foo,argumentsList);output=executionInfo.output}else{output=foo.apply(thisArg,argumentsList);executionInfo=inspectable?.state?.[pathStr]?.value??{}}const callback=inspectable.options.callback;runCallback(callback,pathStr,executionInfo,output);return output}catch(e){console.warn(`Function failed:`,e,inspectable.path)}}}};var objects=function(){const inspectable=this;return{get(target,prop,receiver){if(prop===isProxy)return true;return Reflect.get(target,prop,receiver)},set(target,prop,newVal,receiver){if(prop===isProxy)return true;const pathStr=[...inspectable.path,prop].join(inspectable.options.keySeparator);const isFromProxy=newVal?.[isProxy];const isFromInspectable=newVal?.[fromInspectable];if(isFromInspectable)newVal=newVal.value;const listeners2=inspectable.listeners.setters;const desc=Object.getOwnPropertyDescriptor(target,prop);const createListener=desc&&!desc.get&&!desc.set;if(createListener){if(typeof inspectable.options.globalCallback==="function"){const id=inspectable.path[0];define_default.call(inspectable,prop,true);set("setters",pathStr,newVal,inspectable.options.globalCallback,{[id]:inspectable.root},inspectable.listeners,inspectable.options)}}if(newVal){const newProxy=inspectable.create(prop,target,newVal);if(newProxy)newVal=newProxy}const toActivate=!isFromProxy;if(listeners2&&toActivate&&!inspectable.newKeys.has(prop)){const toActivate2=listeners2[pathStr];if(toActivate2)setterExecution(toActivate2,newVal)}const callback=inspectable.options.callback;const info2=inspectable?.state?.[pathStr]?.value??{};runCallback(callback,pathStr,info2,newVal);if(isFromInspectable||!toActivate)return true;else return Reflect.set(target,prop,newVal,receiver)}}};var canCreate=(parent,key,val)=>{try{if(val===void 0)val=parent[key]}catch(e){return e}const alreadyIs=parent[key]&&parent[key][isProxy];if(alreadyIs)return false;const type=typeof val;const isObject=type==="object";const isFunction=type=="function";const notObjOrFunc=!val||!(isObject||isFunction);if(notObjOrFunc)return false;if(val instanceof Element)return false;if(val instanceof EventTarget)return false;const isESM=isObject&&esm(val);if(isFunction)return true;else{const desc=Object.getOwnPropertyDescriptor(parent,key);if(desc&&(desc.value&&desc.writable||desc.set)){if(!isESM)return true}else if(!parent.hasOwnProperty(key))return true}return false};var Inspectable=class{constructor(target={},opts={},name,parent){this.path=[];this.listeners={};this.newKeys=new Set;this.state={};this.set=(path,info2,update)=>{this.state[path]={output:update,value:info2};setFromPath(path,update,this.proxy,{create:true})};this.check=canCreate;this.create=(key,parent2,val,set2=false)=>{const create=this.check(parent2,key,val);if(val===void 0)val=parent2[key];if(create&&!(create instanceof Error)){parent2[key]=new Inspectable(val,this.options,key,this);return parent2[key]}if(set2){try{this.proxy[key]=val??parent2[key]}catch(e){const isESM=esm(parent2);const path=[...this.path,key];console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM?" because the parent is an ESM.":""}`,isESM?"":e)}}return};if(!opts.pathFormat)opts.pathFormat="relative";if(!opts.keySeparator)opts.keySeparator=keySeparator;if(target.__proxy)this.proxy=target.__proxy;else if(target[isProxy])this.proxy=target;else{this.target=target;this.options=opts;this.parent=parent;if(this.parent){this.root=this.parent.root;this.path=[...this.parent.path];this.state=this.parent.state??{}}else this.root=target;if(name)this.path.push(name);if(this.options.listeners)this.listeners=this.options.listeners;if(this.options.path){if(this.options.path instanceof Function)this.path=this.options.path(this.path);else if(Array.isArray(this.options.path))this.path=this.options.path;else console.log("Invalid path",this.options.path)}if(this.path)this.path=this.path.filter(str=>typeof str==="string");if(!this.options.keySeparator)this.options.keySeparator=keySeparator;let type=this.options.type;if(type!="object")type=typeof target==="function"?"function":"object";const handler2=handlers_exports[`${type}s`].call(this);this.proxy=new Proxy(target,handler2);Object.defineProperty(target,"__proxy",{value:this.proxy,enumerable:false});Object.defineProperty(target,"__esInspectable",{value:this,enumerable:false});for(let key in target)define_default.call(this,key)}return this.proxy}};var setFromOptions=(path,value,baseOptions,opts)=>{const ref=opts.reference;const id=Array.isArray(path)?path[0]:typeof path==="string"?path.split(baseOptions.keySeparator)[0]:path;let isDynamic=opts.hasOwnProperty("static")?!opts.static:false;if(isDynamic&&!globalThis.Proxy){isDynamic=false;console.warn("Falling back to using function interception and setters...")}if(isDynamic){value=new Inspectable(value,{pathFormat:baseOptions.pathFormat,keySeparator:baseOptions.keySeparator,listeners:opts.listeners,path:path2=>path2.filter(str=>!baseOptions.fallbacks||!baseOptions.fallbacks.includes(str))},id)}let options={keySeparator:baseOptions.keySeparator,...opts};setFromPath(path,value,ref,options);return value};var info=(id,callback,path,originalValue,base,listeners2,options,refShortcut={})=>{if(typeof path==="string")path=path.split(options.keySeparator);const relativePath=path.join(options.keySeparator);const refs=base;const shortcutRef=refShortcut.ref;const shortcutPath=refShortcut.path;const get3=path2=>{const thisBase=shortcutRef??base;const res=getFromPath(thisBase,path2,{keySeparator:options.keySeparator,fallbacks:options.fallbacks});return res};const set2=(path2,value)=>{const thisBase=shortcutRef??base;setFromOptions(path2,value,options,{reference:thisBase,listeners:listeners2})};let onUpdate=options.onUpdate;let infoToOutput={};if(onUpdate&&typeof onUpdate==="object"&&onUpdate.callback instanceof Function){infoToOutput=onUpdate.info??{};onUpdate=onUpdate.callback}const absolute=[id,...path];let pathInfo={absolute,relative:relativePath.split(options.keySeparator),parent:absolute.slice(0,-1)};pathInfo.output=pathInfo[options.pathFormat];const completePathInfo=pathInfo;const info2={id,path:completePathInfo,keySeparator:options.keySeparator,infoToOutput,callback:(...args)=>{const output=callback(...args);if(onUpdate instanceof Function)onUpdate(...args);return output},get current(){return get3(shortcutPath??info2.path.absolute)},set current(val){set2(shortcutPath??info2.path.absolute,val)},get parent(){return get3(shortcutPath?shortcutPath?.slice(0,-1):info2.path.parent)},get reference(){return refs[id]},set reference(val){refs[id]=val},original:originalValue,history:typeof originalValue==="object"?Object.assign({},originalValue):originalValue,sub:Symbol("subscription"),last:path.slice(-1)[0]};return info2};var registerInLookup=(name,sub,lookups)=>{if(lookups){const id=Math.random();lookups.symbol[sub]={name,id};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id]=sub}};var register=(info2,collection,lookups)=>{const absolute=getPath("absolute",info2);if(!collection[absolute])collection[absolute]={};collection[absolute][info2.sub]=info2;registerInLookup(absolute,info2.sub,lookups);return true};var listeners={functions:functions2,setters};var set=(type,absPath,value,callback,base,allListeners,options)=>{const{id,path}=getPathInfo(absPath,options);const fullInfo=info(id,callback,path,value,base,listeners,options);if(listeners[type])listeners[type](fullInfo,allListeners[type],allListeners.lookup);else{const path2=getPath("absolute",fullInfo);allListeners[type][path2][fullInfo.sub]=fullInfo;if(allListeners.lookup)registerInLookup(path2,fullInfo.sub,allListeners.lookup)}};var get2=(info2,collection)=>collection[getPath("absolute",info2)];var handler=(info2,collection,subscribeCallback,lookups)=>{let success=!!get2(info2,collection);if(!success){let parent=info2.parent;let val=parent?.[info2.last];success=subscribeCallback(val,parent)}return register(info2,collection,lookups)};var setterExecution=(listeners2,value)=>{return iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,{},value)})};function setters(info2,collection,lookups){const thisValue=this;return handler(info2,collection["setters"],(value,parent)=>{let val=value;if(!parent)return;if(!parent[isProxy]){let redefine=true;try{delete parent[info2.last]}catch(e){console.error("Unable to redeclare setters. May already be a dynamic object...");redefine=false}if(redefine){try{Object.defineProperty(parent,info2.last,{get:()=>val,set:async v=>{const isFunction=typeof val==="function";val=v;if(!isFunction){const listeners2=Object.assign({},collection["setters"][getPath("absolute",info2)]);setterExecution(listeners2,v)}else val=getProxyFunction.call(thisValue,info2,collection,val)},enumerable:true,configurable:true})}catch(e){throw e}}}},lookups)}function getProxyFunction(info2,collection,fn){return function(...args){const listeners2=collection["functions"][getPath("absolute",info2)];return functionExecution(this,listeners2,fn??info2.original,args)}}var functionExecution=(context,listeners2,func,args)=>{listeners2=Object.assign({},listeners2);const keys=Object.getOwnPropertySymbols(listeners2);const infoTemplate=listeners2[keys[0]]??{};const executionInfo=get((...args2)=>func.call(context,...args2),args,infoTemplate.infoToOutput);iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,executionInfo.value,executionInfo.output)});return executionInfo};function functions2(info2,collection,lookups){return handler(info2,collection["functions"],(_,parent)=>{if(!parent[isProxy]){parent[info2.last]=getProxyFunction.call(this,info2,collection);return setters(info2,collection,lookups)}},lookups)}var drillSimple=(obj,callback,options)=>{let accumulator=options.accumulator;if(!accumulator)accumulator=options.accumulator={};const ignore=options.ignore||[];const path=options.path||[];const condition=options.condition||true;const seen=[];const fromSeen=[];let drill=(obj2,acc={},globalInfo)=>{for(let key in obj2){if(ignore.includes(key))continue;const val=obj2[key];const newPath=[...globalInfo.path,key];const info2={typeof:typeof val,name:val?.constructor?.name,simple:true,object:val&&typeof val==="object",path:newPath};if(info2.object){const name=info2.name;const isESM=esm(val);if(isESM||name==="Object"||name==="Array"){info2.simple=true;const idx=seen.indexOf(val);if(idx!==-1)acc[key]=fromSeen[idx];else{seen.push(val);const pass=condition instanceof Function?condition(key,val,info2):condition;info2.pass=pass;acc[key]=callback(key,val,info2);if(pass){fromSeen.push(acc[key]);acc[key]=drill(val,acc[key],{...globalInfo,path:newPath})}}}else{info2.simple=false;acc[key]=callback(key,val,info2)}}else acc[key]=callback(key,val,info2)}return acc};return drill(obj,accumulator,{path})};var createLookup=()=>{return{symbol:{},name:{}}};var Monitor=class{constructor(opts={}){this.poller=new Poller;this.options={pathFormat:"relative",keySeparator};this.listeners={polling:this.poller.listeners,functions:{},setters:{},lookup:createLookup()};this.references={};this.get=(path,output,reference=this.references,throwError=true)=>{return getFromPath(reference,path,{keySeparator:this.options.keySeparator,fallbacks:this.options.fallbacks,output},throwError)};this.set=(path,value,opts2={})=>{const optsCopy={...opts2};if(!optsCopy.reference)optsCopy.reference=this.references;if(!optsCopy.listeners)optsCopy.listeners=this.listeners;return setFromOptions(path,value,this.options,optsCopy)};this.on=(absPath,callback)=>{const info2=getPathInfo(absPath,this.options);return this.listen(info2.id,callback,info2.path)};this.getInfo=(label,callback,path,original)=>{const info2=info(label,callback,path,original,this.references,this.listeners,this.options);const id=Math.random();const lookups=this.listeners.lookup;const name=getPath("absolute",info2);lookups.symbol[info2.sub]={name,id};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id]=info2.sub;return info2};this.listen=(id,callback,path=[],__internal={})=>{if(typeof path==="string")path=path.split(this.options.keySeparator);else if(typeof path==="symbol")path=[path];const arrayPath=path;let baseRef=this.get(id);if(!baseRef){console.error(`Reference does not exist.`,id);return}if(!__internal.poll)__internal.poll=esm(baseRef);if(!__internal.seen)__internal.seen=[];const __internalComplete=__internal;const thisPath=[id,...arrayPath];const ref=this.get(thisPath);const toMonitorInternally=(val,allowArrays=false)=>{const first=val&&typeof val==="object";if(!first)return false;const isEl=val instanceof Element;if(isEl)return false;if(allowArrays)return true;else return!Array.isArray(val)};let subs={};const subscribeAll=toMonitorInternally(ref,true);if(subscribeAll){if(ref.__esInspectable)ref.__esInspectable.options.globalCallback=callback;drillSimple(ref,(_,__,drillInfo)=>{if(drillInfo.pass)return;else{const fullPath=[...arrayPath,...drillInfo.path];const internalSubs=this.listen(id,callback,fullPath,__internalComplete);Object.assign(subs,internalSubs)}},{condition:(_,val)=>toMonitorInternally(val)})}let info2;let success=false;try{info2=this.getInfo(id,callback,arrayPath,ref);if(info2){if(__internalComplete.poll)success=this.poller.add(info2);else{let type="setters";if(typeof ref==="function")type="functions";success=this.add(type,info2)}}}catch(e){console.error("Fallback to polling:",path,e);success=this.poller.add(info2)}if(success){subs[getPath("absolute",info2)]=info2.sub;if(this.options.onInit instanceof Function){const executionInfo={};for(let key in info2.infoToOutput)executionInfo[key]=void 0;this.options.onInit(getPath("output",info2),executionInfo)}return subs}else{console.error("Failed to subscribe to:",path);return}};this.add=(type,info2)=>{if(listeners_exports[type])return listeners_exports[type](info2,this.listeners,this.listeners.lookup);else{this.listeners[type][getPath("absolute",info2)][info2.sub]=info2;return true}};this.remove=subs=>{if(!subs){subs={...this.listeners.functions,...this.listeners.setters,...this.listeners.polling}}if(typeof subs!=="object")subs={sub:subs};for(let key in subs){let innerSub=subs[key];const handleUnsubscribe=sub=>{const res=this.unsubscribe(sub);if(res===false)console.warn(`Subscription for ${key} does not exist.`,sub)};if(typeof innerSub!=="symbol")iterateSymbols(innerSub,handleUnsubscribe);else handleUnsubscribe(innerSub)}return true};this.unsubscribe=sub=>{const info2=this.listeners.lookup.symbol[sub];const absPath=info2.name;const polling=this.poller.get(sub);const funcs=this.listeners.functions[absPath];const func=funcs?.[sub];const setters2=this.listeners.setters[absPath];const setter=setters2?.[sub];if(polling)this.poller.remove(sub);else if(func){delete funcs[sub];if(!Object.getOwnPropertySymbols(funcs).length){Object.defineProperty(func.parent,func.last,{value:func.original,writable:true});delete this.listeners.functions[absPath]}}else if(setter){delete setters2[sub];if(!Object.getOwnPropertySymbols(setters2).length){const parent=setter.parent;if(parent){const last=setter.last;const value=parent[last];Object.defineProperty(parent,last,{value,writable:true})}delete this.listeners.setters[absPath]}}else return false;delete this.listeners.lookup.symbol[sub];const nameLookup=this.listeners.lookup.name[info2.name];delete nameLookup[info2.id];if(!Object.getOwnPropertyNames(nameLookup).length)delete this.listeners.lookup.name[info2.name]};Object.defineProperty(this.listeners,"lookup",{value:createLookup(),enumerable:false,configurable:false});Object.assign(this.options,opts);this.poller.setOptions(opts.polling)}};var src_default=Monitor;var defaultPath="default";var operatorPath="__operator";var specialKeys={path:"__path",isGraphScript:"__",listeners:{value:"__listeners",branch:"__branch",bind:"__bind",trigger:"__trigger",format:"__format"}};var listenerObject=Symbol("listenerObject");var toSet=Symbol("toSet");var subscriptionKey=Symbol("subscriptionKey");var configKey=Symbol("configKey");var toResolveWithKey=Symbol("toResolveWithKey");var isConfigObject=o=>specialKeys.listeners.format in o||specialKeys.listeners.branch in o||specialKeys.listeners.trigger in o||specialKeys.listeners.bind in o;var initializedStatus="INITIALIZED";var registeredStatus="REGISTERED";var globalFrom={};var globalTo={};var globalActive={};var _triggers,_queue,_toResolveWith,_initialize,_getAbsolutePath,_getPathInfo;var Edgelord=class{constructor(listeners2,root,context){this.original={};this.active={};this.globals={};this.context={options:{}};this.rootPath="";this.status="";__privateAdd(this,_triggers,[]);__privateAdd(this,_queue,[]);__privateAdd(this,_toResolveWith,void 0);this.setInitialProperties=(listeners2={},root,context={})=>{Object.assign(this.context,context);if(root)this.rootPath=root;if(!this.context.options.keySeparator)this.context.options.keySeparator=this.context.monitor.options.keySeparator;this.original=listeners2;const globals=[{name:"active",ref:globalActive},{name:"from",ref:globalFrom},{name:"to",ref:globalTo}];globals.forEach(o=>{if(!o.ref[this.context.id])o.ref[this.context.id]={};this.globals[o.name]=o.ref[this.context.id]});__privateSet(this,_toResolveWith,this.getManager());this.runEachListener(listeners2,this.addToGlobalLog)};this.getManager=(mode="from")=>{let target=mode==="to"?this.globals.to:this.globals.from;this.rootPath.split(this.context.options.keySeparator).forEach(key=>{if(!target[key])target[key]={};target=target[key]});return target[toResolveWithKey]??this};this.onStart=f=>{const res=__privateGet(this,_toResolveWith);const isSame2=res===this;if(isSame2){if(this.status===initializedStatus)f();else __privateGet(this,_queue).push(f)}else res.onStart(f)};this.runEachListener=(listeners2,callback)=>{if(!callback)return;for(const first in listeners2){const second=listeners2[first];if(!second){console.warn("Skipping empty listener:",first);continue}if(second&&typeof second==="object"){const from=second;const to=first;for(let fromPath in from){callback(fromPath,to,from[fromPath])}}else{const from=first;const to=second;const typeOf=typeof to;if(typeOf==="function")callback(from,"",to);else if(typeOf==="string")callback(from,to,to);else console.error("Improperly Formatted Listener",to)}}};this.register=(listeners2=this.original)=>{this.runEachListener(listeners2,this.add);this.status=registeredStatus};__privateAdd(this,_initialize,o=>{const res=this.context.monitor.get(o.path,"info");if(typeof res.value==="function"){const args=Array.isArray(o.args)?o.args:[o.args];res.value(...args)}else console.error("Cannot yet trigger values...",o)});this.initialize=o=>{if(!this.status)__privateGet(this,_triggers).push(o);else if(this.status===registeredStatus){this.status=initializedStatus;__privateGet(this,_triggers).forEach(__privateGet(this,_initialize));__privateGet(this,_queue).forEach(f=>f());__privateSet(this,_queue,[]);__privateSet(this,_triggers,[])}else __privateGet(this,_initialize).call(this,o)};this.start=()=>{this.register();this.initialize()};__privateAdd(this,_getAbsolutePath,name=>{const sep=this.context.monitor.options.keySeparator;return!name||!this.rootPath||this.rootPath===name.slice(0,this.rootPath.length)&&name[this.rootPath.length]===sep?name:[this.rootPath,name].join(sep)});__privateAdd(this,_getPathInfo,path=>{const output={absolute:{},relative:{}};path=__privateGet(this,_getAbsolutePath).call(this,path);let rel=this.rootPath?path.replace(`${this.rootPath}.`,""):path;const baseArr=path.split(this.context.options.keySeparator);output.absolute.array=[this.context.id,...baseArr];output.relative.array=rel.split(this.context.options.keySeparator);let obj=this.context.monitor.get(output.relative.array,void 0,this.context.instance,false);if(this.context.graph){if(obj&&this.context.bound){output.absolute.array=[this.context.id,this.context.bound,...output.absolute.array.slice(1)];output.relative.array.unshift(this.context.bound)}else if(!obj){const rel2=output.relative.array.join(this.context.options.keySeparator);obj=this.context.graph.get(rel2)}}const isGraphScript=obj&&typeof obj==="object"&&specialKeys.isGraphScript in obj;if(isGraphScript){if(obj[operatorPath]){output.absolute.array.push(operatorPath);output.relative.array.push(operatorPath)}else if(obj[defaultPath]){output.absolute.array.push(defaultPath);output.relative.array.push(defaultPath)}}output.absolute.value=output.absolute.array.slice(1).join(this.context.options.keySeparator);output.relative.value=output.relative.array.join(this.context.options.keySeparator);return output});this.add=(from,to,value=true,subscription)=>{if(typeof to=="function"){value=to;to=""}else if(typeof to!=="string"){console.error("Improperly Formatted Listener",from,to,value);return}if(!value)return;const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const absPath=fromInfo.absolute.value;if(!subscription)subscription=this.globals.active[absPath]?.[subscriptionKey];if(!subscription){subscription=this.context.monitor.on(fromInfo.absolute.array,(path,_,update)=>this.activate(path,update),{ref:this.context.instance,path:fromInfo.relative.array})}if(typeof value=="string")value=toInfo.absolute.array.slice(1).join(this.context.options.keySeparator);const info2={value,[listenerObject]:true};const refs=[this.active,this.globals.active];refs.forEach(ref=>{if(!ref[absPath])ref[absPath]={};const base=ref[absPath];if(!base[subscriptionKey]){Object.defineProperty(base,subscriptionKey,{value:subscription,configurable:true})}base[toInfo.absolute.value]=info2});const args=value[specialKeys.listeners.trigger];if(args)__privateGet(this,_toResolveWith).initialize({path:fromInfo.absolute.array,args});this.addToGlobalLog(absPath);return info2};this.addToGlobalLog=(path,mode="from")=>{const absolutePath=__privateGet(this,_getAbsolutePath).call(this,path);let target=mode==="to"?this.globals.to:this.globals.from;const globalPath=absolutePath.split(this.context.options.keySeparator);globalPath.forEach(key=>{if(!target[key])target[key]={};target=target[key];if(!target[toResolveWithKey])target[toResolveWithKey]=this})};this.remove=(from,to)=>{const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const path=[fromInfo.absolute.value,toInfo.absolute.value];const toRemove=[{ref:this.active,path},{ref:this.globals.active,path,unlisten:true}];toRemove.forEach(o=>{const{ref,path:path2,unlisten}=o;let base=ref[path2[0]];if(typeof base==="object"){delete base[path2[1]];if(Object.keys(base).length===0){delete ref[path2[0]];const sub=base[subscriptionKey];if(unlisten&&sub){this.context.monitor.remove(sub)}delete base[subscriptionKey]}}else delete ref[path2[0]]})};this.clear=name=>{const value=__privateGet(this,_getAbsolutePath).call(this,name);Object.keys(this.active).forEach(from=>{Object.keys(this.active[from]).forEach(to=>{if(!value||from.slice(0,value.length)===value||to.slice(0,value.length)===value)this.remove(from,to)})})};this.has=(from,ref=this.active)=>!!ref[from];this.get=(from,ref=this.active)=>ref[from];this.activate=(from,update)=>{const listenerGroups=[{info:this.get(from,this.globals.active),name:from}];listenerGroups.forEach(group=>{const info2=group.info;if(info2){if(info2[listenerObject]){this.pass(from,{value:info2.value,parent:this.active,key:group.name,subscription:info2.subscription,__value:true},update)}else if(typeof info2==="object"){for(let key in info2){this.pass(from,{parent:info2,key,subscription:info2[key].subscription,value:info2[key].value},update)}}else console.error("Improperly Formatted Listener",info2)}})};this.pass=(from,target,update)=>{const id=this.context.id;const isValue=target?.__value;let parent=target.parent;let to=target.key;const info2=target.parent[to];target=info2.value;let config=info2?.[configKey];let ogValue=target;const type=typeof target;const checkIfSetter=(path,willSet)=>{const info3=this.context.monitor.get(path,"info");if(info3.exists){const val=info3.value;const noDefault=typeof val!=="function"&&!val?.default;const value=noDefault?toSet:val;const res={value};if(willSet){target=res.value;parent[to]=res}return res}else return{value:void 0}};const transform=willSet=>{const fullPath=[id];fullPath.push(...to.split(this.context.options.keySeparator));return checkIfSetter(fullPath,willSet)};const getPathArray=latest=>{const path=[id];const topPath=[];if(this.rootPath)topPath.push(...this.rootPath.split(this.context.options.keySeparator));topPath.push(...latest.split(this.context.options.keySeparator));path.push(...topPath);return path};if(typeof target==="boolean"){if(!isValue)transform(true);else console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`)}else if(type==="string"){const path=getPathArray(ogValue);checkIfSetter(path,true);if(isValue){parent[to]={[ogValue]:parent[to]};to=ogValue}}else if(target&&type==="object"){const isConfig=isConfigObject(ogValue);if(isConfig){if("value"in ogValue){if(isValue){target=parent[to]=ogValue.value}else{target=parent[to].value=ogValue.value}}else transform(true);if(ogValue){if(ogValue)config=ogValue}Object.defineProperty(parent[to],configKey,{value:config})}}let isValidInput=true;if(config){const bindKey=specialKeys.listeners.value;if(bindKey in config){const path=getPathArray(config[bindKey].original??config[bindKey]);if(typeof config[bindKey]==="string"){const res=this.context.monitor.get(path);if(!res)target=`because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.`;else{config[bindKey]={value:res,original:config[bindKey]}}}else if(!config[bindKey].value.__parent){target=`because ${config[bindKey].original??id.toString()} has become unparented.`}}else{const branchKey=specialKeys.listeners.branch;const formatKey=specialKeys.listeners.format;if(branchKey in config){const isValid=config[branchKey].find(o=>{let localValid=[];if("if"in o)localValid.push(o.if(update));if("is"in o)localValid.push(o.is===update);const isValidLocal=localValid.length>0&&localValid.reduce((a,b)=>a&&b,true);if(isValidLocal){if("value"in o)update=o.value}return isValidLocal});if(!isValid)isValidInput=false}if(formatKey in config){try{update=config[formatKey](update);if(update===void 0)isValidInput=false}catch(e){console.error("Failed to format arguments",e)}}}}if(isValidInput&&update!==void 0){const arrayUpdate=Array.isArray(update)?update:[update];if(target===toSet){const parentPath=[id];parentPath.push(...to.split(this.context.options.keySeparator));const idx=parentPath.pop();const info3=this.context.monitor.get(parentPath,"info");if(info3.value)info3.value[idx]=update;else console.error(`Cannot set value on ${parentPath.filter(str=>typeof str!=="symbol").join(this.context.options.keySeparator)} from ${from}`)}else if(target?.default)target.default.call(target,...arrayUpdate);else if(typeof target==="function"){const noContext=parent[to][listenerObject];if(noContext)target.call(config?.[specialKeys.listeners.bind]?.value??this.context.instance,...arrayUpdate);else target(...arrayUpdate)}else{let baseMessage=to?`listener: ${from} \u2014> ${to}`:`listener from ${from}`;if(parent){console.warn(`Deleting ${baseMessage}`,target);delete parent[to]}else console.error(`Failed to add ${baseMessage}`,target)}}};if(listeners2||root||context)this.setInitialProperties(listeners2,root,context)}};_triggers=new WeakMap;_queue=new WeakMap;_toResolveWith=new WeakMap;_initialize=new WeakMap;_getAbsolutePath=new WeakMap;_getPathInfo=new WeakMap;var edgelord_default=Edgelord;function applyLoader(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loader){const args=[node,parent,graph,tree,properties,tag];if(typeof loader==="object"){if(loader.init)loader(...args);if(loader.connected)node.__addOnconnected(loader.connect);if(loader.disconnected)node.__addOndisconnected(loader.disconnect)}else if(typeof loader==="function")loader(...args)}function applyLoaders(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loaders2=this.__node.loaders){for(const l in loaders2)applyLoader(node,parent,graph,tree,properties,tag,loaders2[l])}var _parent,_graph,_properties,_options,_applied,_applySetters;var GraphNode=class{constructor(properties,parent,graph,options){this.__=Symbol("graphscript");this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,ref:this,flow:new edgelord_default};__privateAdd(this,_parent,void 0);__privateAdd(this,_graph,void 0);__privateAdd(this,_properties,{});__privateAdd(this,_options,{});__privateAdd(this,_applied,[]);__privateAdd(this,_applySetters,(properties=__privateGet(this,_properties),proxy=__privateGet(this,_properties),ignore=[])=>{const isProxy2=proxy===true;let keys=Object.getOwnPropertyNames(properties);if(isProxy2){proxy=properties;keys=getAllPropertyNames(properties)}for(const key of keys){if(ignore.includes(key))continue;if(__privateGet(this,_applied).includes(key))continue;__privateGet(this,_applied).push(key);if(key==="__properties")Object.defineProperty(this,key,{get:()=>__privateGet(this,_properties),enumerable:true});else if(key==="__props"){Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>{proxy[key]=value;__privateGet(this,_applySetters).call(this,value,true)},enumerable:true,configurable:true})}else{Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>proxy[key]=value,enumerable:true,configurable:false})}}});this.____apply=__privateGet(this,_applySetters);this.__init=(properties,parent=__privateGet(this,_parent),graph=__privateGet(this,_graph),options=__privateGet(this,_options))=>{__privateSet(this,_parent,parent);__privateSet(this,_graph,graph);__privateSet(this,_options,options);if(properties){let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(typeof properties==="object"){if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}properties=properties.__node.tree}__privateSet(this,_properties,properties);if(!properties.__node)properties.__node={};if(!properties.__node.initial)this.__node.initial=orig;if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph)properties.__node.graph=graph;if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;properties.__node=Object.assign(this.__node,properties.__node);const ogProperties=properties;__privateGet(this,_applySetters).call(this);applyLoaders.call(graph,this,parent,graph,graph?.__node?.tree,properties);__privateGet(this,_applySetters).call(this,void 0,void 0,["__props"]);if(properties instanceof Graph)this.__node.source=properties;if(typeof options.onInit==="function")options.onInit();if(graph){const symbol=(graph.__node.ref??this).__;const monitor=graph.monitor;this.__node.flow.setInitialProperties(this.__listeners,void 0,{id:symbol,instance:this,monitor,graph,bound:this.__node.tag})}else console.error("No flow manager created for "+this.__node.tag)}}};this.__init(properties,parent,graph,options)}get __properties(){return __privateGet(this,_properties)}__addOnconnected(callback){if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o.call(this,this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o.call(this,this)})}}};_parent=new WeakMap;_graph=new WeakMap;_properties=new WeakMap;_options=new WeakMap;_applied=new WeakMap;_applySetters=new WeakMap;var _init;var _Graph=class{constructor(options){this.monitor=new src_default({keySeparator:".",fallbacks:["__children"]});this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,ref:new GraphNode,loaders:[props_loader_default]};this.init=options=>{if(options){if(options.loaders){this.setLoaders(options.loaders);delete options.loaders}recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};__privateAdd(this,_init,properties=>{const node=this.__node.ref;node.__init(properties,this,this,{onInit:()=>{this.monitor.set(node.__,node.__properties)}});return node});this.setTree=tree=>{const hasGraphscriptProperties=Object.keys(tree).find(str=>{const slice=str.slice(0,2);return slice==="__"&&str!=="__node"});if(!hasGraphscriptProperties)tree={__children:tree};if(!tree.__node)tree.__node={};this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners2=this.recursiveSet(cpy,this,void 0,tree);if(!tree.__node.tag)tree.__node.tag=this.__node.tag;const node=__privateGet(this,_init).call(this,tree);const children=node.__children;const copy=Object.assign({},children);if(children)listeners2=this.recursiveSet(copy,this,void 0,children);if(node.__listeners)listeners2[node.__node.tag]=node.__listeners;this.__node.nodes.forEach(n=>n.__node.flow.start());node.__callConnected();return cpy};this.setLoaders=(loaders2,replace)=>{console.error("Setting loaders",loaders2);if(replace)this.__node.loaders=loaders2;else{if(Array.isArray(this.__node.loaders)){if(Array.isArray(loaders2))this.__node.loaders=[...this.__node.loaders,...loaders2];else this.__node.loaders=[...this.__node.loaders,...Object.values(loaders2)]}else Object.assign(this.__node.loaders,loaders2)}return this.__node.loaders};this.add=(properties,parent)=>{let listeners2={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}node.__callConnected();return node}return};this.recursiveSet=(t,parent,listeners2={},origin=t)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent,this);this.set(node.__node.tag,node);t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}let parentNode=parent instanceof _Graph?parent.__node.ref:parent;parentNode.__addOnconnected(()=>node.__callConnected())}}return listeners2};this.remove=node=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];this.clearListeners(node);node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){const node2=t[key].__node.ref;this.clearListeners(node2);this.delete(node2.__node.tag);delete this.__node.tree[node2.__node.tag];this.delete(key);delete this.__node.tree[key];node2.__node.tag=node2.__node.tag.substring(node2.__node.tag.lastIndexOf(".")+1);this.clearListeners(node2);node2.__callDisconnected();if(node2.__children)recursiveRemove(node2.__children)}};if(node.__children)recursiveRemove(node.__children)}if(node?.__node.tag&&node?.__parent){node.__parent=void 0;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.clearListeners=node=>{this.unsubscribe(node);this.clear(node)};this.get=(tag,base)=>{if(base instanceof GraphNode)base=base.__node.tag;if(tag===this.__node.tag)return this.__node.ref;if(base){const relFrom=[base,tag].join(".");const got=this.get(relFrom);if(got)return got}return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(from,to,value=true,bound=this.__node.ref)=>{if(typeof from!=="string")from=from.__node.tag;if(typeof bound==="string")bound=this.get(bound);if(bound)bound.__node.flow.add(from,to,value)};this.unsubscribe=(node,from,to)=>this.clear(from,to,node);this.clear=(from,to,bound)=>{const nd=typeof bound==="string"?this.get(bound):bound;if(typeof from==="symbol")return this.__node.flow.remove(from);let fromString=from instanceof GraphNode?from.__node.tag:from;let toString=to instanceof GraphNode?to.__node.tag:to;const remove=n=>{const flow=n.__node.flow;toString?flow.remove(fromString,toString):flow.clear(fromString)};if(nd)remove(nd);else{remove(this.__node.ref);this.__node.nodes.forEach(remove)}};this.activate=(from,value)=>this.__node.ref.__node.flow.activate(from,value);this.setState=update=>{for(let key in update)this.activate(key,update)};this.init(options)}};var Graph=_Graph;_init=new WeakMap;function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllPropertyNames(obj){var props=[];do{if(obj.constructor.name==="Object")props.push(...Object.keys(obj));else Object.getOwnPropertyNames(obj).forEach(function(prop){if(props.indexOf(prop)===-1)props.push(prop)})}while(obj=Object.getPrototypeOf(obj));return props}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode)graph.subscribe(parent.__node.tag,node.__node.tag)};var loop=(node,parent,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;const delay=(...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})};node.__operator=delay}else if(node.__node.frame===true){let fn=node.__operator;const frame=(...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})};node.__operator=frame}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;const repeat=async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result};node.__operator=repeat}if(node.__node.loop&&typeof node.__node.loop==="number"){let ogFunction=node.__operator;const looper=function(...args){if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){const res=ogFunction.call(node,...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop);return res}};node.__operator=looper;node.__addOnconnected(node2=>{if(node2.__node.looping)node2.__operator()});let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;const animate2=(...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn.call(node,...args);requestAnimationFrame(()=>{node.__operator(...args)})}return true};node.__operator=animate2;node.__addOnconnected(node2=>{if(node2.__node.animating||(!("animating"in node2.__node)||node2.__node.animating)&&node2.__animation)setTimeout(()=>{requestAnimationFrame(node2.__operator)},10)});node.__addOndisconnected(node2=>{if(node2.__node.animating)node2.__node.animating=false})}};var branching=(node,parent,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__operator=node.post}else if(!node.__operator&&typeof node.get=="function"){node.__operator=node.get}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set2=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set2(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var import_sjcl=__toESM(require_sjcl());var _HTTPfrontend=class extends Service{constructor(options,path,fetched){super(options);this.name="http";this.fetchProxied=false;this.listening={};this.GET=(url="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{let obj=message;if(typeof obj==="object"){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url);return this.POST(message,url)};this.transponder=(url,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url,data:message,responseType:type,onload:ev2=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};this.listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch,that,args){const result=fetch.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};this.stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}};this.setTree(this);this.listen(path,fetched)}};var HTTPfrontend=_HTTPfrontend;HTTPfrontend.request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler2]of entries){element.addEventListener(eventName,function(event){handler2(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners2=this.__listeners;if(listeners2[type]===void 0){listeners2[type]=[]}if(listeners2[type].indexOf(listener)===-1){listeners2[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners2=this.__listeners;return listeners2[type]!==void 0&&listeners2[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText2(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText2(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText2(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText2(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText2(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText2(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText2(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText2(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText2(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w=s.worker;let wpId;wpId=service.establishMessageChannel(w.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w.run("setValue",["routeProxy",s.route]);w.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w2=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w.worker,w2.worker);s.pipeTo.worker=w2}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w.run("setValue",["routeProxy",s.route]);service.transferFunction(w,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;Object.assign(this.__node.graph.ALGORITHMS[_id],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id)_id=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id)return;let res=this.__node.graph.ALGORITHMS[_id].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id]:res});return res}}}};if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope){const worker=new WorkerService({services:{workerCanvasRoutes,unsafeRoutes,Math,Math2}});console.log(worker)}var worker_default=self;})(); diff --git a/examples/basics/sync_async/index.html b/examples/workercanvas/index.html similarity index 100% rename from examples/basics/sync_async/index.html rename to examples/workercanvas/index.html diff --git a/examples/services/workers/workercanvas/index.ts b/examples/workercanvas/index.ts similarity index 97% rename from examples/services/workers/workercanvas/index.ts rename to examples/workercanvas/index.ts index e8efc071..d32ca43c 100644 --- a/examples/services/workers/workercanvas/index.ts +++ b/examples/workercanvas/index.ts @@ -6,7 +6,7 @@ import { WorkerCanvas, WorkerCanvasControls, HTMLNodeProperties -} from '../../../../index'//'graphscript' +} from '../../index'//'graphscript' import gsworker from './worker' @@ -24,7 +24,7 @@ const router = new Router({ console.log(router); -let ret = router.load({ +let ret = router.setTree({ 'main':{ tagName:'div', __children:{ diff --git a/examples/services/workers/workercanvas/package-lock.json b/examples/workercanvas/package-lock.json similarity index 99% rename from examples/services/workers/workercanvas/package-lock.json rename to examples/workercanvas/package-lock.json index ffdfcf4c..8df9d552 100644 --- a/examples/services/workers/workercanvas/package-lock.json +++ b/examples/workercanvas/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "tinybuildapp261", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "^0.0.157" } diff --git a/examples/services/workers/workercanvas/package.json b/examples/workercanvas/package.json similarity index 92% rename from examples/services/workers/workercanvas/package.json rename to examples/workercanvas/package.json index 2a8ad300..6855b641 100644 --- a/examples/services/workers/workercanvas/package.json +++ b/examples/workercanvas/package.json @@ -1,5 +1,5 @@ { - "name": "graphscript-workercanvas-example", + "name": "tinybuildapp261", "version": "0.0.0", "description": "Barebones esbuild and test node server implementation. For building", "main": "index.js", @@ -20,7 +20,7 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47" }, diff --git a/examples/services/workers/workercanvas/tinybuild.config.js b/examples/workercanvas/tinybuild.config.js similarity index 96% rename from examples/services/workers/workercanvas/tinybuild.config.js rename to examples/workercanvas/tinybuild.config.js index 2632c80c..44161dd9 100644 --- a/examples/services/workers/workercanvas/tinybuild.config.js +++ b/examples/workercanvas/tinybuild.config.js @@ -20,10 +20,10 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8081, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port + hotreload: 5001, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) diff --git a/examples/services/workers/workercanvas/worker.ts b/examples/workercanvas/worker.ts similarity index 73% rename from examples/services/workers/workercanvas/worker.ts rename to examples/workercanvas/worker.ts index 6743b34a..a752b4ca 100644 --- a/examples/services/workers/workercanvas/worker.ts +++ b/examples/workercanvas/worker.ts @@ -1,10 +1,10 @@ import { Math2 } from 'brainsatplay-math'; import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, //GPUService -} from '../../../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' +} from '../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' declare var WorkerGlobalScope; @@ -14,7 +14,7 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope services:{ //GPUService as any, workerCanvasRoutes, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading Math, Math2 } diff --git a/examples/workercanvas/yarn.lock b/examples/workercanvas/yarn.lock new file mode 100644 index 00000000..6fb88a92 --- /dev/null +++ b/examples/workercanvas/yarn.lock @@ -0,0 +1,39 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +better-sse@~0.8.0: + version "0.8.0" + resolved "https://registry.npmjs.org/better-sse/-/better-sse-0.8.0.tgz" + integrity sha512-ymOse8R0L+R2S1W85yOGkkc+yTzAmo52S4erjxPyBVwpqjpS+X228BG7hDwgKsGV/D51YhCYd+eaDwJ+sL5JhA== + +brainsatplay-math@~0.0.25: + version "0.0.25" + resolved "https://registry.npmjs.org/brainsatplay-math/-/brainsatplay-math-0.0.25.tgz" + integrity sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ== + +bson-objectid@~2.0.3: + version "2.0.3" + resolved "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.3.tgz" + integrity sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g== + +graphscript@~0.1.47: + version "0.1.50" + resolved "https://registry.npmjs.org/graphscript/-/graphscript-0.1.50.tgz" + integrity sha512-U3JFGAd52bwe96DBrU3YxYT54ofJ1uDwG2zY1QG0Nti/dh13HeNrZy5bxPkjGYprjw785ub8OeJMflaBMxzYLg== + dependencies: + better-sse "~0.8.0" + brainsatplay-math "~0.0.25" + bson-objectid "~2.0.3" + web-worker "~1.2.0" + ws "~8.9.0" + +web-worker@~1.2.0: + version "1.2.0" + resolved "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz" + integrity sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA== + +ws@~8.9.0: + version "8.9.0" + resolved "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz" + integrity sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg== diff --git a/examples/services/workers/workerthreejs/PickHelper.js b/examples/workerthreejs/PickHelper.js similarity index 100% rename from examples/services/workers/workerthreejs/PickHelper.js rename to examples/workerthreejs/PickHelper.js diff --git a/examples/workerthreejs/dist/index.js b/examples/workerthreejs/dist/index.js new file mode 100644 index 00000000..5c2fb98f --- /dev/null +++ b/examples/workerthreejs/dist/index.js @@ -0,0 +1,7032 @@ +(() => { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] + }) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw new Error('Dynamic require of "' + x + '" is not supported'); + }); + var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); + var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); + }; + var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); + }; + var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); + }; + var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; + }; + + // ../../services/e2ee/sjcl.js + var require_sjcl = __commonJS({ + "../../services/e2ee/sjcl.js"(exports, module) { + "use strict"; + var sjcl2 = { cipher: {}, hash: {}, keyexchange: {}, mode: {}, misc: {}, codec: {}, exception: { corrupt: function(a) { + this.toString = function() { + return "CORRUPT: " + this.message; + }; + this.message = a; + }, invalid: function(a) { + this.toString = function() { + return "INVALID: " + this.message; + }; + this.message = a; + }, bug: function(a) { + this.toString = function() { + return "BUG: " + this.message; + }; + this.message = a; + }, notReady: function(a) { + this.toString = function() { + return "NOT READY: " + this.message; + }; + this.message = a; + } } }; + sjcl2.cipher.aes = function(a) { + this.s[0][0][0] || this.O(); + var b, c, d, e, f = this.s[0][4], g = this.s[1]; + b = a.length; + var h = 1; + if (4 !== b && 6 !== b && 8 !== b) + throw new sjcl2.exception.invalid("invalid aes key size"); + this.b = [d = a.slice(0), e = []]; + for (a = b; a < 4 * b + 28; a++) { + c = d[a - 1]; + if (0 === a % b || 8 === b && 4 === a % b) + c = f[c >>> 24] << 24 ^ f[c >> 16 & 255] << 16 ^ f[c >> 8 & 255] << 8 ^ f[c & 255], 0 === a % b && (c = c << 8 ^ c >>> 24 ^ h << 24, h = h << 1 ^ 283 * (h >> 7)); + d[a] = d[a - b] ^ c; + } + for (b = 0; a; b++, a--) + c = d[b & 3 ? a : a - 4], e[b] = 4 >= a || 4 > b ? c : g[0][f[c >>> 24]] ^ g[1][f[c >> 16 & 255]] ^ g[2][f[c >> 8 & 255]] ^ g[3][f[c & 255]]; + }; + sjcl2.cipher.aes.prototype = { encrypt: function(a) { + return t(this, a, 0); + }, decrypt: function(a) { + return t(this, a, 1); + }, s: [[[], [], [], [], []], [[], [], [], [], []]], O: function() { + var a = this.s[0], b = this.s[1], c = a[4], d = b[4], e, f, g, h = [], k = [], l, n, m, p; + for (e = 0; 256 > e; e++) + k[(h[e] = e << 1 ^ 283 * (e >> 7)) ^ e] = e; + for (f = g = 0; !c[f]; f ^= l || 1, g = k[g] || 1) + for (m = g ^ g << 1 ^ g << 2 ^ g << 3 ^ g << 4, m = m >> 8 ^ m & 255 ^ 99, c[f] = m, d[m] = f, n = h[e = h[l = h[f]]], p = 16843009 * n ^ 65537 * e ^ 257 * l ^ 16843008 * f, n = 257 * h[m] ^ 16843008 * m, e = 0; 4 > e; e++) + a[e][f] = n = n << 24 ^ n >>> 8, b[e][m] = p = p << 24 ^ p >>> 8; + for (e = 0; 5 > e; e++) + a[e] = a[e].slice(0), b[e] = b[e].slice(0); + } }; + function t(a, b, c) { + if (4 !== b.length) + throw new sjcl2.exception.invalid("invalid aes block size"); + var d = a.b[c], e = b[0] ^ d[0], f = b[c ? 3 : 1] ^ d[1], g = b[2] ^ d[2]; + b = b[c ? 1 : 3] ^ d[3]; + var h, k, l, n = d.length / 4 - 2, m, p = 4, r = [0, 0, 0, 0]; + h = a.s[c]; + a = h[0]; + var q = h[1], v = h[2], w = h[3], x = h[4]; + for (m = 0; m < n; m++) + h = a[e >>> 24] ^ q[f >> 16 & 255] ^ v[g >> 8 & 255] ^ w[b & 255] ^ d[p], k = a[f >>> 24] ^ q[g >> 16 & 255] ^ v[b >> 8 & 255] ^ w[e & 255] ^ d[p + 1], l = a[g >>> 24] ^ q[b >> 16 & 255] ^ v[e >> 8 & 255] ^ w[f & 255] ^ d[p + 2], b = a[b >>> 24] ^ q[e >> 16 & 255] ^ v[f >> 8 & 255] ^ w[g & 255] ^ d[p + 3], p += 4, e = h, f = k, g = l; + for (m = 0; 4 > m; m++) + r[c ? 3 & -m : m] = x[e >>> 24] << 24 ^ x[f >> 16 & 255] << 16 ^ x[g >> 8 & 255] << 8 ^ x[b & 255] ^ d[p++], h = e, e = f, f = g, g = b, b = h; + return r; + } + sjcl2.bitArray = { bitSlice: function(a, b, c) { + a = sjcl2.bitArray.$(a.slice(b / 32), 32 - (b & 31)).slice(1); + return void 0 === c ? a : sjcl2.bitArray.clamp(a, c - b); + }, extract: function(a, b, c) { + var d = Math.floor(-b - c & 31); + return ((b + c - 1 ^ b) & -32 ? a[b / 32 | 0] << 32 - d ^ a[b / 32 + 1 | 0] >>> d : a[b / 32 | 0] >>> d) & (1 << c) - 1; + }, concat: function(a, b) { + if (0 === a.length || 0 === b.length) + return a.concat(b); + var c = a[a.length - 1], d = sjcl2.bitArray.getPartial(c); + return 32 === d ? a.concat(b) : sjcl2.bitArray.$(b, d, c | 0, a.slice(0, a.length - 1)); + }, bitLength: function(a) { + var b = a.length; + return 0 === b ? 0 : 32 * (b - 1) + sjcl2.bitArray.getPartial(a[b - 1]); + }, clamp: function(a, b) { + if (32 * a.length < b) + return a; + a = a.slice(0, Math.ceil(b / 32)); + var c = a.length; + b = b & 31; + 0 < c && b && (a[c - 1] = sjcl2.bitArray.partial(b, a[c - 1] & 2147483648 >> b - 1, 1)); + return a; + }, partial: function(a, b, c) { + return 32 === a ? b : (c ? b | 0 : b << 32 - a) + 1099511627776 * a; + }, getPartial: function(a) { + return Math.round(a / 1099511627776) || 32; + }, equal: function(a, b) { + if (sjcl2.bitArray.bitLength(a) !== sjcl2.bitArray.bitLength(b)) + return false; + var c = 0, d; + for (d = 0; d < a.length; d++) + c |= a[d] ^ b[d]; + return 0 === c; + }, $: function(a, b, c, d) { + var e; + e = 0; + for (void 0 === d && (d = []); 32 <= b; b -= 32) + d.push(c), c = 0; + if (0 === b) + return d.concat(a); + for (e = 0; e < a.length; e++) + d.push(c | a[e] >>> b), c = a[e] << 32 - b; + e = a.length ? a[a.length - 1] : 0; + a = sjcl2.bitArray.getPartial(e); + d.push(sjcl2.bitArray.partial(b + a & 31, 32 < b + a ? c : d.pop(), 1)); + return d; + }, i: function(a, b) { + return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; + }, byteswapM: function(a) { + var b, c; + for (b = 0; b < a.length; ++b) + c = a[b], a[b] = c >>> 24 | c >>> 8 & 65280 | (c & 65280) << 8 | c << 24; + return a; + } }; + sjcl2.codec.utf8String = { fromBits: function(a) { + var b = "", c = sjcl2.bitArray.bitLength(a), d, e; + for (d = 0; d < c / 8; d++) + 0 === (d & 3) && (e = a[d / 4]), b += String.fromCharCode(e >>> 8 >>> 8 >>> 8), e <<= 8; + return decodeURIComponent(escape(b)); + }, toBits: function(a) { + a = unescape(encodeURIComponent(a)); + var b = [], c, d = 0; + for (c = 0; c < a.length; c++) + d = d << 8 | a.charCodeAt(c), 3 === (c & 3) && (b.push(d), d = 0); + c & 3 && b.push(sjcl2.bitArray.partial(8 * (c & 3), d)); + return b; + } }; + sjcl2.codec.hex = { fromBits: function(a) { + var b = "", c; + for (c = 0; c < a.length; c++) + b += ((a[c] | 0) + 263882790666240).toString(16).substr(4); + return b.substr(0, sjcl2.bitArray.bitLength(a) / 4); + }, toBits: function(a) { + var b, c = [], d; + a = a.replace(/\s|0x/g, ""); + d = a.length; + a = a + "00000000"; + for (b = 0; b < a.length; b += 8) + c.push(parseInt(a.substr(b, 8), 16) ^ 0); + return sjcl2.bitArray.clamp(c, 4 * d); + } }; + sjcl2.codec.base32 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", X: "0123456789ABCDEFGHIJKLMNOPQRSTUV", BITS: 32, BASE: 5, REMAINING: 27, fromBits: function(a, b, c) { + var d = sjcl2.codec.base32.BASE, e = sjcl2.codec.base32.REMAINING, f = "", g = 0, h = sjcl2.codec.base32.B, k = 0, l = sjcl2.bitArray.bitLength(a); + c && (h = sjcl2.codec.base32.X); + for (c = 0; f.length * d < l; ) + f += h.charAt((k ^ a[c] >>> g) >>> e), g < d ? (k = a[c] << d - g, g += e, c++) : (k <<= d, g -= d); + for (; f.length & 7 && !b; ) + f += "="; + return f; + }, toBits: function(a, b) { + a = a.replace(/\s|=/g, "").toUpperCase(); + var c = sjcl2.codec.base32.BITS, d = sjcl2.codec.base32.BASE, e = sjcl2.codec.base32.REMAINING, f = [], g, h = 0, k = sjcl2.codec.base32.B, l = 0, n, m = "base32"; + b && (k = sjcl2.codec.base32.X, m = "base32hex"); + for (g = 0; g < a.length; g++) { + n = k.indexOf(a.charAt(g)); + if (0 > n) { + if (!b) + try { + return sjcl2.codec.base32hex.toBits(a); + } catch (p) { + } + throw new sjcl2.exception.invalid("this isn't " + m + "!"); + } + h > e ? (h -= e, f.push(l ^ n >>> h), l = n << c - h) : (h += d, l ^= n << c - h); + } + h & 56 && f.push(sjcl2.bitArray.partial(h & 56, l, 1)); + return f; + } }; + sjcl2.codec.base32hex = { fromBits: function(a, b) { + return sjcl2.codec.base32.fromBits(a, b, 1); + }, toBits: function(a) { + return sjcl2.codec.base32.toBits(a, 1); + } }; + sjcl2.codec.base64 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fromBits: function(a, b, c) { + var d = "", e = 0, f = sjcl2.codec.base64.B, g = 0, h = sjcl2.bitArray.bitLength(a); + c && (f = f.substr(0, 62) + "-_"); + for (c = 0; 6 * d.length < h; ) + d += f.charAt((g ^ a[c] >>> e) >>> 26), 6 > e ? (g = a[c] << 6 - e, e += 26, c++) : (g <<= 6, e -= 6); + for (; d.length & 3 && !b; ) + d += "="; + return d; + }, toBits: function(a, b) { + a = a.replace(/\s|=/g, ""); + var c = [], d, e = 0, f = sjcl2.codec.base64.B, g = 0, h; + b && (f = f.substr(0, 62) + "-_"); + for (d = 0; d < a.length; d++) { + h = f.indexOf(a.charAt(d)); + if (0 > h) + throw new sjcl2.exception.invalid("this isn't base64!"); + 26 < e ? (e -= 26, c.push(g ^ h >>> e), g = h << 32 - e) : (e += 6, g ^= h << 32 - e); + } + e & 56 && c.push(sjcl2.bitArray.partial(e & 56, g, 1)); + return c; + } }; + sjcl2.codec.base64url = { fromBits: function(a) { + return sjcl2.codec.base64.fromBits(a, 1, 1); + }, toBits: function(a) { + return sjcl2.codec.base64.toBits(a, 1); + } }; + sjcl2.hash.sha256 = function(a) { + this.b[0] || this.O(); + a ? (this.F = a.F.slice(0), this.A = a.A.slice(0), this.l = a.l) : this.reset(); + }; + sjcl2.hash.sha256.hash = function(a) { + return new sjcl2.hash.sha256().update(a).finalize(); + }; + sjcl2.hash.sha256.prototype = { blockSize: 512, reset: function() { + this.F = this.Y.slice(0); + this.A = []; + this.l = 0; + return this; + }, update: function(a) { + "string" === typeof a && (a = sjcl2.codec.utf8String.toBits(a)); + var b, c = this.A = sjcl2.bitArray.concat(this.A, a); + b = this.l; + a = this.l = b + sjcl2.bitArray.bitLength(a); + if (9007199254740991 < a) + throw new sjcl2.exception.invalid("Cannot hash more than 2^53 - 1 bits"); + if ("undefined" !== typeof Uint32Array) { + var d = new Uint32Array(c), e = 0; + for (b = 512 + b - (512 + b & 511); b <= a; b += 512) + u(this, d.subarray(16 * e, 16 * (e + 1))), e += 1; + c.splice(0, 16 * e); + } else + for (b = 512 + b - (512 + b & 511); b <= a; b += 512) + u(this, c.splice(0, 16)); + return this; + }, finalize: function() { + var a, b = this.A, c = this.F, b = sjcl2.bitArray.concat(b, [sjcl2.bitArray.partial(1, 1)]); + for (a = b.length + 2; a & 15; a++) + b.push(0); + b.push(Math.floor(this.l / 4294967296)); + for (b.push(this.l | 0); b.length; ) + u(this, b.splice(0, 16)); + this.reset(); + return c; + }, Y: [], b: [], O: function() { + function a(a2) { + return 4294967296 * (a2 - Math.floor(a2)) | 0; + } + for (var b = 0, c = 2, d, e; 64 > b; c++) { + e = true; + for (d = 2; d * d <= c; d++) + if (0 === c % d) { + e = false; + break; + } + e && (8 > b && (this.Y[b] = a(Math.pow(c, 0.5))), this.b[b] = a(Math.pow(c, 1 / 3)), b++); + } + } }; + function u(a, b) { + var c, d, e, f = a.F, g = a.b, h = f[0], k = f[1], l = f[2], n = f[3], m = f[4], p = f[5], r = f[6], q = f[7]; + for (c = 0; 64 > c; c++) + 16 > c ? d = b[c] : (d = b[c + 1 & 15], e = b[c + 14 & 15], d = b[c & 15] = (d >>> 7 ^ d >>> 18 ^ d >>> 3 ^ d << 25 ^ d << 14) + (e >>> 17 ^ e >>> 19 ^ e >>> 10 ^ e << 15 ^ e << 13) + b[c & 15] + b[c + 9 & 15] | 0), d = d + q + (m >>> 6 ^ m >>> 11 ^ m >>> 25 ^ m << 26 ^ m << 21 ^ m << 7) + (r ^ m & (p ^ r)) + g[c], q = r, r = p, p = m, m = n + d | 0, n = l, l = k, k = h, h = d + (k & l ^ n & (k ^ l)) + (k >>> 2 ^ k >>> 13 ^ k >>> 22 ^ k << 30 ^ k << 19 ^ k << 10) | 0; + f[0] = f[0] + h | 0; + f[1] = f[1] + k | 0; + f[2] = f[2] + l | 0; + f[3] = f[3] + n | 0; + f[4] = f[4] + m | 0; + f[5] = f[5] + p | 0; + f[6] = f[6] + r | 0; + f[7] = f[7] + q | 0; + } + sjcl2.mode.ccm = { name: "ccm", G: [], listenProgress: function(a) { + sjcl2.mode.ccm.G.push(a); + }, unListenProgress: function(a) { + a = sjcl2.mode.ccm.G.indexOf(a); + -1 < a && sjcl2.mode.ccm.G.splice(a, 1); + }, fa: function(a) { + var b = sjcl2.mode.ccm.G.slice(), c; + for (c = 0; c < b.length; c += 1) + b[c](a); + }, encrypt: function(a, b, c, d, e) { + var f, g = b.slice(0), h = sjcl2.bitArray, k = h.bitLength(c) / 8, l = h.bitLength(g) / 8; + e = e || 64; + d = d || []; + if (7 > k) + throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes"); + for (f = 2; 4 > f && l >>> 8 * f; f++) + ; + f < 15 - k && (f = 15 - k); + c = h.clamp(c, 8 * (15 - f)); + b = sjcl2.mode.ccm.V(a, b, c, d, e, f); + g = sjcl2.mode.ccm.C(a, g, c, b, e, f); + return h.concat(g.data, g.tag); + }, decrypt: function(a, b, c, d, e) { + e = e || 64; + d = d || []; + var f = sjcl2.bitArray, g = f.bitLength(c) / 8, h = f.bitLength(b), k = f.clamp(b, h - e), l = f.bitSlice(b, h - e), h = (h - e) / 8; + if (7 > g) + throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes"); + for (b = 2; 4 > b && h >>> 8 * b; b++) + ; + b < 15 - g && (b = 15 - g); + c = f.clamp(c, 8 * (15 - b)); + k = sjcl2.mode.ccm.C(a, k, c, l, e, b); + a = sjcl2.mode.ccm.V(a, k.data, c, d, e, b); + if (!f.equal(k.tag, a)) + throw new sjcl2.exception.corrupt("ccm: tag doesn't match"); + return k.data; + }, na: function(a, b, c, d, e, f) { + var g = [], h = sjcl2.bitArray, k = h.i; + d = [h.partial(8, (b.length ? 64 : 0) | d - 2 << 2 | f - 1)]; + d = h.concat(d, c); + d[3] |= e; + d = a.encrypt(d); + if (b.length) + for (c = h.bitLength(b) / 8, 65279 >= c ? g = [h.partial(16, c)] : 4294967295 >= c && (g = h.concat([h.partial(16, 65534)], [c])), g = h.concat(g, b), b = 0; b < g.length; b += 4) + d = a.encrypt(k(d, g.slice(b, b + 4).concat([0, 0, 0]))); + return d; + }, V: function(a, b, c, d, e, f) { + var g = sjcl2.bitArray, h = g.i; + e /= 8; + if (e % 2 || 4 > e || 16 < e) + throw new sjcl2.exception.invalid("ccm: invalid tag length"); + if (4294967295 < d.length || 4294967295 < b.length) + throw new sjcl2.exception.bug("ccm: can't deal with 4GiB or more data"); + c = sjcl2.mode.ccm.na(a, d, c, e, g.bitLength(b) / 8, f); + for (d = 0; d < b.length; d += 4) + c = a.encrypt(h(c, b.slice(d, d + 4).concat([0, 0, 0]))); + return g.clamp(c, 8 * e); + }, C: function(a, b, c, d, e, f) { + var g, h = sjcl2.bitArray; + g = h.i; + var k = b.length, l = h.bitLength(b), n = k / 50, m = n; + c = h.concat([h.partial(8, f - 1)], c).concat([0, 0, 0]).slice(0, 4); + d = h.bitSlice(g(d, a.encrypt(c)), 0, e); + if (!k) + return { tag: d, data: [] }; + for (g = 0; g < k; g += 4) + g > n && (sjcl2.mode.ccm.fa(g / k), n += m), c[3]++, e = a.encrypt(c), b[g] ^= e[0], b[g + 1] ^= e[1], b[g + 2] ^= e[2], b[g + 3] ^= e[3]; + return { tag: d, data: h.clamp(b, l) }; + } }; + sjcl2.mode.ocb2 = { name: "ocb2", encrypt: function(a, b, c, d, e, f) { + if (128 !== sjcl2.bitArray.bitLength(c)) + throw new sjcl2.exception.invalid("ocb iv must be 128 bits"); + var g, h = sjcl2.mode.ocb2.S, k = sjcl2.bitArray, l = k.i, n = [0, 0, 0, 0]; + c = h(a.encrypt(c)); + var m, p = []; + d = d || []; + e = e || 64; + for (g = 0; g + 4 < b.length; g += 4) + m = b.slice(g, g + 4), n = l(n, m), p = p.concat(l(c, a.encrypt(l(c, m)))), c = h(c); + m = b.slice(g); + b = k.bitLength(m); + g = a.encrypt(l(c, [0, 0, 0, b])); + m = k.clamp(l(m.concat([0, 0, 0]), g), b); + n = l(n, l(m.concat([0, 0, 0]), g)); + n = a.encrypt(l(n, l(c, h(c)))); + d.length && (n = l(n, f ? d : sjcl2.mode.ocb2.pmac(a, d))); + return p.concat(k.concat(m, k.clamp(n, e))); + }, decrypt: function(a, b, c, d, e, f) { + if (128 !== sjcl2.bitArray.bitLength(c)) + throw new sjcl2.exception.invalid("ocb iv must be 128 bits"); + e = e || 64; + var g = sjcl2.mode.ocb2.S, h = sjcl2.bitArray, k = h.i, l = [0, 0, 0, 0], n = g(a.encrypt(c)), m, p, r = sjcl2.bitArray.bitLength(b) - e, q = []; + d = d || []; + for (c = 0; c + 4 < r / 32; c += 4) + m = k(n, a.decrypt(k(n, b.slice(c, c + 4)))), l = k(l, m), q = q.concat(m), n = g(n); + p = r - 32 * c; + m = a.encrypt(k(n, [0, 0, 0, p])); + m = k(m, h.clamp(b.slice(c), p).concat([ + 0, + 0, + 0 + ])); + l = k(l, m); + l = a.encrypt(k(l, k(n, g(n)))); + d.length && (l = k(l, f ? d : sjcl2.mode.ocb2.pmac(a, d))); + if (!h.equal(h.clamp(l, e), h.bitSlice(b, r))) + throw new sjcl2.exception.corrupt("ocb: tag doesn't match"); + return q.concat(h.clamp(m, p)); + }, pmac: function(a, b) { + var c, d = sjcl2.mode.ocb2.S, e = sjcl2.bitArray, f = e.i, g = [0, 0, 0, 0], h = a.encrypt([0, 0, 0, 0]), h = f(h, d(d(h))); + for (c = 0; c + 4 < b.length; c += 4) + h = d(h), g = f(g, a.encrypt(f(h, b.slice(c, c + 4)))); + c = b.slice(c); + 128 > e.bitLength(c) && (h = f(h, d(h)), c = e.concat(c, [-2147483648, 0, 0, 0])); + g = f(g, c); + return a.encrypt(f(d(f(h, d(h))), g)); + }, S: function(a) { + return [a[0] << 1 ^ a[1] >>> 31, a[1] << 1 ^ a[2] >>> 31, a[2] << 1 ^ a[3] >>> 31, a[3] << 1 ^ 135 * (a[0] >>> 31)]; + } }; + sjcl2.mode.gcm = { name: "gcm", encrypt: function(a, b, c, d, e) { + var f = b.slice(0); + b = sjcl2.bitArray; + d = d || []; + a = sjcl2.mode.gcm.C(true, a, f, d, c, e || 128); + return b.concat(a.data, a.tag); + }, decrypt: function(a, b, c, d, e) { + var f = b.slice(0), g = sjcl2.bitArray, h = g.bitLength(f); + e = e || 128; + d = d || []; + e <= h ? (b = g.bitSlice(f, h - e), f = g.bitSlice(f, 0, h - e)) : (b = f, f = []); + a = sjcl2.mode.gcm.C(false, a, f, d, c, e); + if (!g.equal(a.tag, b)) + throw new sjcl2.exception.corrupt("gcm: tag doesn't match"); + return a.data; + }, ka: function(a, b) { + var c, d, e, f, g, h = sjcl2.bitArray.i; + e = [ + 0, + 0, + 0, + 0 + ]; + f = b.slice(0); + for (c = 0; 128 > c; c++) { + (d = 0 !== (a[Math.floor(c / 32)] & 1 << 31 - c % 32)) && (e = h(e, f)); + g = 0 !== (f[3] & 1); + for (d = 3; 0 < d; d--) + f[d] = f[d] >>> 1 | (f[d - 1] & 1) << 31; + f[0] >>>= 1; + g && (f[0] ^= -520093696); + } + return e; + }, j: function(a, b, c) { + var d, e = c.length; + b = b.slice(0); + for (d = 0; d < e; d += 4) + b[0] ^= 4294967295 & c[d], b[1] ^= 4294967295 & c[d + 1], b[2] ^= 4294967295 & c[d + 2], b[3] ^= 4294967295 & c[d + 3], b = sjcl2.mode.gcm.ka(b, a); + return b; + }, C: function(a, b, c, d, e, f) { + var g, h, k, l, n, m, p, r, q = sjcl2.bitArray; + m = c.length; + p = q.bitLength(c); + r = q.bitLength(d); + h = q.bitLength(e); + g = b.encrypt([0, 0, 0, 0]); + 96 === h ? (e = e.slice(0), e = q.concat(e, [1])) : (e = sjcl2.mode.gcm.j(g, [0, 0, 0, 0], e), e = sjcl2.mode.gcm.j(g, e, [0, 0, Math.floor(h / 4294967296), h & 4294967295])); + h = sjcl2.mode.gcm.j(g, [0, 0, 0, 0], d); + n = e.slice(0); + d = h.slice(0); + a || (d = sjcl2.mode.gcm.j(g, h, c)); + for (l = 0; l < m; l += 4) + n[3]++, k = b.encrypt(n), c[l] ^= k[0], c[l + 1] ^= k[1], c[l + 2] ^= k[2], c[l + 3] ^= k[3]; + c = q.clamp(c, p); + a && (d = sjcl2.mode.gcm.j(g, h, c)); + a = [Math.floor(r / 4294967296), r & 4294967295, Math.floor(p / 4294967296), p & 4294967295]; + d = sjcl2.mode.gcm.j(g, d, a); + k = b.encrypt(e); + d[0] ^= k[0]; + d[1] ^= k[1]; + d[2] ^= k[2]; + d[3] ^= k[3]; + return { tag: q.bitSlice(d, 0, f), data: c }; + } }; + sjcl2.misc.hmac = function(a, b) { + this.W = b = b || sjcl2.hash.sha256; + var c = [[], []], d, e = b.prototype.blockSize / 32; + this.w = [new b(), new b()]; + a.length > e && (a = b.hash(a)); + for (d = 0; d < e; d++) + c[0][d] = a[d] ^ 909522486, c[1][d] = a[d] ^ 1549556828; + this.w[0].update(c[0]); + this.w[1].update(c[1]); + this.R = new b(this.w[0]); + }; + sjcl2.misc.hmac.prototype.encrypt = sjcl2.misc.hmac.prototype.mac = function(a) { + if (this.aa) + throw new sjcl2.exception.invalid("encrypt on already updated hmac called!"); + this.update(a); + return this.digest(a); + }; + sjcl2.misc.hmac.prototype.reset = function() { + this.R = new this.W(this.w[0]); + this.aa = false; + }; + sjcl2.misc.hmac.prototype.update = function(a) { + this.aa = true; + this.R.update(a); + }; + sjcl2.misc.hmac.prototype.digest = function() { + var a = this.R.finalize(), a = new this.W(this.w[1]).update(a).finalize(); + this.reset(); + return a; + }; + sjcl2.misc.pbkdf2 = function(a, b, c, d, e) { + c = c || 1e4; + if (0 > d || 0 > c) + throw new sjcl2.exception.invalid("invalid params to pbkdf2"); + "string" === typeof a && (a = sjcl2.codec.utf8String.toBits(a)); + "string" === typeof b && (b = sjcl2.codec.utf8String.toBits(b)); + e = e || sjcl2.misc.hmac; + a = new e(a); + var f, g, h, k, l = [], n = sjcl2.bitArray; + for (k = 1; 32 * l.length < (d || 1); k++) { + e = f = a.encrypt(n.concat(b, [k])); + for (g = 1; g < c; g++) + for (f = a.encrypt(f), h = 0; h < f.length; h++) + e[h] ^= f[h]; + l = l.concat(e); + } + d && (l = n.clamp(l, d)); + return l; + }; + sjcl2.prng = function(a) { + this.c = [new sjcl2.hash.sha256()]; + this.m = [0]; + this.P = 0; + this.H = {}; + this.N = 0; + this.U = {}; + this.Z = this.f = this.o = this.ha = 0; + this.b = [0, 0, 0, 0, 0, 0, 0, 0]; + this.h = [0, 0, 0, 0]; + this.L = void 0; + this.M = a; + this.D = false; + this.K = { progress: {}, seeded: {} }; + this.u = this.ga = 0; + this.I = 1; + this.J = 2; + this.ca = 65536; + this.T = [0, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024]; + this.da = 3e4; + this.ba = 80; + }; + sjcl2.prng.prototype = { + randomWords: function(a, b) { + var c = [], d; + d = this.isReady(b); + var e; + if (d === this.u) + throw new sjcl2.exception.notReady("generator isn't seeded"); + if (d & this.J) { + d = !(d & this.I); + e = []; + var f = 0, g; + this.Z = e[0] = new Date().valueOf() + this.da; + for (g = 0; 16 > g; g++) + e.push(4294967296 * Math.random() | 0); + for (g = 0; g < this.c.length && (e = e.concat(this.c[g].finalize()), f += this.m[g], this.m[g] = 0, d || !(this.P & 1 << g)); g++) + ; + this.P >= 1 << this.c.length && (this.c.push(new sjcl2.hash.sha256()), this.m.push(0)); + this.f -= f; + f > this.o && (this.o = f); + this.P++; + this.b = sjcl2.hash.sha256.hash(this.b.concat(e)); + this.L = new sjcl2.cipher.aes(this.b); + for (d = 0; 4 > d && (this.h[d] = this.h[d] + 1 | 0, !this.h[d]); d++) + ; + } + for (d = 0; d < a; d += 4) + 0 === (d + 1) % this.ca && y(this), e = z(this), c.push(e[0], e[1], e[2], e[3]); + y(this); + return c.slice(0, a); + }, + setDefaultParanoia: function(a, b) { + if (0 === a && "Setting paranoia=0 will ruin your security; use it only for testing" !== b) + throw new sjcl2.exception.invalid("Setting paranoia=0 will ruin your security; use it only for testing"); + this.M = a; + }, + addEntropy: function(a, b, c) { + c = c || "user"; + var d, e, f = new Date().valueOf(), g = this.H[c], h = this.isReady(), k = 0; + d = this.U[c]; + void 0 === d && (d = this.U[c] = this.ha++); + void 0 === g && (g = this.H[c] = 0); + this.H[c] = (this.H[c] + 1) % this.c.length; + switch (typeof a) { + case "number": + void 0 === b && (b = 1); + this.c[g].update([d, this.N++, 1, b, f, 1, a | 0]); + break; + case "object": + c = Object.prototype.toString.call(a); + if ("[object Uint32Array]" === c) { + e = []; + for (c = 0; c < a.length; c++) + e.push(a[c]); + a = e; + } else + for ("[object Array]" !== c && (k = 1), c = 0; c < a.length && !k; c++) + "number" !== typeof a[c] && (k = 1); + if (!k) { + if (void 0 === b) + for (c = b = 0; c < a.length; c++) + for (e = a[c]; 0 < e; ) + b++, e = e >>> 1; + this.c[g].update([d, this.N++, 2, b, f, a.length].concat(a)); + } + break; + case "string": + void 0 === b && (b = a.length); + this.c[g].update([d, this.N++, 3, b, f, a.length]); + this.c[g].update(a); + break; + default: + k = 1; + } + if (k) + throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string"); + this.m[g] += b; + this.f += b; + h === this.u && (this.isReady() !== this.u && A("seeded", Math.max(this.o, this.f)), A("progress", this.getProgress())); + }, + isReady: function(a) { + a = this.T[void 0 !== a ? a : this.M]; + return this.o && this.o >= a ? this.m[0] > this.ba && new Date().valueOf() > this.Z ? this.J | this.I : this.I : this.f >= a ? this.J | this.u : this.u; + }, + getProgress: function(a) { + a = this.T[a ? a : this.M]; + return this.o >= a ? 1 : this.f > a ? 1 : this.f / a; + }, + startCollectors: function() { + if (!this.D) { + this.a = { loadTimeCollector: B(this, this.ma), mouseCollector: B(this, this.oa), keyboardCollector: B(this, this.la), accelerometerCollector: B(this, this.ea), touchCollector: B(this, this.qa) }; + if (window.addEventListener) + window.addEventListener("load", this.a.loadTimeCollector, false), window.addEventListener("mousemove", this.a.mouseCollector, false), window.addEventListener("keypress", this.a.keyboardCollector, false), window.addEventListener("devicemotion", this.a.accelerometerCollector, false), window.addEventListener("touchmove", this.a.touchCollector, false); + else if (document.attachEvent) + document.attachEvent("onload", this.a.loadTimeCollector), document.attachEvent("onmousemove", this.a.mouseCollector), document.attachEvent("keypress", this.a.keyboardCollector); + else + throw new sjcl2.exception.bug("can't attach event"); + this.D = true; + } + }, + stopCollectors: function() { + this.D && (window.removeEventListener ? (window.removeEventListener("load", this.a.loadTimeCollector, false), window.removeEventListener("mousemove", this.a.mouseCollector, false), window.removeEventListener("keypress", this.a.keyboardCollector, false), window.removeEventListener("devicemotion", this.a.accelerometerCollector, false), window.removeEventListener("touchmove", this.a.touchCollector, false)) : document.detachEvent && (document.detachEvent("onload", this.a.loadTimeCollector), document.detachEvent("onmousemove", this.a.mouseCollector), document.detachEvent("keypress", this.a.keyboardCollector)), this.D = false); + }, + addEventListener: function(a, b) { + this.K[a][this.ga++] = b; + }, + removeEventListener: function(a, b) { + var c, d, e = this.K[a], f = []; + for (d in e) + e.hasOwnProperty(d) && e[d] === b && f.push(d); + for (c = 0; c < f.length; c++) + d = f[c], delete e[d]; + }, + la: function() { + C(this, 1); + }, + oa: function(a) { + var b, c; + try { + b = a.x || a.clientX || a.offsetX || 0, c = a.y || a.clientY || a.offsetY || 0; + } catch (d) { + c = b = 0; + } + 0 != b && 0 != c && this.addEntropy([b, c], 2, "mouse"); + C(this, 0); + }, + qa: function(a) { + a = a.touches[0] || a.changedTouches[0]; + this.addEntropy([a.pageX || a.clientX, a.pageY || a.clientY], 1, "touch"); + C(this, 0); + }, + ma: function() { + C(this, 2); + }, + ea: function(a) { + a = a.accelerationIncludingGravity.x || a.accelerationIncludingGravity.y || a.accelerationIncludingGravity.z; + if (window.orientation) { + var b = window.orientation; + "number" === typeof b && this.addEntropy(b, 1, "accelerometer"); + } + a && this.addEntropy(a, 2, "accelerometer"); + C(this, 0); + } + }; + function A(a, b) { + var c, d = sjcl2.random.K[a], e = []; + for (c in d) + d.hasOwnProperty(c) && e.push(d[c]); + for (c = 0; c < e.length; c++) + e[c](b); + } + function C(a, b) { + "undefined" !== typeof window && window.performance && "function" === typeof window.performance.now ? a.addEntropy(window.performance.now(), b, "loadtime") : a.addEntropy(new Date().valueOf(), b, "loadtime"); + } + function y(a) { + a.b = z(a).concat(z(a)); + a.L = new sjcl2.cipher.aes(a.b); + } + function z(a) { + for (var b = 0; 4 > b && (a.h[b] = a.h[b] + 1 | 0, !a.h[b]); b++) + ; + return a.L.encrypt(a.h); + } + function B(a, b) { + return function() { + b.apply(a, arguments); + }; + } + sjcl2.random = new sjcl2.prng(6); + a: + try { + if (G = "undefined" !== typeof module && module.exports) { + try { + H = __require("crypto"); + } catch (a) { + H = null; + } + G = E = H; + } + if (G && E.randomBytes) + D = E.randomBytes(128), D = new Uint32Array(new Uint8Array(D).buffer), sjcl2.random.addEntropy(D, 1024, "crypto['randomBytes']"); + else if ("undefined" !== typeof window && "undefined" !== typeof Uint32Array) { + F = new Uint32Array(32); + if (window.crypto && window.crypto.getRandomValues) + window.crypto.getRandomValues(F); + else if (window.msCrypto && window.msCrypto.getRandomValues) + window.msCrypto.getRandomValues(F); + else + break a; + sjcl2.random.addEntropy(F, 1024, "crypto['getRandomValues']"); + } + } catch (a) { + "undefined" !== typeof window && window.console && (console.log("There was an error collecting entropy from the browser:"), console.log(a)); + } + var D; + var E; + var F; + var G; + var H; + sjcl2.json = { defaults: { v: 1, iter: 1e4, ks: 128, ts: 64, mode: "ccm", adata: "", cipher: "aes" }, ja: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl2.json, f = e.g({ iv: sjcl2.random.randomWords(4, 0) }, e.defaults), g; + e.g(f, c); + c = f.adata; + "string" === typeof f.salt && (f.salt = sjcl2.codec.base64.toBits(f.salt)); + "string" === typeof f.iv && (f.iv = sjcl2.codec.base64.toBits(f.iv)); + if (!sjcl2.mode[f.mode] || !sjcl2.cipher[f.cipher] || "string" === typeof a && 100 >= f.iter || 64 !== f.ts && 96 !== f.ts && 128 !== f.ts || 128 !== f.ks && 192 !== f.ks && 256 !== f.ks || 2 > f.iv.length || 4 < f.iv.length) + throw new sjcl2.exception.invalid("json encrypt: invalid parameters"); + "string" === typeof a ? (g = sjcl2.misc.cachedPbkdf2(a, f), a = g.key.slice(0, f.ks / 32), f.salt = g.salt) : sjcl2.ecc && a instanceof sjcl2.ecc.elGamal.publicKey && (g = a.kem(), f.kemtag = g.tag, a = g.key.slice(0, f.ks / 32)); + "string" === typeof b && (b = sjcl2.codec.utf8String.toBits(b)); + "string" === typeof c && (f.adata = c = sjcl2.codec.utf8String.toBits(c)); + g = new sjcl2.cipher[f.cipher](a); + e.g(d, f); + d.key = a; + f.ct = "ccm" === f.mode && sjcl2.arrayBuffer && sjcl2.arrayBuffer.ccm && b instanceof ArrayBuffer ? sjcl2.arrayBuffer.ccm.encrypt(g, b, f.iv, c, f.ts) : sjcl2.mode[f.mode].encrypt(g, b, f.iv, c, f.ts); + return f; + }, encrypt: function(a, b, c, d) { + var e = sjcl2.json, f = e.ja.apply(e, arguments); + return e.encode(f); + }, ia: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl2.json; + b = e.g(e.g(e.g({}, e.defaults), b), c, true); + var f, g; + f = b.adata; + "string" === typeof b.salt && (b.salt = sjcl2.codec.base64.toBits(b.salt)); + "string" === typeof b.iv && (b.iv = sjcl2.codec.base64.toBits(b.iv)); + if (!sjcl2.mode[b.mode] || !sjcl2.cipher[b.cipher] || "string" === typeof a && 100 >= b.iter || 64 !== b.ts && 96 !== b.ts && 128 !== b.ts || 128 !== b.ks && 192 !== b.ks && 256 !== b.ks || !b.iv || 2 > b.iv.length || 4 < b.iv.length) + throw new sjcl2.exception.invalid("json decrypt: invalid parameters"); + "string" === typeof a ? (g = sjcl2.misc.cachedPbkdf2(a, b), a = g.key.slice(0, b.ks / 32), b.salt = g.salt) : sjcl2.ecc && a instanceof sjcl2.ecc.elGamal.secretKey && (a = a.unkem(sjcl2.codec.base64.toBits(b.kemtag)).slice(0, b.ks / 32)); + "string" === typeof f && (f = sjcl2.codec.utf8String.toBits(f)); + g = new sjcl2.cipher[b.cipher](a); + f = "ccm" === b.mode && sjcl2.arrayBuffer && sjcl2.arrayBuffer.ccm && b.ct instanceof ArrayBuffer ? sjcl2.arrayBuffer.ccm.decrypt(g, b.ct, b.iv, b.tag, f, b.ts) : sjcl2.mode[b.mode].decrypt(g, b.ct, b.iv, f, b.ts); + e.g(d, b); + d.key = a; + return 1 === c.raw ? f : sjcl2.codec.utf8String.fromBits(f); + }, decrypt: function(a, b, c, d) { + var e = sjcl2.json; + return e.ia(a, e.decode(b), c, d); + }, encode: function(a) { + var b, c = "{", d = ""; + for (b in a) + if (a.hasOwnProperty(b)) { + if (!b.match(/^[a-z0-9]+$/i)) + throw new sjcl2.exception.invalid("json encode: invalid property name"); + c += d + '"' + b + '":'; + d = ","; + switch (typeof a[b]) { + case "number": + case "boolean": + c += a[b]; + break; + case "string": + c += '"' + escape(a[b]) + '"'; + break; + case "object": + c += '"' + sjcl2.codec.base64.fromBits(a[b], 0) + '"'; + break; + default: + throw new sjcl2.exception.bug("json encode: unsupported type"); + } + } + return c + "}"; + }, decode: function(a) { + a = a.replace(/\s/g, ""); + if (!a.match(/^\{.*\}$/)) + throw new sjcl2.exception.invalid("json decode: this isn't json!"); + a = a.replace(/^\{|\}$/g, "").split(/,/); + var b = {}, c, d; + for (c = 0; c < a.length; c++) { + if (!(d = a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i))) + throw new sjcl2.exception.invalid("json decode: this isn't json!"); + null != d[3] ? b[d[2]] = parseInt(d[3], 10) : null != d[4] ? b[d[2]] = d[2].match(/^(ct|adata|salt|iv)$/) ? sjcl2.codec.base64.toBits(d[4]) : unescape(d[4]) : null != d[5] && (b[d[2]] = "true" === d[5]); + } + return b; + }, g: function(a, b, c) { + void 0 === a && (a = {}); + if (void 0 === b) + return a; + for (var d in b) + if (b.hasOwnProperty(d)) { + if (c && void 0 !== a[d] && a[d] !== b[d]) + throw new sjcl2.exception.invalid("required parameter overridden"); + a[d] = b[d]; + } + return a; + }, sa: function(a, b) { + var c = {}, d; + for (d in a) + a.hasOwnProperty(d) && a[d] !== b[d] && (c[d] = a[d]); + return c; + }, ra: function(a, b) { + var c = {}, d; + for (d = 0; d < b.length; d++) + void 0 !== a[b[d]] && (c[b[d]] = a[b[d]]); + return c; + } }; + sjcl2.encrypt = sjcl2.json.encrypt; + sjcl2.decrypt = sjcl2.json.decrypt; + sjcl2.misc.pa = {}; + sjcl2.misc.cachedPbkdf2 = function(a, b) { + var c = sjcl2.misc.pa, d; + b = b || {}; + d = b.iter || 1e3; + c = c[a] = c[a] || {}; + d = c[d] = c[d] || { firstSalt: b.salt && b.salt.length ? b.salt.slice(0) : sjcl2.random.randomWords(2, 0) }; + c = void 0 === b.salt ? d.firstSalt : b.salt; + d[c] = d[c] || sjcl2.misc.pbkdf2(a, c, b.iter); + return { key: d[c].slice(0), salt: c.slice(0) }; + }; + "undefined" !== typeof module && module.exports && (module.exports = sjcl2); + "function" === typeof define && define([], function() { + return sjcl2; + }); + } + }); + + // ../../node_modules/web-worker/cjs/browser.js + var require_browser = __commonJS({ + "../../node_modules/web-worker/cjs/browser.js"(exports, module) { + module.exports = Worker; + } + }); + + // ../../core/loaders/props/props.loader.ts + var props_loader_default = (node) => { + if (node.__properties.__props) + node.____apply(node.__properties.__props, true); + }; + + // ../../core/libraries/esmonitor/dist/index.esm.js + var __defProp2 = Object.defineProperty; + var __export = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); + }; + var moduleStringTag = "[object Module]"; + var esm = (object) => { + const res = object && (!!Object.keys(object).reduce((a, b) => { + const desc = Object.getOwnPropertyDescriptor(object, b); + const isModule = desc && desc.get && !desc.set ? 1 : 0; + return a + isModule; + }, 0) || Object.prototype.toString.call(object) === moduleStringTag); + return !!res; + }; + var isSame = (a, b) => { + if (a && typeof a === "object" && b && typeof b === "object") { + const jA = JSON.stringify(a); + const jB = JSON.stringify(b); + return jA === jB; + } else + return a === b; + }; + var iterateSymbols = (obj, callback) => { + return Promise.all(Object.getOwnPropertySymbols(obj).map((sym) => callback(sym, obj[sym]))); + }; + var getPath = (type, info2) => { + const pathType = info2.path[type]; + if (!pathType) + throw new Error("Invalid Path Type"); + const filtered = pathType.filter((v) => typeof v === "string"); + return filtered.join(info2.keySeparator); + }; + var getPathInfo = (path, options) => { + let splitPath = path; + if (typeof path === "string") + splitPath = path.split(options.keySeparator); + else if (typeof path === "symbol") + splitPath = [path]; + return { + id: splitPath[0], + path: splitPath.slice(1) + }; + }; + var runCallback = (callback, path, info2, output, setGlobal = true) => { + if (callback instanceof Function) { + if (output && typeof output === "object" && typeof output.then === "function") + output.then((value) => callback(path, info2, value)); + else + callback(path, info2, output); + } + if (setGlobal && globalThis.ESMonitorState) { + const callback2 = globalThis.ESMonitorState.callback; + globalThis.ESMonitorState.state[path] = { output, value: info2 }; + runCallback(callback2, path, info2, output, false); + } + }; + var defaultSamplingRate = 60; + var _pollingId, _sps, _a; + var Poller = (_a = class { + constructor(listeners2, sps) { + __privateAdd(this, _pollingId, void 0); + __privateAdd(this, _sps, void 0); + this.listeners = {}; + this.setOptions = (opts = {}) => { + for (let key in opts) + this[key] = opts[key]; + }; + this.add = (info2) => { + const sub = info2.sub; + this.listeners[sub] = info2; + this.start(); + return true; + }; + this.get = (sub) => this.listeners[sub]; + this.remove = (sub) => { + delete this.listeners[sub]; + if (!Object.keys(this.listeners).length) + this.stop(); + }; + this.poll = (listeners22) => { + iterateSymbols(listeners22, (sym, o) => { + let { callback, current, history } = o; + if (!o.path.resolved) + o.path.resolved = getPath("output", o); + if (!isSame(current, history)) { + runCallback(callback, o.path.resolved, {}, current); + if (typeof current === "object") { + if (Array.isArray(current)) + history = [...current]; + else + history = { ...current }; + } else + listeners22[sym].history = current; + } + }); + }; + this.start = (listeners22 = this.listeners) => { + if (!this.sps) + this.sps = defaultSamplingRate; + else if (!__privateGet(this, _pollingId)) { + console.warn("[escode]: Starting Polling!"); + __privateSet(this, _pollingId, setInterval(() => this.poll(listeners22), 1e3 / this.sps)); + } + }; + this.stop = () => { + if (__privateGet(this, _pollingId)) { + console.warn("[escode]: Stopped Polling!"); + clearInterval(__privateGet(this, _pollingId)); + __privateSet(this, _pollingId, void 0); + } + }; + if (listeners2) + this.listeners = listeners2; + if (sps) + this.sps = sps; + } + get sps() { + return __privateGet(this, _sps); + } + set sps(sps) { + __privateSet(this, _sps, sps); + const listeners2 = this.listeners; + const nListeners = Object.keys(listeners2).length; + if (nListeners) { + this.stop(); + this.start(); + } + } + }, _pollingId = new WeakMap(), _sps = new WeakMap(), _a); + var listeners_exports = {}; + __export(listeners_exports, { + functionExecution: () => functionExecution, + functions: () => functions2, + getProxyFunction: () => getProxyFunction, + info: () => info, + register: () => register, + set: () => set, + setterExecution: () => setterExecution, + setters: () => setters + }); + globalThis.ESMonitorState = { + state: {}, + callback: void 0, + info: {} + }; + var global_default = globalThis.ESMonitorState; + var performance2 = async (callback, args) => { + const tic = globalThis.performance.now(); + const output = await callback(...args); + const toc = globalThis.performance.now(); + return { + output, + value: toc - tic + }; + }; + var infoFunctions = { + performance: performance2 + }; + var get = (func, args, info2) => { + let result = { + value: {}, + output: void 0 + }; + const infoToGet = { ...global_default.info, ...info2 }; + for (let key in infoToGet) { + if (infoToGet[key] && infoFunctions[key]) { + const ogFunc = func; + func = async (...args2) => { + const o = await infoFunctions[key](ogFunc, args2); + result.value[key] = o.value; + return o.output; + }; + } + } + result.output = func(...args); + return result; + }; + var isProxy = Symbol("isProxy"); + var fromInspectable = Symbol("fromInspectable"); + var fromInspectableHandler = Symbol("fromInspectableHandler"); + var keySeparator = "."; + var hasKey = (key, obj) => key in obj; + var getShortcut = (path, shortcuts, keySeparator2) => { + const sc = shortcuts[path[0]]; + if (sc) { + const value = sc[path.slice(1).join(keySeparator2)]; + if (value) + return value; + } + }; + var getFromPath = (baseObject, path, opts = {}) => { + const fallbackKeys = opts.fallbacks ?? []; + const keySeparator2 = opts.keySeparator ?? keySeparator; + if (opts.shortcuts) { + const shortcut = getShortcut(path, opts.shortcuts, keySeparator2); + if (shortcut) { + if (opts.output === "info") + return { value: shortcut, exists: true, shortcut: true }; + else + return shortcut; + } + } + if (typeof path === "string") + path = path.split(keySeparator2).flat(); + else if (typeof path == "symbol") + path = [path]; + let exists; + path = [...path]; + path = path.map((o) => typeof o === "string" ? o.split(keySeparator2) : o).flat(); + let ref = baseObject; + for (let i = 0; i < path.length; i++) { + if (ref) { + const str = path[i]; + if (!hasKey(str, ref) && "__children" in ref) { + for (let i2 in fallbackKeys) { + const key = fallbackKeys[i2]; + if (hasKey(key, ref)) { + ref = ref[key]; + break; + } + } + } + exists = hasKey(str, ref); + if (exists) + ref = ref[str]; + else { + ref = void 0; + exists = true; + } + } + } + if (opts.output === "info") + return { value: ref, exists }; + else + return ref; + }; + var setFromPath = (path, value, ref, opts = {}) => { + const create = opts?.create ?? false; + const keySeparator2 = opts?.keySeparator ?? keySeparator; + if (typeof path === "string") + path = path.split(keySeparator2); + else if (typeof path == "symbol") + path = [path]; + path = [...path]; + const copy = [...path]; + const last = copy.pop(); + if (ref.__children) + ref = ref.__children; + for (let i = 0; i < copy.length; i++) { + const str = copy[i]; + let has = hasKey(str, ref); + if (create && !has) { + ref[str] = {}; + has = true; + } + if (has) + ref = ref[str]; + if (ref.__children) + ref = ref.__children; + } + ref[last] = value; + return true; + }; + var handlers_exports = {}; + __export(handlers_exports, { + functions: () => functions, + objects: () => objects + }); + function define2(key, registerAsNewKey) { + const inspectable = this; + const target = this.target; + if (!this.parent) { + let value = target[key]; + if (typeof value === "function") { + target[key] = async (...args) => await this.proxy[key]({ [fromInspectable]: true, value }, ...args); + } else { + try { + Object.defineProperty(target, key, { + get: () => value, + set: function(val) { + value = val; + inspectable.proxy[key] = { [isProxy]: this[isProxy], [fromInspectable]: true, value: val }; + }, + enumerable: true, + configurable: true + }); + } catch (e) { + console.error(`Could not reassign ${key} to a top-level setter...`); + } + } + } + if (registerAsNewKey) + this.newKeys.add(key); + this.create(key, target, void 0, true); + } + var define_default = define2; + var functions = function() { + const inspectable = this; + return { + apply: async function(target, thisArg, argumentsList) { + try { + let foo = target; + const isFromInspectable = argumentsList[0]?.[fromInspectable]; + if (isFromInspectable) { + foo = argumentsList[0].value; + argumentsList = argumentsList.slice(1); + } + let listeners2 = inspectable.listeners.functions; + const pathStr = inspectable.path.join(inspectable.options.keySeparator); + const toActivate = listeners2 ? listeners2[pathStr] : void 0; + let output, executionInfo = {}; + if (toActivate) { + executionInfo = functionExecution(thisArg, toActivate, foo, argumentsList); + output = executionInfo.output; + } else { + output = foo.apply(thisArg, argumentsList); + executionInfo = inspectable?.state?.[pathStr]?.value ?? {}; + } + const callback = inspectable.options.callback; + runCallback(callback, pathStr, executionInfo, output); + return output; + } catch (e) { + console.warn(`Function failed:`, e, inspectable.path); + } + } + }; + }; + var objects = function() { + const inspectable = this; + return { + get(target, prop, receiver) { + if (prop === isProxy) + return true; + return Reflect.get(target, prop, receiver); + }, + set(target, prop, newVal, receiver) { + if (prop === isProxy) + return true; + const pathStr = [...inspectable.path, prop].join(inspectable.options.keySeparator); + const isFromProxy = newVal?.[isProxy]; + const isFromInspectable = newVal?.[fromInspectable]; + if (isFromInspectable) + newVal = newVal.value; + const listeners2 = inspectable.listeners.setters; + const desc = Object.getOwnPropertyDescriptor(target, prop); + const createListener = desc && !desc.get && !desc.set; + if (createListener) { + if (typeof inspectable.options.globalCallback === "function") { + const id = inspectable.path[0]; + define_default.call(inspectable, prop, true); + set("setters", pathStr, newVal, inspectable.options.globalCallback, { [id]: inspectable.root }, inspectable.listeners, inspectable.options); + } + } + if (newVal) { + const newProxy = inspectable.create(prop, target, newVal); + if (newProxy) + newVal = newProxy; + } + const toActivate = !isFromProxy; + if (listeners2 && toActivate && !inspectable.newKeys.has(prop)) { + const toActivate2 = listeners2[pathStr]; + if (toActivate2) + setterExecution(toActivate2, newVal); + } + const callback = inspectable.options.callback; + const info2 = inspectable?.state?.[pathStr]?.value ?? {}; + runCallback(callback, pathStr, info2, newVal); + if (isFromInspectable || !toActivate) + return true; + else + return Reflect.set(target, prop, newVal, receiver); + } + }; + }; + var canCreate = (parent, key, val) => { + try { + if (val === void 0) + val = parent[key]; + } catch (e) { + return e; + } + const alreadyIs = parent[key] && parent[key][isProxy]; + if (alreadyIs) + return false; + const type = typeof val; + const isObject = type === "object"; + const isFunction = type == "function"; + const notObjOrFunc = !val || !(isObject || isFunction); + if (notObjOrFunc) + return false; + if (val instanceof Element) + return false; + if (val instanceof EventTarget) + return false; + const isESM = isObject && esm(val); + if (isFunction) + return true; + else { + const desc = Object.getOwnPropertyDescriptor(parent, key); + if (desc && (desc.value && desc.writable || desc.set)) { + if (!isESM) + return true; + } else if (!parent.hasOwnProperty(key)) + return true; + } + return false; + }; + var Inspectable = class { + constructor(target = {}, opts = {}, name, parent) { + this.path = []; + this.listeners = {}; + this.newKeys = /* @__PURE__ */ new Set(); + this.state = {}; + this.set = (path, info2, update) => { + this.state[path] = { + output: update, + value: info2 + }; + setFromPath(path, update, this.proxy, { create: true }); + }; + this.check = canCreate; + this.create = (key, parent2, val, set2 = false) => { + const create = this.check(parent2, key, val); + if (val === void 0) + val = parent2[key]; + if (create && !(create instanceof Error)) { + parent2[key] = new Inspectable(val, this.options, key, this); + return parent2[key]; + } + if (set2) { + try { + this.proxy[key] = val ?? parent2[key]; + } catch (e) { + const isESM = esm(parent2); + const path = [...this.path, key]; + console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM ? " because the parent is an ESM." : ""}`, isESM ? "" : e); + } + } + return; + }; + if (!opts.pathFormat) + opts.pathFormat = "relative"; + if (!opts.keySeparator) + opts.keySeparator = keySeparator; + if (target.__proxy) + this.proxy = target.__proxy; + else if (target[isProxy]) + this.proxy = target; + else { + this.target = target; + this.options = opts; + this.parent = parent; + if (this.parent) { + this.root = this.parent.root; + this.path = [...this.parent.path]; + this.state = this.parent.state ?? {}; + } else + this.root = target; + if (name) + this.path.push(name); + if (this.options.listeners) + this.listeners = this.options.listeners; + if (this.options.path) { + if (this.options.path instanceof Function) + this.path = this.options.path(this.path); + else if (Array.isArray(this.options.path)) + this.path = this.options.path; + else + console.log("Invalid path", this.options.path); + } + if (this.path) + this.path = this.path.filter((str) => typeof str === "string"); + if (!this.options.keySeparator) + this.options.keySeparator = keySeparator; + let type = this.options.type; + if (type != "object") + type = typeof target === "function" ? "function" : "object"; + const handler2 = handlers_exports[`${type}s`].call(this); + this.proxy = new Proxy(target, handler2); + Object.defineProperty(target, "__proxy", { value: this.proxy, enumerable: false }); + Object.defineProperty(target, "__esInspectable", { value: this, enumerable: false }); + for (let key in target) + define_default.call(this, key); + } + return this.proxy; + } + }; + var setFromOptions = (path, value, baseOptions, opts) => { + const ref = opts.reference; + const id = Array.isArray(path) ? path[0] : typeof path === "string" ? path.split(baseOptions.keySeparator)[0] : path; + let isDynamic = opts.hasOwnProperty("static") ? !opts.static : false; + if (isDynamic && !globalThis.Proxy) { + isDynamic = false; + console.warn("Falling back to using function interception and setters..."); + } + if (isDynamic) { + value = new Inspectable(value, { + pathFormat: baseOptions.pathFormat, + keySeparator: baseOptions.keySeparator, + listeners: opts.listeners, + path: (path2) => path2.filter((str) => !baseOptions.fallbacks || !baseOptions.fallbacks.includes(str)) + }, id); + } + let options = { keySeparator: baseOptions.keySeparator, ...opts }; + setFromPath(path, value, ref, options); + return value; + }; + var info = (id, callback, path, originalValue, base, listeners2, options, refShortcut = {}) => { + if (typeof path === "string") + path = path.split(options.keySeparator); + const relativePath = path.join(options.keySeparator); + const refs = base; + const shortcutRef = refShortcut.ref; + const shortcutPath = refShortcut.path; + const get3 = (path2) => { + const thisBase = shortcutRef ?? base; + const res = getFromPath(thisBase, path2, { + keySeparator: options.keySeparator, + fallbacks: options.fallbacks + }); + return res; + }; + const set2 = (path2, value) => { + const thisBase = shortcutRef ?? base; + setFromOptions(path2, value, options, { + reference: thisBase, + listeners: listeners2 + }); + }; + let onUpdate = options.onUpdate; + let infoToOutput = {}; + if (onUpdate && typeof onUpdate === "object" && onUpdate.callback instanceof Function) { + infoToOutput = onUpdate.info ?? {}; + onUpdate = onUpdate.callback; + } + const absolute = [id, ...path]; + let pathInfo = { + absolute, + relative: relativePath.split(options.keySeparator), + parent: absolute.slice(0, -1) + }; + pathInfo.output = pathInfo[options.pathFormat]; + const completePathInfo = pathInfo; + const info2 = { + id, + path: completePathInfo, + keySeparator: options.keySeparator, + infoToOutput, + callback: (...args) => { + const output = callback(...args); + if (onUpdate instanceof Function) + onUpdate(...args); + return output; + }, + get current() { + return get3(shortcutPath ?? info2.path.absolute); + }, + set current(val) { + set2(shortcutPath ?? info2.path.absolute, val); + }, + get parent() { + return get3(shortcutPath ? shortcutPath?.slice(0, -1) : info2.path.parent); + }, + get reference() { + return refs[id]; + }, + set reference(val) { + refs[id] = val; + }, + original: originalValue, + history: typeof originalValue === "object" ? Object.assign({}, originalValue) : originalValue, + sub: Symbol("subscription"), + last: path.slice(-1)[0] + }; + return info2; + }; + var registerInLookup = (name, sub, lookups) => { + if (lookups) { + const id = Math.random(); + lookups.symbol[sub] = { + name, + id + }; + if (!lookups.name[name]) + lookups.name[name] = {}; + lookups.name[name][id] = sub; + } + }; + var register = (info2, collection, lookups) => { + const absolute = getPath("absolute", info2); + if (!collection[absolute]) + collection[absolute] = {}; + collection[absolute][info2.sub] = info2; + registerInLookup(absolute, info2.sub, lookups); + return true; + }; + var listeners = { + functions: functions2, + setters + }; + var set = (type, absPath, value, callback, base, allListeners, options) => { + const { id, path } = getPathInfo(absPath, options); + const fullInfo = info(id, callback, path, value, base, listeners, options); + if (listeners[type]) + listeners[type](fullInfo, allListeners[type], allListeners.lookup); + else { + const path2 = getPath("absolute", fullInfo); + allListeners[type][path2][fullInfo.sub] = fullInfo; + if (allListeners.lookup) + registerInLookup(path2, fullInfo.sub, allListeners.lookup); + } + }; + var get2 = (info2, collection) => collection[getPath("absolute", info2)]; + var handler = (info2, collection, subscribeCallback, lookups) => { + let success = !!get2(info2, collection); + if (!success) { + let parent = info2.parent; + let val = parent?.[info2.last]; + success = subscribeCallback(val, parent); + } + return register(info2, collection, lookups); + }; + var setterExecution = (listeners2, value) => { + return iterateSymbols(listeners2, (_, o) => { + const path = getPath("output", o); + runCallback(o.callback, path, {}, value); + }); + }; + function setters(info2, collection, lookups) { + const thisValue = this; + return handler(info2, collection["setters"], (value, parent) => { + let val = value; + if (!parent) + return; + if (!parent[isProxy]) { + let redefine = true; + try { + delete parent[info2.last]; + } catch (e) { + console.error("Unable to redeclare setters. May already be a dynamic object..."); + redefine = false; + } + if (redefine) { + try { + Object.defineProperty(parent, info2.last, { + get: () => val, + set: async (v) => { + const isFunction = typeof val === "function"; + val = v; + if (!isFunction) { + const listeners2 = Object.assign({}, collection["setters"][getPath("absolute", info2)]); + setterExecution(listeners2, v); + } else + val = getProxyFunction.call(thisValue, info2, collection, val); + }, + enumerable: true, + configurable: true + }); + } catch (e) { + throw e; + } + } + } + }, lookups); + } + function getProxyFunction(info2, collection, fn) { + return function(...args) { + const listeners2 = collection["functions"][getPath("absolute", info2)]; + return functionExecution(this, listeners2, fn ?? info2.original, args); + }; + } + var functionExecution = (context, listeners2, func, args) => { + listeners2 = Object.assign({}, listeners2); + const keys = Object.getOwnPropertySymbols(listeners2); + const infoTemplate = listeners2[keys[0]] ?? {}; + const executionInfo = get((...args2) => func.call(context, ...args2), args, infoTemplate.infoToOutput); + iterateSymbols(listeners2, (_, o) => { + const path = getPath("output", o); + runCallback(o.callback, path, executionInfo.value, executionInfo.output); + }); + return executionInfo; + }; + function functions2(info2, collection, lookups) { + return handler(info2, collection["functions"], (_, parent) => { + if (!parent[isProxy]) { + parent[info2.last] = getProxyFunction.call(this, info2, collection); + return setters(info2, collection, lookups); + } + }, lookups); + } + var drillSimple = (obj, callback, options) => { + let accumulator = options.accumulator; + if (!accumulator) + accumulator = options.accumulator = {}; + const ignore = options.ignore || []; + const path = options.path || []; + const condition = options.condition || true; + const seen = []; + const fromSeen = []; + let drill = (obj2, acc = {}, globalInfo) => { + for (let key in obj2) { + if (ignore.includes(key)) + continue; + const val = obj2[key]; + const newPath = [...globalInfo.path, key]; + const info2 = { + typeof: typeof val, + name: val?.constructor?.name, + simple: true, + object: val && typeof val === "object", + path: newPath + }; + if (info2.object) { + const name = info2.name; + const isESM = esm(val); + if (isESM || name === "Object" || name === "Array") { + info2.simple = true; + const idx = seen.indexOf(val); + if (idx !== -1) + acc[key] = fromSeen[idx]; + else { + seen.push(val); + const pass = condition instanceof Function ? condition(key, val, info2) : condition; + info2.pass = pass; + acc[key] = callback(key, val, info2); + if (pass) { + fromSeen.push(acc[key]); + acc[key] = drill(val, acc[key], { ...globalInfo, path: newPath }); + } + } + } else { + info2.simple = false; + acc[key] = callback(key, val, info2); + } + } else + acc[key] = callback(key, val, info2); + } + return acc; + }; + return drill(obj, accumulator, { path }); + }; + var createLookup = () => { + return { symbol: {}, name: {} }; + }; + var Monitor = class { + constructor(opts = {}) { + this.poller = new Poller(); + this.options = { + pathFormat: "relative", + keySeparator + }; + this.listeners = { + polling: this.poller.listeners, + functions: {}, + setters: {}, + lookup: createLookup() + }; + this.references = {}; + this.get = (path, output, reference = this.references, throwError = true) => { + return getFromPath(reference, path, { + keySeparator: this.options.keySeparator, + fallbacks: this.options.fallbacks, + output + }, throwError); + }; + this.set = (path, value, opts2 = {}) => { + const optsCopy = { ...opts2 }; + if (!optsCopy.reference) + optsCopy.reference = this.references; + if (!optsCopy.listeners) + optsCopy.listeners = this.listeners; + return setFromOptions(path, value, this.options, optsCopy); + }; + this.on = (absPath, callback) => { + const info2 = getPathInfo(absPath, this.options); + return this.listen(info2.id, callback, info2.path); + }; + this.getInfo = (label, callback, path, original) => { + const info2 = info(label, callback, path, original, this.references, this.listeners, this.options); + const id = Math.random(); + const lookups = this.listeners.lookup; + const name = getPath("absolute", info2); + lookups.symbol[info2.sub] = { + name, + id + }; + if (!lookups.name[name]) + lookups.name[name] = {}; + lookups.name[name][id] = info2.sub; + return info2; + }; + this.listen = (id, callback, path = [], __internal = {}) => { + if (typeof path === "string") + path = path.split(this.options.keySeparator); + else if (typeof path === "symbol") + path = [path]; + const arrayPath = path; + let baseRef = this.get(id); + if (!baseRef) { + console.error(`Reference does not exist.`, id); + return; + } + if (!__internal.poll) + __internal.poll = esm(baseRef); + if (!__internal.seen) + __internal.seen = []; + const __internalComplete = __internal; + const thisPath = [id, ...arrayPath]; + const ref = this.get(thisPath); + const toMonitorInternally = (val, allowArrays = false) => { + const first = val && typeof val === "object"; + if (!first) + return false; + const isEl = val instanceof Element; + if (isEl) + return false; + if (allowArrays) + return true; + else + return !Array.isArray(val); + }; + let subs = {}; + const subscribeAll = toMonitorInternally(ref, true); + if (subscribeAll) { + if (ref.__esInspectable) + ref.__esInspectable.options.globalCallback = callback; + drillSimple(ref, (_, __, drillInfo) => { + if (drillInfo.pass) + return; + else { + const fullPath = [...arrayPath, ...drillInfo.path]; + const internalSubs = this.listen(id, callback, fullPath, __internalComplete); + Object.assign(subs, internalSubs); + } + }, { + condition: (_, val) => toMonitorInternally(val) + }); + } + let info2; + let success = false; + try { + info2 = this.getInfo(id, callback, arrayPath, ref); + if (info2) { + if (__internalComplete.poll) + success = this.poller.add(info2); + else { + let type = "setters"; + if (typeof ref === "function") + type = "functions"; + success = this.add(type, info2); + } + } + } catch (e) { + console.error("Fallback to polling:", path, e); + success = this.poller.add(info2); + } + if (success) { + subs[getPath("absolute", info2)] = info2.sub; + if (this.options.onInit instanceof Function) { + const executionInfo = {}; + for (let key in info2.infoToOutput) + executionInfo[key] = void 0; + this.options.onInit(getPath("output", info2), executionInfo); + } + return subs; + } else { + console.error("Failed to subscribe to:", path); + return; + } + }; + this.add = (type, info2) => { + if (listeners_exports[type]) + return listeners_exports[type](info2, this.listeners, this.listeners.lookup); + else { + this.listeners[type][getPath("absolute", info2)][info2.sub] = info2; + return true; + } + }; + this.remove = (subs) => { + if (!subs) { + subs = { + ...this.listeners.functions, + ...this.listeners.setters, + ...this.listeners.polling + }; + } + if (typeof subs !== "object") + subs = { sub: subs }; + for (let key in subs) { + let innerSub = subs[key]; + const handleUnsubscribe = (sub) => { + const res = this.unsubscribe(sub); + if (res === false) + console.warn(`Subscription for ${key} does not exist.`, sub); + }; + if (typeof innerSub !== "symbol") + iterateSymbols(innerSub, handleUnsubscribe); + else + handleUnsubscribe(innerSub); + } + return true; + }; + this.unsubscribe = (sub) => { + const info2 = this.listeners.lookup.symbol[sub]; + const absPath = info2.name; + const polling = this.poller.get(sub); + const funcs = this.listeners.functions[absPath]; + const func = funcs?.[sub]; + const setters2 = this.listeners.setters[absPath]; + const setter = setters2?.[sub]; + if (polling) + this.poller.remove(sub); + else if (func) { + delete funcs[sub]; + if (!Object.getOwnPropertySymbols(funcs).length) { + Object.defineProperty(func.parent, func.last, { + value: func.original, + writable: true + }); + delete this.listeners.functions[absPath]; + } + } else if (setter) { + delete setters2[sub]; + if (!Object.getOwnPropertySymbols(setters2).length) { + const parent = setter.parent; + if (parent) { + const last = setter.last; + const value = parent[last]; + Object.defineProperty(parent, last, { value, writable: true }); + } + delete this.listeners.setters[absPath]; + } + } else + return false; + delete this.listeners.lookup.symbol[sub]; + const nameLookup = this.listeners.lookup.name[info2.name]; + delete nameLookup[info2.id]; + if (!Object.getOwnPropertyNames(nameLookup).length) + delete this.listeners.lookup.name[info2.name]; + }; + Object.defineProperty(this.listeners, "lookup", { + value: createLookup(), + enumerable: false, + configurable: false + }); + Object.assign(this.options, opts); + this.poller.setOptions(opts.polling); + } + }; + var src_default = Monitor; + + // ../../core/libraries/edgelord/index.ts + var defaultPath = "default"; + var operatorPath = "__operator"; + var specialKeys = { + path: "__path", + isGraphScript: "__", + listeners: { + value: "__listeners", + branch: "__branch", + bind: "__bind", + trigger: "__trigger", + format: "__format" + } + }; + var listenerObject = Symbol("listenerObject"); + var toSet = Symbol("toSet"); + var subscriptionKey = Symbol("subscriptionKey"); + var configKey = Symbol("configKey"); + var toResolveWithKey = Symbol("toResolveWithKey"); + var isConfigObject = (o) => specialKeys.listeners.format in o || specialKeys.listeners.branch in o || specialKeys.listeners.trigger in o || specialKeys.listeners.bind in o; + var initializedStatus = "INITIALIZED"; + var registeredStatus = "REGISTERED"; + var globalFrom = {}; + var globalTo = {}; + var globalActive = {}; + var _triggers, _queue, _toResolveWith, _initialize, _getAbsolutePath, _getPathInfo; + var Edgelord = class { + constructor(listeners2, root, context) { + this.original = {}; + this.active = {}; + this.globals = {}; + this.context = { + options: {} + }; + this.rootPath = ""; + this.status = ""; + __privateAdd(this, _triggers, []); + __privateAdd(this, _queue, []); + __privateAdd(this, _toResolveWith, void 0); + this.setInitialProperties = (listeners2 = {}, root, context = {}) => { + Object.assign(this.context, context); + if (root) + this.rootPath = root; + if (!this.context.options.keySeparator) + this.context.options.keySeparator = this.context.monitor.options.keySeparator; + this.original = listeners2; + const globals = [{ name: "active", ref: globalActive }, { name: "from", ref: globalFrom }, { name: "to", ref: globalTo }]; + globals.forEach((o) => { + if (!o.ref[this.context.id]) + o.ref[this.context.id] = {}; + this.globals[o.name] = o.ref[this.context.id]; + }); + __privateSet(this, _toResolveWith, this.getManager()); + this.runEachListener(listeners2, this.addToGlobalLog); + }; + this.getManager = (mode = "from") => { + let target = mode === "to" ? this.globals.to : this.globals.from; + this.rootPath.split(this.context.options.keySeparator).forEach((key) => { + if (!target[key]) + target[key] = {}; + target = target[key]; + }); + return target[toResolveWithKey] ?? this; + }; + this.onStart = (f) => { + const res = __privateGet(this, _toResolveWith); + const isSame2 = res === this; + if (isSame2) { + if (this.status === initializedStatus) + f(); + else + __privateGet(this, _queue).push(f); + } else + res.onStart(f); + }; + this.runEachListener = (listeners2, callback) => { + if (!callback) + return; + for (const first in listeners2) { + const second = listeners2[first]; + if (!second) { + console.warn("Skipping empty listener:", first); + continue; + } + if (second && typeof second === "object") { + const from = second; + const to = first; + for (let fromPath in from) { + callback(fromPath, to, from[fromPath]); + } + } else { + const from = first; + const to = second; + const typeOf = typeof to; + if (typeOf === "function") + callback(from, "", to); + else if (typeOf === "string") + callback(from, to, to); + else + console.error("Improperly Formatted Listener", to); + } + } + }; + this.register = (listeners2 = this.original) => { + this.runEachListener(listeners2, this.add); + this.status = registeredStatus; + }; + __privateAdd(this, _initialize, (o) => { + const res = this.context.monitor.get(o.path, "info"); + if (typeof res.value === "function") { + const args = Array.isArray(o.args) ? o.args : [o.args]; + res.value(...args); + } else + console.error("Cannot yet trigger values...", o); + }); + this.initialize = (o) => { + if (!this.status) + __privateGet(this, _triggers).push(o); + else if (this.status === registeredStatus) { + this.status = initializedStatus; + __privateGet(this, _triggers).forEach(__privateGet(this, _initialize)); + __privateGet(this, _queue).forEach((f) => f()); + __privateSet(this, _queue, []); + __privateSet(this, _triggers, []); + } else + __privateGet(this, _initialize).call(this, o); + }; + this.start = () => { + this.register(); + this.initialize(); + }; + __privateAdd(this, _getAbsolutePath, (name) => { + const sep = this.context.monitor.options.keySeparator; + return !name || !this.rootPath || this.rootPath === name.slice(0, this.rootPath.length) && name[this.rootPath.length] === sep ? name : [this.rootPath, name].join(sep); + }); + __privateAdd(this, _getPathInfo, (path) => { + const output = { + absolute: {}, + relative: {} + }; + path = __privateGet(this, _getAbsolutePath).call(this, path); + let rel = this.rootPath ? path.replace(`${this.rootPath}.`, "") : path; + const baseArr = path.split(this.context.options.keySeparator); + output.absolute.array = [this.context.id, ...baseArr]; + output.relative.array = rel.split(this.context.options.keySeparator); + let obj = this.context.monitor.get(output.relative.array, void 0, this.context.instance, false); + if (this.context.graph) { + if (obj && this.context.bound) { + output.absolute.array = [this.context.id, this.context.bound, ...output.absolute.array.slice(1)]; + output.relative.array.unshift(this.context.bound); + } else if (!obj) { + const rel2 = output.relative.array.join(this.context.options.keySeparator); + obj = this.context.graph.get(rel2); + } + } + const isGraphScript = obj && typeof obj === "object" && specialKeys.isGraphScript in obj; + if (isGraphScript) { + if (obj[operatorPath]) { + output.absolute.array.push(operatorPath); + output.relative.array.push(operatorPath); + } else if (obj[defaultPath]) { + output.absolute.array.push(defaultPath); + output.relative.array.push(defaultPath); + } + } + output.absolute.value = output.absolute.array.slice(1).join(this.context.options.keySeparator); + output.relative.value = output.relative.array.join(this.context.options.keySeparator); + return output; + }); + this.add = (from, to, value = true, subscription) => { + if (typeof to == "function") { + value = to; + to = ""; + } else if (typeof to !== "string") { + console.error("Improperly Formatted Listener", from, to, value); + return; + } + if (!value) + return; + const fromInfo = __privateGet(this, _getPathInfo).call(this, from); + const toInfo = __privateGet(this, _getPathInfo).call(this, to); + const absPath = fromInfo.absolute.value; + if (!subscription) + subscription = this.globals.active[absPath]?.[subscriptionKey]; + if (!subscription) { + subscription = this.context.monitor.on(fromInfo.absolute.array, (path, _, update) => this.activate(path, update), { + ref: this.context.instance, + path: fromInfo.relative.array + }); + } + if (typeof value == "string") + value = toInfo.absolute.array.slice(1).join(this.context.options.keySeparator); + const info2 = { + value, + [listenerObject]: true + }; + const refs = [this.active, this.globals.active]; + refs.forEach((ref) => { + if (!ref[absPath]) + ref[absPath] = {}; + const base = ref[absPath]; + if (!base[subscriptionKey]) { + Object.defineProperty(base, subscriptionKey, { + value: subscription, + configurable: true + }); + } + base[toInfo.absolute.value] = info2; + }); + const args = value[specialKeys.listeners.trigger]; + if (args) + __privateGet(this, _toResolveWith).initialize({ + path: fromInfo.absolute.array, + args + }); + this.addToGlobalLog(absPath); + return info2; + }; + this.addToGlobalLog = (path, mode = "from") => { + const absolutePath = __privateGet(this, _getAbsolutePath).call(this, path); + let target = mode === "to" ? this.globals.to : this.globals.from; + const globalPath = absolutePath.split(this.context.options.keySeparator); + globalPath.forEach((key) => { + if (!target[key]) + target[key] = {}; + target = target[key]; + if (!target[toResolveWithKey]) + target[toResolveWithKey] = this; + }); + }; + this.remove = (from, to) => { + const fromInfo = __privateGet(this, _getPathInfo).call(this, from); + const toInfo = __privateGet(this, _getPathInfo).call(this, to); + const path = [fromInfo.absolute.value, toInfo.absolute.value]; + const toRemove = [ + { ref: this.active, path }, + { ref: this.globals.active, path, unlisten: true } + ]; + toRemove.forEach((o) => { + const { ref, path: path2, unlisten } = o; + let base = ref[path2[0]]; + if (typeof base === "object") { + delete base[path2[1]]; + if (Object.keys(base).length === 0) { + delete ref[path2[0]]; + const sub = base[subscriptionKey]; + if (unlisten && sub) { + this.context.monitor.remove(sub); + } + delete base[subscriptionKey]; + } + } else + delete ref[path2[0]]; + }); + }; + this.clear = (name) => { + const value = __privateGet(this, _getAbsolutePath).call(this, name); + Object.keys(this.active).forEach((from) => { + Object.keys(this.active[from]).forEach((to) => { + if (!value || from.slice(0, value.length) === value || to.slice(0, value.length) === value) + this.remove(from, to); + }); + }); + }; + this.has = (from, ref = this.active) => !!ref[from]; + this.get = (from, ref = this.active) => ref[from]; + this.activate = (from, update) => { + const listenerGroups = [{ + info: this.get(from, this.globals.active), + name: from + }]; + listenerGroups.forEach((group) => { + const info2 = group.info; + if (info2) { + if (info2[listenerObject]) { + this.pass(from, { + value: info2.value, + parent: this.active, + key: group.name, + subscription: info2.subscription, + __value: true + }, update); + } else if (typeof info2 === "object") { + for (let key in info2) { + this.pass(from, { + parent: info2, + key, + subscription: info2[key].subscription, + value: info2[key].value + }, update); + } + } else + console.error("Improperly Formatted Listener", info2); + } + }); + }; + this.pass = (from, target, update) => { + const id = this.context.id; + const isValue = target?.__value; + let parent = target.parent; + let to = target.key; + const info2 = target.parent[to]; + target = info2.value; + let config = info2?.[configKey]; + let ogValue = target; + const type = typeof target; + const checkIfSetter = (path, willSet) => { + const info3 = this.context.monitor.get(path, "info"); + if (info3.exists) { + const val = info3.value; + const noDefault = typeof val !== "function" && !val?.default; + const value = noDefault ? toSet : val; + const res = { value }; + if (willSet) { + target = res.value; + parent[to] = res; + } + return res; + } else + return { value: void 0 }; + }; + const transform = (willSet) => { + const fullPath = [id]; + fullPath.push(...to.split(this.context.options.keySeparator)); + return checkIfSetter(fullPath, willSet); + }; + const getPathArray = (latest) => { + const path = [id]; + const topPath = []; + if (this.rootPath) + topPath.push(...this.rootPath.split(this.context.options.keySeparator)); + topPath.push(...latest.split(this.context.options.keySeparator)); + path.push(...topPath); + return path; + }; + if (typeof target === "boolean") { + if (!isValue) + transform(true); + else + console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`); + } else if (type === "string") { + const path = getPathArray(ogValue); + checkIfSetter(path, true); + if (isValue) { + parent[to] = { [ogValue]: parent[to] }; + to = ogValue; + } + } else if (target && type === "object") { + const isConfig = isConfigObject(ogValue); + if (isConfig) { + if ("value" in ogValue) { + if (isValue) { + target = parent[to] = ogValue.value; + } else { + target = parent[to].value = ogValue.value; + } + } else + transform(true); + if (ogValue) { + if (ogValue) + config = ogValue; + } + Object.defineProperty(parent[to], configKey, { value: config }); + } + } + let isValidInput = true; + if (config) { + const bindKey = specialKeys.listeners.value; + if (bindKey in config) { + const path = getPathArray(config[bindKey].original ?? config[bindKey]); + if (typeof config[bindKey] === "string") { + const res = this.context.monitor.get(path); + if (!res) + target = `because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.`; + else { + config[bindKey] = { + value: res, + original: config[bindKey] + }; + } + } else if (!config[bindKey].value.__parent) { + target = `because ${config[bindKey].original ?? id.toString()} has become unparented.`; + } + } else { + const branchKey = specialKeys.listeners.branch; + const formatKey = specialKeys.listeners.format; + if (branchKey in config) { + const isValid = config[branchKey].find((o) => { + let localValid = []; + if ("if" in o) + localValid.push(o.if(update)); + if ("is" in o) + localValid.push(o.is === update); + const isValidLocal = localValid.length > 0 && localValid.reduce((a, b) => a && b, true); + if (isValidLocal) { + if ("value" in o) + update = o.value; + } + return isValidLocal; + }); + if (!isValid) + isValidInput = false; + } + if (formatKey in config) { + try { + update = config[formatKey](update); + if (update === void 0) + isValidInput = false; + } catch (e) { + console.error("Failed to format arguments", e); + } + } + } + } + if (isValidInput && update !== void 0) { + const arrayUpdate = Array.isArray(update) ? update : [update]; + if (target === toSet) { + const parentPath = [id]; + parentPath.push(...to.split(this.context.options.keySeparator)); + const idx = parentPath.pop(); + const info3 = this.context.monitor.get(parentPath, "info"); + if (info3.value) + info3.value[idx] = update; + else + console.error(`Cannot set value on ${parentPath.filter((str) => typeof str !== "symbol").join(this.context.options.keySeparator)} from ${from}`); + } else if (target?.default) + target.default.call(target, ...arrayUpdate); + else if (typeof target === "function") { + const noContext = parent[to][listenerObject]; + if (noContext) + target.call(config?.[specialKeys.listeners.bind]?.value ?? this.context.instance, ...arrayUpdate); + else + target(...arrayUpdate); + } else { + let baseMessage = to ? `listener: ${from} \u2014> ${to}` : `listener from ${from}`; + if (parent) { + console.warn(`Deleting ${baseMessage}`, target); + delete parent[to]; + } else + console.error(`Failed to add ${baseMessage}`, target); + } + } + }; + if (listeners2 || root || context) + this.setInitialProperties(listeners2, root, context); + } + }; + _triggers = new WeakMap(); + _queue = new WeakMap(); + _toResolveWith = new WeakMap(); + _initialize = new WeakMap(); + _getAbsolutePath = new WeakMap(); + _getPathInfo = new WeakMap(); + var edgelord_default = Edgelord; + + // ../../core/Graph2.ts + function applyLoader(node, parent, graph = this, tree = graph.__node.tree, properties, tag = node.__node.tag, loader) { + const args = [node, parent, graph, tree, properties, tag]; + if (typeof loader === "object") { + if (loader.init) + loader(...args); + if (loader.connected) + node.__addOnconnected(loader.connect); + if (loader.disconnected) + node.__addOndisconnected(loader.disconnect); + } else if (typeof loader === "function") + loader(...args); + } + function applyLoaders(node, parent, graph = this, tree = graph.__node.tree, properties, tag = node.__node.tag, loaders2 = this.__node.loaders) { + for (const l in loaders2) + applyLoader(node, parent, graph, tree, properties, tag, loaders2[l]); + } + var _parent, _graph, _properties, _options, _applied, _applySetters; + var GraphNode = class { + constructor(properties, parent, graph, options) { + this.__ = Symbol("graphscript"); + this.__node = { + tag: `node${Math.floor(Math.random() * 1e15)}`, + unique: `${Math.random()}`, + ref: this, + flow: new edgelord_default() + }; + __privateAdd(this, _parent, void 0); + __privateAdd(this, _graph, void 0); + __privateAdd(this, _properties, {}); + __privateAdd(this, _options, {}); + __privateAdd(this, _applied, []); + __privateAdd(this, _applySetters, (properties = __privateGet(this, _properties), proxy = __privateGet(this, _properties), ignore = []) => { + const isProxy2 = proxy === true; + let keys = Object.getOwnPropertyNames(properties); + if (isProxy2) { + proxy = properties; + keys = getAllPropertyNames(properties); + } + for (const key of keys) { + if (ignore.includes(key)) + continue; + if (__privateGet(this, _applied).includes(key)) + continue; + __privateGet(this, _applied).push(key); + if (key === "__properties") + Object.defineProperty(this, key, { + get: () => __privateGet(this, _properties), + enumerable: true + }); + else if (key === "__props") { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => { + proxy[key] = value; + __privateGet(this, _applySetters).call(this, value, true); + }, + enumerable: true, + configurable: true + }); + } else { + Object.defineProperty(this, key, { + get: () => proxy[key], + set: (value) => proxy[key] = value, + enumerable: true, + configurable: false + }); + } + } + }); + this.____apply = __privateGet(this, _applySetters); + this.__init = (properties, parent = __privateGet(this, _parent), graph = __privateGet(this, _graph), options = __privateGet(this, _options)) => { + __privateSet(this, _parent, parent); + __privateSet(this, _graph, graph); + __privateSet(this, _options, options); + if (properties) { + let orig = properties; + if (typeof properties === "function") { + if (isNativeClass(properties)) { + properties = new properties(); + } else + properties = { + __operator: properties, + __node: { + forward: true, + tag: properties.name + } + }; + } else if (typeof properties === "string") { + if (graph?.get(properties)) { + properties = graph.get(properties); + } + } + if (typeof properties === "object") { + if (parent instanceof Graph && properties instanceof Graph) { + if (properties.__node.loaders) + Object.assign(parent.__node.loaders ? parent.__node.loaders : {}, properties.__node.loaders); + if (parent.__node.mapGraphs) { + properties.__node.nodes.forEach((n) => { + parent.set(properties.__node.tag + "." + n.__node.tag, n); + }); + let ondelete = () => { + properties.__node.nodes.forEach((n) => { + parent.__node.nodes.delete(properties.__node.tag + "." + n.__node.tag); + }); + }; + this.__addOndisconnected(ondelete); + } + properties = properties.__node.tree; + } + __privateSet(this, _properties, properties); + if (!properties.__node) + properties.__node = {}; + if (!properties.__node.initial) + this.__node.initial = orig; + if (properties.__props) { + if (typeof properties.__props === "function") + properties.__props = new properties.__props(); + } + if (typeof properties.__node === "string") { + if (graph?.get(properties.__node.tag)) { + properties = graph.get(properties.__node.tag); + } else + properties.__node = {}; + } else if (!properties.__node) + properties.__node = {}; + if (graph) + properties.__node.graph = graph; + if (properties.__operator) { + if (typeof properties.__operator === "string") { + if (graph) { + let n = graph.get(properties.__operator); + if (n) + properties.__operator = n.__operator; + if (!properties.__node.tag && properties.__operator.name) + properties.__node.tag = properties.__operator.name; + } + } + } + if (!properties.__node.tag) { + if (properties.__operator?.name) + properties.__node.tag = properties.__operator.name; + else + properties.__node.tag = `node${Math.floor(Math.random() * 1e15)}`; + } + if (!properties.__parent && parent) + properties.__parent = parent; + if (parent?.__node && !(parent instanceof Graph || properties instanceof Graph)) + properties.__node.tag = parent.__node.tag + "." + properties.__node.tag; + properties.__node = Object.assign(this.__node, properties.__node); + const ogProperties = properties; + __privateGet(this, _applySetters).call(this); + applyLoaders.call(graph, this, parent, graph, graph?.__node?.tree, properties); + __privateGet(this, _applySetters).call(this, void 0, void 0, ["__props"]); + if (properties instanceof Graph) + this.__node.source = properties; + if (typeof options.onInit === "function") + options.onInit(); + if (graph) { + const symbol = (graph.__node.ref ?? this).__; + const monitor = graph.monitor; + this.__node.flow.setInitialProperties(this.__listeners, void 0, { + id: symbol, + instance: this, + monitor, + graph, + bound: this.__node.tag + }); + } else + console.error("No flow manager created for " + this.__node.tag); + } + } + }; + this.__init(properties, parent, graph, options); + } + get __properties() { + return __privateGet(this, _properties); + } + __addOnconnected(callback) { + if (Array.isArray(this.__onconnected)) { + this.__onconnected.push(callback); + } else if (typeof this.__onconnected === "function") { + this.__onconnected = [callback, this.__onconnected]; + } else + this.__onconnected = callback; + } + __addOndisconnected(callback) { + if (Array.isArray(this.__ondisconnected)) { + this.__ondisconnected.push(callback); + } else if (typeof this.__ondisconnected === "function") { + this.__ondisconnected = [callback, this.__ondisconnected]; + } else + this.__ondisconnected = callback; + } + __callConnected(node = this) { + if (typeof this.__onconnected === "function") { + this.__onconnected(this); + } else if (Array.isArray(this.__onconnected)) { + this.__onconnected.forEach((o) => { + o.call(this, this); + }); + } + } + __callDisconnected(node = this) { + if (typeof this.__ondisconnected === "function") + this.__ondisconnected(this); + else if (Array.isArray(this.__ondisconnected)) { + this.__ondisconnected.forEach((o) => { + o.call(this, this); + }); + } + } + }; + _parent = new WeakMap(); + _graph = new WeakMap(); + _properties = new WeakMap(); + _options = new WeakMap(); + _applied = new WeakMap(); + _applySetters = new WeakMap(); + var _init; + var _Graph = class { + constructor(options) { + this.monitor = new src_default({ + keySeparator: ".", + fallbacks: ["__children"] + }); + this.__node = { + tag: `graph${Math.floor(Math.random() * 1e15)}`, + nodes: /* @__PURE__ */ new Map(), + ref: new GraphNode(), + loaders: [ + props_loader_default + ] + }; + this.init = (options) => { + if (options) { + if (options.loaders) { + this.setLoaders(options.loaders); + delete options.loaders; + } + recursivelyAssign(this.__node, options); + if (options.tree) + this.setTree(options.tree); + } + }; + __privateAdd(this, _init, (properties) => { + const node = this.__node.ref; + node.__init(properties, this, this, { + onInit: () => { + this.monitor.set(node.__, node.__properties); + } + }); + return node; + }); + this.setTree = (tree) => { + const hasGraphscriptProperties = Object.keys(tree).find((str) => { + const slice = str.slice(0, 2); + return slice === "__" && str !== "__node"; + }); + if (!hasGraphscriptProperties) + tree = { __children: tree }; + if (!tree.__node) + tree.__node = {}; + this.__node.tree = Object.assign(this.__node.tree ? this.__node.tree : {}, tree); + let cpy = Object.assign({}, tree); + if (cpy.__node) + delete cpy.__node; + let listeners2 = this.recursiveSet(cpy, this, void 0, tree); + if (!tree.__node.tag) + tree.__node.tag = this.__node.tag; + const node = __privateGet(this, _init).call(this, tree); + const children = node.__children; + const copy = Object.assign({}, children); + if (children) + listeners2 = this.recursiveSet(copy, this, void 0, children); + if (node.__listeners) + listeners2[node.__node.tag] = node.__listeners; + this.__node.nodes.forEach((n) => n.__node.flow.start()); + node.__callConnected(); + return cpy; + }; + this.setLoaders = (loaders2, replace) => { + if (replace) + this.__node.loaders = loaders2; + else { + if (Array.isArray(this.__node.loaders)) { + if (Array.isArray(loaders2)) + this.__node.loaders = [...this.__node.loaders, ...loaders2]; + else + this.__node.loaders = [...this.__node.loaders, ...Object.values(loaders2)]; + } else + Object.assign(this.__node.loaders, loaders2); + } + return this.__node.loaders; + }; + this.add = (properties, parent) => { + let listeners2 = {}; + if (typeof parent === "string") + parent = this.get(parent); + let instanced; + if (typeof properties === "function") { + if (isNativeClass(properties)) { + if (properties.prototype instanceof GraphNode) { + properties = properties.prototype.constructor(properties, parent, this); + instanced = true; + } else + properties = new properties(); + } else + properties = { __operator: properties }; + } else if (typeof properties === "string") + properties = this.__node.tree[properties]; + if (!instanced) { + properties = Object.assign({}, properties); + } + if (!properties.__node) + properties.__node = {}; + properties.__node.initial = properties; + if (typeof properties === "object" && (!properties?.__node?.tag || !this.get(properties.__node.tag))) { + let node; + if (instanced) + node = properties; + else + node = new GraphNode(properties, parent, this); + this.set(node.__node.tag, node); + this.__node.tree[node.__node.tag] = properties; + if (node.__listeners) { + listeners2[node.__node.tag] = node.__listeners; + } + if (node.__children) { + const children = node.__children; + const copy = Object.assign({}, children); + this.recursiveSet(copy, node, listeners2, children); + } + node.__callConnected(); + return node; + } + return; + }; + this.recursiveSet = (t, parent, listeners2 = {}, origin = t) => { + let keys = Object.getOwnPropertyNames(origin); + for (const key of keys) { + if (key.includes("__")) + continue; + let p = origin[key]; + if (Array.isArray(p)) + continue; + let instanced; + if (typeof p === "function") { + if (isNativeClass(p)) { + p = new p(); + if (p instanceof GraphNode) { + p = p.prototype.constructor(p, parent, this); + instanced = true; + } + } else + p = { __operator: p }; + } else if (typeof p === "string") + p = this.__node.tree[p]; + else if (typeof p === "boolean") + p = this.__node.tree[key]; + if (typeof p === "object") { + if (!p.__node) + p.__node = {}; + if (!p.__node.tag) + p.__node.tag = key; + p.__node.initial = t[key]; + if (this.get(p.__node.tag) && !(parent?.__node && this.get(parent.__node.tag + "." + p.__node.tag)) || parent?.__node && this.get(parent.__node.tag + "." + p.__node.tag)) + continue; + let node; + if (instanced) + node = p; + else + node = new GraphNode(p, parent, this); + this.set(node.__node.tag, node); + t[key] = node; + this.__node.tree[node.__node.tag] = p; + if (node.__listeners) { + listeners2[node.__node.tag] = node.__listeners; + } + if (node.__children) { + const children = node.__children; + const copy = Object.assign({}, children); + this.recursiveSet(copy, node, listeners2, children); + } + let parentNode = parent instanceof _Graph ? parent.__node.ref : parent; + parentNode.__addOnconnected(() => node.__callConnected()); + } + } + return listeners2; + }; + this.remove = (node) => { + if (typeof node === "string") + node = this.get(node); + if (node instanceof GraphNode) { + this.delete(node.__node.tag); + delete this.__node.tree[node.__node.tag]; + this.clearListeners(node); + node.__callDisconnected(); + const recursiveRemove = (t) => { + for (const key in t) { + const node2 = t[key].__node.ref; + this.clearListeners(node2); + this.delete(node2.__node.tag); + delete this.__node.tree[node2.__node.tag]; + this.delete(key); + delete this.__node.tree[key]; + node2.__node.tag = node2.__node.tag.substring(node2.__node.tag.lastIndexOf(".") + 1); + this.clearListeners(node2); + node2.__callDisconnected(); + if (node2.__children) + recursiveRemove(node2.__children); + } + }; + if (node.__children) + recursiveRemove(node.__children); + } + if (node?.__node.tag && node?.__parent) { + node.__parent = void 0; + node.__node.tag = node.__node.tag.substring(node.__node.tag.indexOf(".") + 1); + } + return node; + }; + this.run = (node, ...args) => { + if (typeof node === "string") { + let nd = this.get(node); + if (!nd && node.includes(".")) { + nd = this.get(node.substring(0, node.lastIndexOf("."))); + if (typeof nd?.[node.substring(node.lastIndexOf(".") + 1)] === "function") + return nd[node.substring(node.lastIndexOf(".") + 1)](...args); + } else if (nd?.__operator) + return nd.__operator(...args); + } + if (node?.__operator) { + return node?.__operator(...args); + } + }; + this.clearListeners = (node) => { + this.unsubscribe(node); + this.clear(node); + }; + this.get = (tag, base) => { + if (base instanceof GraphNode) + base = base.__node.tag; + if (tag === this.__node.tag) + return this.__node.ref; + if (base) { + const relFrom = [base, tag].join("."); + const got = this.get(relFrom); + if (got) + return got; + } + return this.__node.nodes.get(tag); + }; + this.set = (tag, node) => { + return this.__node.nodes.set(tag, node); + }; + this.delete = (tag) => { + return this.__node.nodes.delete(tag); + }; + this.getProps = (node, getInitial) => { + if (typeof node === "string") + node = this.get(node); + if (node instanceof GraphNode) { + let cpy; + if (getInitial) + cpy = Object.assign({}, this.__node.tree[node.__node.tag]); + else { + cpy = Object.assign({}, node); + delete cpy.__unsubscribe; + delete cpy.__setOperator; + delete cpy.__node; + delete cpy.__subscribeState; + delete cpy.__subscribe; + } + } + }; + this.subscribe = (from, to, value = true, bound = this.__node.ref) => { + if (typeof from !== "string") + from = from.__node.tag; + if (typeof bound === "string") + bound = this.get(bound); + if (bound) + bound.__node.flow.add(from, to, value); + }; + this.unsubscribe = (node, from, to) => this.clear(from, to, node); + this.clear = (from, to, bound) => { + const nd = typeof bound === "string" ? this.get(bound) : bound; + if (typeof from === "symbol") + return this.__node.flow.remove(from); + let fromString = from instanceof GraphNode ? from.__node.tag : from; + let toString = to instanceof GraphNode ? to.__node.tag : to; + const remove = (n) => { + const flow = n.__node.flow; + toString ? flow.remove(fromString, toString) : flow.clear(fromString); + }; + if (nd) + remove(nd); + else { + remove(this.__node.ref); + this.__node.nodes.forEach(remove); + } + }; + this.activate = (from, value) => this.__node.ref.__node.flow.activate(from, value); + this.setState = (update) => { + for (let key in update) + this.activate(key, update); + }; + this.init(options); + } + }; + var Graph = _Graph; + _init = new WeakMap(); + function recursivelyAssign(target, obj) { + for (const key in obj) { + if (obj[key]?.constructor.name === "Object" && !Array.isArray(obj[key])) { + if (target[key]?.constructor.name === "Object" && !Array.isArray(target[key])) + recursivelyAssign(target[key], obj[key]); + else + target[key] = recursivelyAssign({}, obj[key]); + } else { + target[key] = obj[key]; + } + } + return target; + } + function getAllPropertyNames(obj) { + var props = []; + do { + if (obj.constructor.name === "Object") + props.push(...Object.keys(obj)); + else + Object.getOwnPropertyNames(obj).forEach(function(prop) { + if (props.indexOf(prop) === -1) + props.push(prop); + }); + } while (obj = Object.getPrototypeOf(obj)); + return props; + } + function isNativeClass(thing) { + return typeof thing === "function" && thing.hasOwnProperty("prototype") && !thing.hasOwnProperty("arguments"); + } + + // ../../core/loaders/index.ts + var backprop = (node, parent, graph) => { + if (node.__node.backward && parent instanceof GraphNode) + graph.subscribe(parent.__node.tag, node.__node.tag); + }; + var loop = (node, parent, graph) => { + if (node.__operator && !node.__node.looperSet) { + node.__node.looperSet = true; + if (typeof node.__node.delay === "number") { + let fn = node.__operator; + const delay = (...args) => { + return new Promise((res, rej) => { + setTimeout(async () => { + res(await fn(...args)); + }, node.__node.delay); + }); + }; + node.__operator = delay; + } else if (node.__node.frame === true) { + let fn = node.__operator; + const frame = (...args) => { + return new Promise((res, rej) => { + requestAnimationFrame(async () => { + res(await fn(...args)); + }); + }); + }; + node.__operator = frame; + } + if (typeof node.__node.repeat === "number" || typeof node.__node.recursive === "number") { + let fn = node.__operator; + const repeat = async (...args) => { + let i = node.__node.repeat ? node.__node.repeat : node.__node.recursive; + let result; + let repeater = async (tick, ...inp) => { + while (tick > 0) { + if (node.__node.delay || node.__node.frame) { + fn(...inp).then(async (res) => { + if (node.__node.recursive) { + await repeater(tick, res); + } else + await repeater(tick, ...inp); + }); + break; + } else + result = await fn(...args); + tick--; + } + }; + await repeater(i, ...args); + return result; + }; + node.__operator = repeat; + } + if (node.__node.loop && typeof node.__node.loop === "number") { + let ogFunction = node.__operator; + const looper = function(...args) { + if (!("looping" in node.__node)) + node.__node.looping = true; + if (node.__node.looping) { + const res = ogFunction.call(node, ...args); + setTimeout(() => { + node.__operator(...args); + }, node.__node.loop); + return res; + } + }; + node.__operator = looper; + node.__addOnconnected((node2) => { + if (node2.__node.looping) + node2.__operator(); + }); + let ondelete = (node2) => { + if (node2.__node.looping) + node2.__node.looping = false; + }; + node.__addOndisconnected(ondelete); + } + } + }; + var animate = (node, parent, graph) => { + if (node.__node.animate === true || node.__animation) { + let fn = node.__operator; + const animate2 = (...args) => { + if (!("animating" in node.__node)) + node.__node.animating = true; + if (node.__node.animating) { + if (typeof node.__animation === "function") + node.__animation(...args); + else + fn.call(node, ...args); + requestAnimationFrame(() => { + node.__operator(...args); + }); + } + return true; + }; + node.__operator = animate2; + node.__addOnconnected((node2) => { + if (node2.__node.animating || (!("animating" in node2.__node) || node2.__node.animating) && node2.__animation) + setTimeout(() => { + requestAnimationFrame(node2.__operator); + }, 10); + }); + node.__addOndisconnected((node2) => { + if (node2.__node.animating) + node2.__node.animating = false; + }); + } + }; + var branching = (node, parent, graph) => { + if (typeof node.__node.branch === "object" && node.__operator && !node.__node.branchApplied) { + let fn = node.__operator; + node.__node.branchApplied = true; + node.__operator = (...args) => { + let result = fn(...args); + for (const key in node.__node.branch) { + let triggered = () => { + if (typeof node.__node.branch[key].then === "function") { + node.__node.branch[key].then(result); + } else if (node.__node.branch[key].then instanceof GraphNode && node.__node.branch[key].then.__operator) { + node.__node.branch[key].then.__operator(result); + } else + result = node.__node.branch[key].then; + }; + if (typeof node.__node.branch[key].if === "function") { + if (node.__node.branch[key].if(result)) { + triggered(); + } + } else if (node.__node.branch[key].if === result) { + triggered(); + } + } + return result; + }; + } + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (node.__listeners[key].branch && !node.__listeners[key].branchApplied) { + let fn = node.__listeners[key].callback; + node.__listeners[key].branchApplied = true; + node.__listeners.callback = (ret2) => { + let triggered = () => { + if (typeof node.__listeners[key].branch.then === "function") { + ret2 = node.__listeners[key].branch.then(ret2); + } else if (node.__listeners[key].branch.then instanceof GraphNode && node.__listeners[key].branch.then.__operator) { + ret2 = node.__listeners[key].branch.then.__operator(ret2); + } else + ret2 = node.__listeners[key].branch.then; + }; + if (typeof node.__listeners[key].branch.if === "function") { + if (node.__listeners[key].branch.if(ret2)) { + triggered(); + } + } else if (node.__listeners[key].branch.if === ret2) { + triggered(); + } + return fn(ret2); + }; + } + } + } + } + }; + var triggerListenerOncreate = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (node.__listeners[key].oncreate) { + node.__listeners[key].callback(node.__listeners[key].oncreate); + } + } + } + } + }; + var bindListener = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (typeof node.__listeners[key].binding === "object") { + node.__listeners.callback = node.__listeners.callback.bind(node.__listeners[key].binding); + } + } + } + } + }; + var transformListenerResult = (node, parent, graph) => { + if (node.__listeners) { + for (const key in node.__listeners) { + if (typeof node.__listeners[key] === "object") { + if (typeof node.__listeners[key].transform === "function" && !node.__listeners[key].transformApplied) { + let fn = node.__listeners[key].callback; + node.__listeners[key].transformApplied = true; + node.__listeners.callback = (ret2) => { + ret2 = node.__listeners[key].transform(ret2); + return fn(ret2); + }; + } + } + } + } + }; + var substitute__operator = (node, parent, graph) => { + if (node.post && !node.__operator) { + node.__operator = node.post; + } else if (!node.__operator && typeof node.get == "function") { + node.__operator = node.get; + } + if (!node.get && node.__operator) { + node.get = node.__operator; + } + if (node.aliases) { + node.aliases.forEach((a) => { + graph.set(a, node); + let ondelete = (node2) => { + graph.__node.nodes.delete(a); + }; + node.__addOndisconnected(ondelete); + }); + } + if (typeof graph.__node.tree[node.__node.tag] === "object" && node.get) + graph.__node.tree[node.__node.tag].get = node.get; + }; + var loaders = { + backprop, + loop, + animate, + branching, + triggerListenerOncreate, + bindListener, + transformListenerResult, + substitute__operator + }; + + // ../../services/Service.ts + var Service = class extends Graph { + constructor(options) { + super({ + ...options, + loaders: options?.loaders ? Object.assign({ ...loaders }, options.loaders) : { ...loaders } + }); + this.name = `service${Math.floor(Math.random() * 1e15)}`; + this.addServices = (services) => { + for (const s in services) { + if (typeof services[s] === "function") + services[s] = new services[s](); + if (services[s]?.__node?.loaders) + Object.assign(this.__node.loaders, services[s].__node.loaders); + if (services[s]?.__node?.nodes) { + services[s].__node.nodes.forEach((n, tag) => { + if (!this.get(tag)) { + this.set(tag, n); + } else + this.set(s + "." + tag, n); + }); + this.__node.nodes.forEach((n, k) => { + if (!services[s].__node.nodes.get(k)) + services[s].__node.nodes.set(k, n); + }); + let set2 = this.set; + this.set = (tag, node) => { + services[s].set(tag, node); + return set2(tag, node); + }; + let del = this.delete; + this.delete = (tag) => { + services[s].delete(tag); + return del(tag); + }; + } else if (typeof services[s] === "object") { + this.setTree(services[s]); + } + } + }; + this.handleMethod = (route, method, args) => { + let m = method.toLowerCase(); + let src = this.__node.nodes.get(route); + if (!src) { + src = this.__node.tree[route]; + } + if (src?.[m]) { + if (!(src[m] instanceof Function)) { + if (args) + src[m] = args; + return src[m]; + } else + return src[m](args); + } else + return this.handleServiceMessage({ route, args, method }); + }; + this.transmit = (...args) => { + if (typeof args[0] === "object") { + if (args[0].method) { + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if (args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node) { + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if (this.__node.keepState) { + if (args[0].route) + this.setState({ [args[0].route]: args[0].args }); + if (args[0].node) + this.setState({ [args[0].node]: args[0].args }); + } + return args; + } else + return args; + }; + this.receive = (...args) => { + if (args[0]) { + if (typeof args[0] === "string") { + let substr = args[0].substring(0, 8); + if (substr.includes("{") || substr.includes("[")) { + if (substr.includes("\\")) + args[0] = args[0].replace(/\\/g, ""); + if (args[0][0] === '"') { + args[0] = args[0].substring(1, args[0].length - 1); + } + ; + args[0] = JSON.parse(args[0]); + } + } + } + if (typeof args[0] === "object") { + if (args[0].method) { + return this.handleMethod(args[0].route, args[0].method, args[0].args); + } else if (args[0].route) { + return this.handleServiceMessage(args[0]); + } else if (args[0].node) { + return this.handleGraphNodeCall(args[0].node, args[0].args); + } else if (this.__node.keepState) { + if (args[0].route) + this.setState({ [args[0].route]: args[0].args }); + if (args[0].node) + this.setState({ [args[0].node]: args[0].args }); + } + return args; + } else + return args; + }; + this.pipe = (source, destination, endpoint, method, callback) => { + if (source instanceof GraphNode) { + if (callback) + return this.subscribe(source, (res) => { + let mod = callback(res); + if (mod !== void 0) + this.transmit({ route: destination, args: mod, method }); + else + this.transmit({ route: destination, args: res, method }, endpoint); + }); + else + return this.subscribe(source, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + } else if (typeof source === "string") + return this.subscribe(source, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + }; + this.pipeOnce = (source, destination, endpoint, method, callback) => { + if (source instanceof GraphNode) { + if (callback) + return source.__node.state.subscribeTriggerOnce(source.__node.unique, (res) => { + let mod = callback(res); + if (mod !== void 0) + this.transmit({ route: destination, args: mod, method }); + else + this.transmit({ route: destination, args: res, method }, endpoint); + }); + else + return this.__node.state.subscribeTriggerOnce(source.__node.unique, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + } else if (typeof source === "string") + return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique, (res) => { + this.transmit({ route: destination, args: res, method }, endpoint); + }); + }; + this.terminate = (...args) => { + }; + this.isTypedArray = isTypedArray; + this.recursivelyAssign = recursivelyAssign2; + this.spliceTypedArray = spliceTypedArray; + this.ping = () => { + console.log("pinged!"); + return "pong"; + }; + this.echo = (...args) => { + this.transmit(...args); + return args; + }; + if (options?.services) + this.addServices(options.services); + this.setTree(this); + } + handleServiceMessage(message) { + let call; + if (typeof message === "object") { + if (message.route) + call = message.route; + else if (message.node) + call = message.node; + } + if (call) { + if (Array.isArray(message.args)) + return this.run(call, ...message.args); + else + return this.run(call, message.args); + } else + return message; + } + handleGraphNodeCall(route, args) { + if (!route) + return args; + if (args?.args) { + this.handleServiceMessage(args); + } else if (Array.isArray(args)) + return this.run(route, ...args); + else + return this.run(route, args); + } + }; + function isTypedArray(x) { + return ArrayBuffer.isView(x) && Object.prototype.toString.call(x) !== "[object DataView]"; + } + var recursivelyAssign2 = (target, obj) => { + for (const key in obj) { + if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { + if (typeof target[key] === "object" && !Array.isArray(target[key])) + recursivelyAssign2(target[key], obj[key]); + else + target[key] = recursivelyAssign2({}, obj[key]); + } else + target[key] = obj[key]; + } + return target; + }; + function spliceTypedArray(arr, start, end) { + let s = arr.subarray(0, start); + let e; + if (end) { + e = arr.subarray(end + 1); + } + let ta; + if (s.length > 0 || e?.length > 0) + ta = new arr.constructor(s.length + e.length); + if (ta) { + if (s.length > 0) + ta.set(s); + if (e && e.length > 0) + ta.set(e, s.length); + } + return ta; + } + + // ../../services/utils.ts + function parseFunctionFromText(method = "") { + let getFunctionBody = (methodString) => { + return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, "$2$3$4"); + }; + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf("=>") + 1; + if (startindex <= 0) { + startindex = methodString.indexOf("){"); + } + if (startindex <= 0) { + startindex = methodString.indexOf(") {"); + } + return methodString.slice(0, methodString.indexOf("{", startindex) + 1); + }; + let newFuncHead = getFunctionHead(method); + let newFuncBody = getFunctionBody(method); + let newFunc; + if (newFuncHead.includes("function")) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody); + } else { + if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf("{") + 1, newFuncBody.length - 1)); + } else { + try { + newFunc = (0, eval)(newFuncHead + newFuncBody + "}"); + } catch { + } + } + } + return newFunc; + } + var stringifyWithCircularRefs = function() { + const refs = /* @__PURE__ */ new Map(); + const parents = []; + const path = ["this"]; + function clear() { + refs.clear(); + parents.length = 0; + path.length = 1; + } + function updateParents(key, value) { + var idx = parents.length - 1; + var prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value || idx === 0) { + path.push(key); + parents.push(value.pushed); + } else { + while (idx-- >= 0) { + prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value) { + idx += 2; + parents.length = idx; + path.length = idx; + --idx; + parents[idx] = value; + path[idx] = key; + break; + } + } + idx--; + } + } + } + } + function checkCircular(key, value) { + if (value != null) { + if (typeof value === "object") { + if (key) { + updateParents(key, value); + } + let other = refs.get(value); + if (other) { + return "[Circular Reference]" + other; + } else { + refs.set(value, path.join(".")); + } + } + } + return value; + } + return function stringifyWithCircularRefs2(obj, space) { + try { + parents.push(obj); + return JSON.stringify(obj, checkCircular, space); + } finally { + clear(); + } + }; + }(); + if (JSON.stringifyWithCircularRefs === void 0) { + JSON.stringifyWithCircularRefs = stringifyWithCircularRefs; + } + var stringifyFast = function() { + const refs = /* @__PURE__ */ new Map(); + const parents = []; + const path = ["this"]; + function clear() { + refs.clear(); + parents.length = 0; + path.length = 1; + } + function updateParents(key, value) { + var idx = parents.length - 1; + if (parents[idx]) { + var prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value || idx === 0) { + path.push(key); + parents.push(value.pushed); + } else { + while (idx-- >= 0) { + prev = parents[idx]; + if (typeof prev === "object") { + if (prev[key] === value) { + idx += 2; + parents.length = idx; + path.length = idx; + --idx; + parents[idx] = value; + path[idx] = key; + break; + } + } + idx++; + } + } + } + } + } + function checkValues(key, value) { + let val; + if (value != null) { + if (typeof value === "object") { + let c = value.constructor.name; + if (key && c === "Object") { + updateParents(key, value); + } + let other = refs.get(value); + if (other) { + return "[Circular Reference]" + other; + } else { + refs.set(value, path.join(".")); + } + if (c === "Array") { + if (value.length > 20) { + val = value.slice(value.length - 20); + } else + val = value; + } else if (c.includes("Set")) { + val = Array.from(value); + } else if (c !== "Object" && c !== "Number" && c !== "String" && c !== "Boolean") { + val = "instanceof_" + c; + } else if (c === "Object") { + let obj = {}; + for (const prop in value) { + if (value[prop] == null) { + obj[prop] = value[prop]; + } else if (Array.isArray(value[prop])) { + if (value[prop].length > 20) + obj[prop] = value[prop].slice(value[prop].length - 20); + else + obj[prop] = value[prop]; + } else if (value[prop].constructor.name === "Object") { + obj[prop] = {}; + for (const p in value[prop]) { + if (Array.isArray(value[prop][p])) { + if (value[prop][p].length > 20) + obj[prop][p] = value[prop][p].slice(value[prop][p].length - 20); + else + obj[prop][p] = value[prop][p]; + } else { + if (value[prop][p] != null) { + let con = value[prop][p].constructor.name; + if (con.includes("Set")) { + obj[prop][p] = Array.from(value[prop][p]); + } else if (con !== "Number" && con !== "String" && con !== "Boolean") { + obj[prop][p] = "instanceof_" + con; + } else { + obj[prop][p] = value[prop][p]; + } + } else { + obj[prop][p] = value[prop][p]; + } + } + } + } else { + let con = value[prop].constructor.name; + if (con.includes("Set")) { + obj[prop] = Array.from(value[prop]); + } else if (con !== "Number" && con !== "String" && con !== "Boolean") { + obj[prop] = "instanceof_" + con; + } else { + obj[prop] = value[prop]; + } + } + } + val = obj; + } else { + val = value; + } + } else { + val = value; + } + } + return val; + } + return function stringifyFast2(obj, space) { + parents.push(obj); + let res = JSON.stringify(obj, checkValues, space); + clear(); + return res; + }; + }(); + if (JSON.stringifyFast === void 0) { + JSON.stringifyFast = stringifyFast; + } + + // ../../services/unsafe/Unsafe.service.ts + var unsafeRoutes = { + setRoute: function(fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + if (this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__setOperator(fn); + } else { + let node = this.__node.graph.add({ __node: { tag: fnName }, __operator: fn }); + } + return true; + } + return false; + }, + setNode: function(fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + if (this.__node.graph.get(fnName)) { + this.__node.graph.get(fnName).__setOperator(fn); + } else + this.__node.graph.add({ __node: { tag: fnName }, __operator: fn }); + return true; + } + return false; + }, + setMethod: function(route, fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + if (this.__node.graph.get(route)) { + this.__node.graph.get(route)[fnName] = fn; + } else + this.__node.graph.add({ __node: { tag: fnName, [fnName]: fn } }); + return true; + } + return false; + }, + assignRoute: function(route, source) { + if (this.__node.graph.get(route) && typeof source === "object") { + Object.assign(this.__node.graph.get(route), source); + } + }, + transferClass: (classObj, className) => { + if (typeof classObj === "object") { + let str = classObj.toString(); + let message = { route: "receiveClass", args: [str, className] }; + return message; + } + return false; + }, + receiveClass: function(stringified, className) { + if (typeof stringified === "string") { + if (stringified.indexOf("class") === 0) { + let cls = (0, eval)("(" + stringified + ")"); + let name = className; + if (!name) + name = cls.name; + this.__node.graph[name] = cls; + return true; + } + } + return false; + }, + setGlobal: (key, value) => { + globalThis[key] = value; + return true; + }, + assignGlobalObject: (target, source) => { + if (!globalThis[target]) + return false; + if (typeof source === "object") + Object.assign(globalThis[target], source); + return true; + }, + setValue: function(key, value) { + this.__node.graph[key] = value; + return true; + }, + assignObject: function(target, source) { + if (!this.__node.graph[target]) + return false; + if (typeof source === "object") + Object.assign(this.__node.graph[target], source); + return true; + }, + setGlobalFunction: (fn, fnName) => { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + globalThis[fnName] = fn; + return true; + } + return false; + }, + assignFunctionToGlobalObject: function(globalObjectName, fn, fnName) { + if (!globalThis[globalObjectName]) + return false; + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + this.__node.graph[globalObjectName][fnName] = fn; + return true; + } + return false; + }, + setFunction: function(fn, fnName) { + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + this.__node.graph[fnName] = fn; + return true; + } + return false; + }, + assignFunctionToObject: function(objectName, fn, fnName) { + if (!this.__node.graph[objectName]) + return false; + if (typeof fn === "string") + fn = parseFunctionFromText(fn); + if (typeof fn === "function") { + if (!fnName) + fnName = fn.name; + this.__node.graph[objectName][fnName] = fn; + return true; + } + return false; + } + }; + + // ../../core/loaders/html/DOMElement.js + var DOMElement = class extends HTMLElement { + constructor() { + super(); + __publicField(this, "template", function(self2 = this, props) { + return `
      Custom Fragment Props: ${JSON.stringify(props)}
      `; + }); + __publicField(this, "props", {}); + __publicField(this, "useShadow", false); + __publicField(this, "styles"); + __publicField(this, "oncreate"); + __publicField(this, "onresize"); + __publicField(this, "ondelete"); + __publicField(this, "onchanged"); + __publicField(this, "renderonchanged", false); + __publicField(this, "FRAGMENT"); + __publicField(this, "STYLE"); + __publicField(this, "attachedShadow", false); + __publicField(this, "obsAttributes", ["props", "options", "onchanged", "onresize", "ondelete", "oncreate", "template"]); + __publicField(this, "attributeChangedCallback", (name, old, val) => { + if (name === "onchanged") { + let onchanged = val; + if (typeof onchanged === "string") + onchanged = parseFunctionFromText2(onchanged); + if (typeof onchanged === "function") { + this.onchanged = onchanged; + this.state.data.props = this.props; + this.state.unsubscribeTrigger("props"); + this.state.subscribeTrigger("props", this.onchanged); + let changed = new CustomEvent("changed", { detail: { props: this.props, self: this } }); + this.state.subscribeTrigger("props", () => { + this.dispatchEvent(changed); + }); + } + } else if (name === "onresize") { + let onresize = val; + if (typeof onresize === "string") + onresize = parseFunctionFromText2(onresize); + if (typeof onresize === "function") { + if (this.ONRESIZE) { + try { + window.removeEventListener("resize", this.ONRESIZE); + } catch (err) { + } + } + this.ONRESIZE = (ev) => { + this.onresize(this.props, this); + }; + this.onresize = onresize; + window.addEventListener("resize", this.ONRESIZE); + } + } else if (name === "ondelete") { + let ondelete = val; + if (typeof ondelete === "string") + ondelete = parseFunctionFromText2(ondelete); + if (typeof ondelete === "function") { + this.ondelete = () => { + if (this.ONRESIZE) + window.removeEventListener("resize", this.ONRESIZE); + this.state.unsubscribeTrigger("props"); + if (ondelete) + ondelete(this.props, this); + }; + } + } else if (name === "oncreate") { + let oncreate = val; + if (typeof oncreate === "string") + oncreate = parseFunctionFromText2(oncreate); + if (typeof oncreate === "function") { + this.oncreate = oncreate; + } + } else if (name === "renderonchanged") { + let rpc = val; + if (typeof this.renderonchanged === "number") + this.unsubscribeTrigger(this.renderonchanged); + if (typeof rpc === "string") + rpc = parseFunctionFromText2(rpc); + if (typeof rpc === "function") { + this.renderonchanged = this.state.subscribeTrigger("props", (p) => { + this.render(p); + rpc(this, p); + }); + } else if (rpc != false) + this.renderonchanged = this.state.subscribeTrigger("props", this.render); + } else if (name === "props") { + let newProps = val; + if (typeof newProps === "string") + newProps = JSON.parse(newProps); + Object.assign(this.props, newProps); + this.state.setState({ props: this.props }); + } else if (name === "template") { + let template = val; + this.template = template; + this.render(this.props); + let created = new CustomEvent("created", { detail: { props: this.props } }); + this.dispatchEvent(created); + } else { + let parsed = val; + if (name.includes("eval_")) { + name = name.split("_"); + name.shift(); + name = name.join(); + parsed = parseFunctionFromText2(val); + } else if (typeof val === "string") { + try { + parsed = JSON.parse(val); + } catch (err) { + parsed = val; + } + } + this[name] = parsed; + if (name !== "props" && this.props) + this.props[name] = parsed; + } + }); + __publicField(this, "delete", () => { + this.remove(); + if (typeof this.ondelete === "function") + this.ondelete(this.props); + }); + __publicField(this, "render", (props = this.props) => { + if (typeof this.template === "function") + this.templateResult = this.template(this, props); + else + this.templateResult = this.template; + if (this.styles) + this.templateResult = `${this.templateResult}`; + const t = document.createElement("template"); + if (typeof this.templateResult === "string") + t.innerHTML = this.templateResult; + else if (this.templateResult instanceof HTMLElement) { + if (this.templateResult.parentNode) { + this.templateResult.parentNode.removeChild(this.templateResult); + } + t.appendChild(this.templateResult); + } + const fragment = t.content; + if (this.FRAGMENT) { + if (this.useShadow) { + if (this.STYLE) + this.shadowRoot.removeChild(this.STYLE); + this.FRAGMENT.forEach((c) => { + this.shadowRoot.removeChild(c); + }); + } else + this.FRAGMENT.forEach((c) => { + this.removeChild(c); + }); + } + if (this.useShadow) { + if (!this.attachedShadow) { + this.attachShadow({ mode: "open" }).innerHTML = ""; + this.attachedShadow = true; + } + if (this.styles) { + let style = document.createElement("style"); + style.textContent = this.styles; + this.shadowRoot.prepend(style); + this.STYLE = style; + } + let len = fragment.childNodes.length; + this.shadowRoot.prepend(fragment); + this.FRAGMENT = Array.from(this.shadowRoot.childNodes).slice(0, len); + } else { + let len = fragment.childNodes.length; + this.prepend(fragment); + this.FRAGMENT = Array.from(this.childNodes).slice(0, len); + } + let rendered = new CustomEvent("rendered", { detail: { props: this.props, self: this } }); + this.dispatchEvent(rendered); + if (this.oncreate) + this.oncreate(this, props); + }); + __publicField(this, "state", { + pushToState: {}, + data: {}, + triggers: {}, + setState(updateObj) { + Object.assign(this.pushToState, updateObj); + if (Object.keys(this.triggers).length > 0) { + for (const prop of Object.getOwnPropertyNames(this.triggers)) { + if (this.pushToState[prop]) { + this.data[prop] = this.pushToState[prop]; + delete this.pushToState[prop]; + this.triggers[prop].forEach((obj) => { + obj.onchanged(this.data[prop]); + }); + } + } + } + return this.pushToState; + }, + subscribeTrigger(key, onchanged = (res) => { + }) { + if (key) { + if (!this.triggers[key]) { + this.triggers[key] = []; + } + let l = this.triggers[key].length; + this.triggers[key].push({ idx: l, onchanged }); + return this.triggers[key].length - 1; + } else + return void 0; + }, + unsubscribeTrigger(key, sub) { + let triggers = this.triggers[key]; + if (triggers) { + if (!sub) + delete this.triggers[key]; + else { + let idx = void 0; + let obj = triggers.find((o, i) => { + if (o.idx === sub) { + idx = i; + return true; + } + }); + if (obj) + triggers.splice(idx, 1); + return true; + } + } + }, + subscribeTriggerOnce(key = void 0, onchanged = (value) => { + }) { + let sub; + let changed = (value) => { + onchanged(value); + this.unsubscribeTrigger(key, sub); + }; + sub = this.subscribeTrigger(key, changed); + } + }); + } + get observedAttributes() { + return this.obsAttributes; + } + get obsAttributes() { + return this.obsAttributes; + } + set obsAttributes(att) { + if (typeof att === "string") { + this.obsAttributes.push(att); + } else if (Array.isArray(att)) + this.obsAttributes = att; + } + static get tag() { + return this.name.toLowerCase() + "-"; + } + static addElement(tag = this.tag, cls = this, extend = void 0) { + addCustomElement(cls, tag, extend); + } + connectedCallback() { + if (!this.props) + this.props = {}; + let newProps = this.getAttribute("props"); + if (typeof newProps === "string") + newProps = JSON.parse(newProps); + Object.assign(this.props, newProps); + this.state.setState({ props: this.props }); + Array.from(this.attributes).forEach((att) => { + let name = att.name; + let parsed = att.value; + if (name.includes("eval_") || name.includes("()")) { + if (name.includes("eval_")) + name = name.split("_"); + else if (name.includes("()")) + name = name.substring(0, name.indexOf("(")); + name.shift(); + name = name.join(); + parsed = parseFunctionFromText2(att.value); + } else if (typeof att.value === "string") { + try { + parsed = JSON.parse(att.value); + } catch (err) { + parsed = att.value; + } + } + if (!this[name]) { + Object.defineProperties(this, att, { + value: parsed, + writable: true, + get() { + return this[name]; + }, + set(val) { + this.setAttribute(name, val); + } + }); + } + this[name] = parsed; + if (name !== "props") + this.props[name] = parsed; + this.obsAttributes.push(name); + }); + let resizeevent = new CustomEvent("resized", { detail: { props: this.props, self: this } }); + let changed = new CustomEvent("changed", { detail: { props: this.props, self: this } }); + let deleted = new CustomEvent("deleted", { detail: { props: this.props, self: this } }); + let created = new CustomEvent("created", { detail: { props: this.props, self: this } }); + this.render(this.props); + this.dispatchEvent(created); + this.state.subscribeTrigger("props", () => { + this.dispatchEvent(changed); + }); + if (typeof this.onresize === "function") { + if (this.ONRESIZE) { + try { + window.removeEventListener("resize", this.ONRESIZE); + } catch (err) { + } + } + this.ONRESIZE = (ev) => { + this.onresize(this, this.props); + this.dispatchEvent(resizeevent); + }; + window.addEventListener("resize", this.ONRESIZE); + } + if (typeof this.ondelete === "function") { + let ondelete = this.ondelete; + this.ondelete = (props = this.props) => { + if (this.ONRESIZE) + window.removeEventListener("resize", this.ONRESIZE); + this.state.unsubscribeTrigger("props"); + this.dispatchEvent(deleted); + ondelete(this, props); + }; + } + if (typeof this.onchanged === "function") { + this.state.data.props = this.props; + this.state.subscribeTrigger("props", this.onchanged); + } + if (this.renderonchanged) { + let rpc = this.renderonchanged; + if (typeof this.renderonchanged === "number") + this.unsubscribeTrigger(this.renderonchanged); + if (typeof rpc === "string") + rpc = parseFunctionFromText2(rpc); + if (typeof rpc === "function") { + this.renderonchanged = this.state.subscribeTrigger("props", (p) => { + this.render(p); + rpc(this, p); + }); + } else if (rpc !== false) + this.renderonchanged = this.state.subscribeTrigger("props", this.render); + } + } + get props() { + return this.props; + } + set props(newProps = {}) { + this.setAttribute("props", newProps); + } + get template() { + return this.template; + } + set template(template) { + this.setAttribute("template", template); + } + get render() { + return this.render; + } + get delete() { + return this.delete; + } + get state() { + return this.state; + } + get onchanged() { + return this.onchanged; + } + set onchanged(onchanged) { + this.setAttribute("onchanged", onchanged); + } + get styles() { + return this.styles; + } + set styles(templateStr) { + this.styles = templateStr; + if (this.querySelector("style")) { + this.querySelector("style").innerHTML = templateStr; + } else { + this.render(); + } + } + get renderonchanged() { + return this.renderonchanged; + } + set renderonchanged(onchanged) { + this.setAttribute("renderonchanged", onchanged); + } + get onresize() { + return this.props; + } + set onresize(onresize) { + this.setAttribute("onresize", onresize); + } + get ondelete() { + return this.props; + } + set ondelete(ondelete) { + this.setAttribute("ondelete", ondelete); + } + get oncreate() { + return this.oncreate; + } + set oncreate(oncreate) { + this.setAttribute("oncreated", oncreate); + } + }; + function addCustomElement(cls, tag, extend = null) { + try { + if (extend) { + if (tag) + window.customElements.define(tag, cls, { extends: extend }); + else + window.customElements.define(cls.name.toLowerCase() + "-", cls, { extends: extend }); + } else { + if (tag) + window.customElements.define(tag, cls); + else + window.customElements.define(cls.name.toLowerCase() + "-", cls); + } + } catch (err) { + } + } + function parseFunctionFromText2(method) { + let getFunctionBody = (methodString) => { + return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, "$2$3$4"); + }; + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf(")"); + return methodString.slice(0, methodString.indexOf("{", startindex) + 1); + }; + let newFuncHead = getFunctionHead(method); + let newFuncBody = getFunctionBody(method); + let newFunc; + try { + if (newFuncHead.includes("function")) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody); + } else { + if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf("{") + 1, newFuncBody.length - 1)); + } else { + try { + newFunc = (0, eval)(newFuncHead + newFuncBody + "}"); + } catch (err) { + newFunc = (0, eval)(method); + } + } + } + } catch (err) { + } + return newFunc; + } + + // ../../core/loaders/html/html.loader.ts + var htmlloader = (node, parent, graph, tree, properties, key) => { + if (node.__onresize) { + let onresize = node.__onresize; + node.__onresize = (ev) => { + onresize.call(node, ev, node.__props); + }; + } + if (node.__onremove) { + let ondelete = node.__onremove; + node.__onremove = (element) => { + ondelete.call(node, element); + }; + } + if (node.__onrender) { + let onrender = node.__onrender; + node.__onrender = (element) => onrender.call(node, element); + } + if (node.tagName && !node.__props && !node.__template) { + node.__props = document.createElement(node.tagName); + let keys = Object.getOwnPropertyNames(properties); + for (const k of keys) { + if (k === "style" && typeof properties[k] === "object") { + Object.assign(node.__props.style, properties[k]); + } else + node.__props[k] = properties[k]; + } + } else if (node.__element && !node.__template) { + if (typeof node.__element === "string") + node.__element = document.createElement(node.__element); + if (!(node.__element instanceof HTMLElement)) + return; + node.__props = node.__element; + let keys = Object.getOwnPropertyNames(properties); + for (const k of keys) { + if (k === "style" && typeof properties[k] === "object") { + Object.assign(node.__props.style, properties[k]); + } else + node.__props[k] = properties[k]; + } + } else if (typeof node.__css === "string") { + node.__template = ``; + delete node.__css; + } + if (node.__template) { + if (typeof node.__renderonchanged === "function") { + let renderonchanged = node.__renderonchanged; + node.__renderonchanged = (element) => { + renderonchanged.call(element.node, element); + }; + } + class CustomElement extends DOMElement { + constructor() { + super(...arguments); + this.props = node.props; + this.styles = node.__css; + this.useShadow = node.useShadow; + this.template = node.__template; + this.oncreate = node.__onrender; + this.onresize = node.__onresize; + this.ondelete = node.__onremove; + this.renderonchanged = node.__renderonchanged; + } + } + if (node.__element) + node.tagName = node.__element; + if (!node.tagName) + node.tagName = `element${Math.floor(Math.random() * 1e15)}-`; + CustomElement.addElement(node.tagName); + node.__props = document.createElement(node.tagName); + node.__props.node = node; + let keys = Object.getOwnPropertyNames(properties); + for (const k of keys) { + if (k === "style" && typeof properties[k] === "object") { + Object.assign(node.__props.style, properties[k]); + } else + node.__props[k] = properties[k]; + } + } else if (node.__props instanceof HTMLElement) { + if (node.__onresize) + window.addEventListener("resize", node.__onresize); + } + if (node.__attributes && node.__props instanceof HTMLElement) { + for (const k in node.__attributes) { + if (k === "style" && typeof node.__attribute[k] === "object") { + Object.assign(node.__props.style, node.__attribute[k]); + } + node.__props[k] = node.__attributes[k]; + } + } + if (node.__props instanceof HTMLElement) { + node.__props.id = key; + node.__addOnconnected((n) => { + if (n.__props.parentNode) + n.__props.remove(); + if (n.parentNode) { + if (typeof n.parentNode === "string" && document.getElementById(n.parentNode)) + document.getElementById(n.parentNode).appendChild(n.__props); + else if (n.parentNode instanceof HTMLElement) + n.parentNode.appendChild(n.__props); + } else if (parent.__props instanceof HTMLElement) { + parent.__props.appendChild(node.__props); + } else if (typeof graph.parentNode === "string" && document.getElementById(n.parentNode)) { + document.getElementById(n.parentNode).appendChild(graph.__props); + } else if (graph.parentNode instanceof HTMLElement) { + graph.parentNode.appendChild(node.__props); + } else if (!(node.__props instanceof HTMLBodyElement || node.__props instanceof HTMLHeadElement)) + document.body.appendChild(node.__props); + if (node.__onrender && !node.__template) + setTimeout(() => { + node.__onrender(node.__props); + }, 0.01); + }); + node.__addOndisconnected((n) => { + n.__props.remove(); + if (typeof n.__onremove === "function") { + n.__onremove(n.__props); + } + if (n.__onresize) { + window.removeEventListener("resize", n.__onresize); + } + }); + } + }; + + // ../../services/e2ee/E2EE.service.ts + var import_sjcl = __toESM(require_sjcl()); + + // ../../services/http/HTTP.browser.ts + var _HTTPfrontend = class extends Service { + constructor(options, path, fetched) { + super(options); + this.name = "http"; + this.fetchProxied = false; + this.listening = {}; + this.GET = (url2 = "http://localhost:8080/ping", type = "", mimeType) => { + if (type === "json") + mimeType = "application/json"; + return new Promise((resolve, reject) => { + let xhr = _HTTPfrontend.request({ + method: "GET", + url: url2, + responseType: type, + mimeType, + onload: (ev) => { + let data; + if (xhr.responseType === "" || xhr.responseType === "text") + data = xhr.responseText; + else + data = xhr.response; + if (url2 instanceof URL) + url2 = url2.toString(); + this.setState({ [url2]: data }); + resolve(data); + }, + onabort: (er) => { + reject(er); + } + }); + }).catch(console.error); + }; + this.POST = (message, url2 = "http://localhost:8080/echo", type = "", mimeType) => { + if (typeof message === "object" && (type === "json" || type === "text" || !type)) { + message = JSON.stringify(message); + } + if (type === "json") + mimeType = "application/json"; + return new Promise((resolve, reject) => { + let xhr = _HTTPfrontend.request({ + method: "POST", + url: url2, + data: message, + responseType: type, + mimeType, + onload: (ev) => { + let data; + if (xhr.responseType === "" || xhr.responseType === "text") + data = xhr.responseText; + else + data = xhr.response; + if (url2 instanceof URL) + url2 = url2.toString(); + this.setState({ [url2]: data }); + resolve(data); + }, + onabort: (er) => { + reject(er); + } + }); + }).catch(console.error); + }; + this.transmit = (message, url2) => { + let obj = message; + if (typeof obj === "object") { + message = JSON.stringify(obj); + } + if (obj?.method?.toLowerCase() == "get" || message?.toLowerCase() === "get") + return this.GET(url2); + return this.POST(message, url2); + }; + this.transponder = (url2, message, type = "", mimeType) => { + if (typeof message === "object") + message = JSON.stringify(message); + let method = "GET"; + if (message) { + method = "POST"; + } + if (type === "json") + mimeType = "application/json"; + else + return new Promise((resolve, reject) => { + let xhr = _HTTPfrontend.request({ + method, + url: url2, + data: message, + responseType: type, + onload: (ev) => { + let body = xhr.response; + if (typeof body === "string") { + let substr = body.substring(0, 8); + if (substr.includes("{") || substr.includes("[")) { + if (substr.includes("\\")) + body = body.replace(/\\/g, ""); + if (body[0] === '"') { + body = body.substring(1, body.length - 1); + } + ; + body = JSON.parse(body); + } + } + if (typeof body?.method === "string") { + return resolve(this.handleMethod(body.route, body.method, body.args)); + } else if (typeof body?.route === "string") { + return resolve(this.handleServiceMessage(body)); + } else if (typeof body?.node === "string" || body.node instanceof GraphNode) { + return resolve(this.handleGraphNodeCall(body.node, body.args)); + } else + return resolve(body); + }, + onabort: (er) => { + reject(er); + } + }); + }).catch(console.error); + }; + this.listen = (path = "0", fetched = async (clone, args, response) => { + const result = await clone.text(); + const returned = this.receive(result); + this.setState({ [response.url]: returned }); + }) => { + this.listening[path] = {}; + let listenerId = `${path}${Math.floor(Math.random() * 1e15)}`; + this.listening[path][listenerId] = fetched; + if (!this.fetchProxied) { + globalThis.fetch = new Proxy(globalThis.fetch, { + apply(fetch, that, args) { + const result = fetch.apply(that, args); + result.then((response) => { + if (!response.ok) + return; + if (this.listening["0"]) { + for (const key in this.listeners) { + const clone = response.clone(); + this.listening["0"][key](clone, args, response); + } + } else { + for (const key in this.listening) { + if (response.url.includes(key)) { + for (const key2 in this.listening[path]) { + const clone = response.clone(); + this.listening[path][key2](clone, args, response); + } + break; + } + } + } + }).catch((er) => { + console.error(er); + }); + return result; + } + }); + this.fetchProxied = true; + } + return listenerId; + }; + this.stopListening = (path, listener) => { + if (!path && path !== 0) { + for (const key in this.listening) + delete this.listening[key]; + } else { + if (!listener) + delete this.listening[path]; + else + delete this.listening[listener]; + } + }; + this.setTree(this); + this.listen(path, fetched); + } + }; + var HTTPfrontend = _HTTPfrontend; + HTTPfrontend.request = (options) => { + const xhr = new XMLHttpRequest(); + if (options.responseType) + xhr.responseType = options.responseType; + else + options.responseType = "json"; + if (options.mimeType) { + xhr.overrideMimeType(options.mimeType); + } + if (options.onload) + xhr.addEventListener("load", options.onload, false); + if (options.onprogress) + xhr.addEventListener("progress", options.onprogress, false); + if (options.onabort) + xhr.addEventListener("abort", options.onabort, false); + if (options.onloadend) + xhr.addEventListener("loadend", options.onloadend, false); + if (options.onerror) + xhr.addEventListener("error", options.onerror, false); + xhr.open(options.method, options.url, true, options.user, options.pass); + if (!options.onerror) + xhr.onerror = function() { + xhr.abort(); + }; + xhr.send(options.data); + return xhr; + }; + + // ../../services/worker/Worker.service.ts + var import_web_worker = __toESM(require_browser()); + var WorkerService = class extends Service { + constructor(options) { + super(); + this.name = "worker"; + this.workers = {}; + this.threadRot = 0; + this.loadWorkerRoute = (rt, routeKey) => { + if (rt.workerUrl) + rt.url = rt.workerUrl; + if (rt.workerId) + rt.__node.tag = rt.workerId; + if (!rt.__node.tag) + rt.__node.tag = routeKey; + rt._id = rt.__node.tag; + let worker; + if (this.workers[rt._id]) + worker = this.workers[rt._id]; + else if (rt.worker) + worker = rt.worker; + if (!worker) { + worker = this.addWorker(rt); + let ondelete = (rt2) => { + rt2.worker?.terminate(); + }; + rt.__addOndisconnected(ondelete); + } + rt.worker = worker; + if (rt.transferFunctions) { + for (const prop in rt.transferFunctions) { + this.transferFunction(worker, rt.transferFunctions[prop], prop); + } + } + if (rt.transferClasses) { + for (const prop in rt.transferClasses) { + this.transferClass(worker, rt.transferClasses[prop], prop); + } + } + if (worker) { + if (!rt.__operator) { + rt.__operator = (...args) => { + if (rt.callback) { + if (!this.__node.nodes.get(rt.__node.tag)?.__children) + worker.post(rt.callback, args); + else + return worker.run(rt.callback, args); + } else { + if (!this.__node.nodes.get(rt.__node.tag)?.__children) + worker.send(args); + else + return worker.request(args); + } + }; + } + if (rt.init) { + worker.run(rt.init, rt.initArgs, rt.initTransfer); + } + return worker; + } + }; + this.workerloader = { + "workers": (node, parent, graph, tree) => { + let rt = node; + if (!node.parentRoute && (parent?.callback && parent?.worker)) + node.parentRoute = parent?.callback; + if (rt?.worker || rt?.workerId || rt?.workerUrl) { + let worker = this.loadWorkerRoute(rt, rt.__node.tag); + if (worker) { + if (!rt.parentRoute && rt.__parent?.callback) + rt.parentRoute = rt.__parent.callback; + if (rt.__parent && !rt.portId) { + if (typeof rt.__parent === "string") { + if (rt.__node.tag !== rt.__parent && worker._id !== rt.__parent) + rt.portId = this.establishMessageChannel(worker, rt.__parent); + } else if (rt.__node.tag !== rt.__parent?.__node?.tag && worker._id !== rt.__parent.tag) { + rt.portId = this.establishMessageChannel(worker, rt.__parent.worker); + } + } + ; + if (rt.parentRoute) { + if (!rt.stopped) { + if (typeof rt.__parent === "string" && rt.__parent === worker._id) { + worker.run("subscribe", [rt.parentRoute, void 0, rt.callback]); + } else if (rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag) { + worker.run("subscribe", [rt.parentRoute, void 0, rt.callback]); + } else + worker.run("subscribeToWorker", [rt.parentRoute, rt.portId, rt.callback, rt.blocking]).then((sub) => { + worker.workerSubs[rt.parentRoute + rt.portId].sub = sub; + }); + } + if (!(typeof rt.__parent === "string" && rt.__parent === worker._id) && !(rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag)) + worker.workerSubs[rt.parentRoute + rt.portId] = { sub: null, route: rt.parentRoute, portId: rt.portId, callback: rt.callback, blocking: rt.blocking }; + } else if (rt.__parent) { + if (typeof rt.__parent === "string") { + if (!rt.stopped) { + if (rt.__parent === worker._id) { + worker.run("subscribe", [rt.__parent, void 0, rt.callback]); + } else + worker.run("subscribeToWorker", [rt.__parent, rt.portId, rt.callback, rt.blocking]).then((sub) => { + worker.workerSubs[rt.__parent + rt.portId].sub = sub; + }); + } + if (!(typeof rt.__parent === "string" && rt.__parent === worker._id)) + worker.workerSubs[rt.__parent + rt.portId] = { sub: null, route: worker._id, portId: rt.portId, callback: rt.callback, blocking: rt.blocking }; + } else if (rt.__parent?.__node?.tag && rt.__parent?.worker) { + if (!rt.stopped) { + if (rt.__node.tag === rt.__parent.__node.tag || worker._id === rt.__parent.__node.tag) { + worker.run("subscribe", [rt.__parent.__node.tag, void 0, rt.callback]); + } else + worker.run("subscribeToWorker", [rt.__parent.__node.tag, rt.portId, rt.callback, rt.blocking]).then((sub) => { + worker.workerSubs[rt.__parent.__node.tag + rt.portId].sub = sub; + }); + } + if (!(rt.__node.tag === rt.__parent?.__node?.tag || worker._id === rt.__parent?.__node?.tag)) + worker.workerSubs[rt.__parent.__node.tag + rt.portId] = { sub: null, route: rt.__parent.__node.tag, portId: rt.portId, callback: rt.callback, blocking: rt.blocking }; + } + } + } + } else if (rt.__parent && rt.parentRoute) { + if (typeof rt.__parent === "string" && tree[rt.__parent]?.worker) { + tree[rt.__parent].worker.subscribe(rt.parentRoute, rt.__operator, rt.blocking); + } else if (rt.__parent?.worker) { + rt.__parent.worker.subscribe(rt.parentRoute, rt.__operator, rt.blocking); + } + } + return rt; + } + }; + this.addDefaultMessageListener = () => { + globalThis.onmessage = (ev) => { + let result = this.receive(ev.data); + if (this.__node.keepState) + this.setState({ [this.name]: result }); + }; + }; + this.postMessage = (message, target, transfer) => { + if (this.workers[target]) { + this.workers[target].send(message, transfer); + } else { + globalThis.postMessage(message, target, transfer); + } + }; + this.addWorker = (options) => { + let worker; + if (!options._id) + options._id = `worker${Math.floor(Math.random() * 1e15)}`; + if (options.url) + worker = new import_web_worker.default(options.url); + else if (options.port) { + worker = options.port; + } else if (this.workers[options._id]) { + if (this.workers[options._id].port) + worker = this.workers[options._id].port; + else + worker = this.workers[options._id].worker; + } + if (!worker) + return; + let send = (message, transfer) => { + return this.transmit(message, worker, transfer); + }; + let post = (route, args, transfer, method) => { + let message = { + route, + args + }; + if (method) + message.method = method; + return this.transmit(message, worker, transfer); + }; + let run = (route, args, transfer, method) => { + return new Promise((res, rej) => { + let callbackId = Math.random(); + let req = { route: "runRequest", args: [{ route, args }, options._id, callbackId] }; + if (method) + req.args[0].method = method; + let onmessage = (ev) => { + if (typeof ev.data === "object") { + if (ev.data.callbackId === callbackId) { + worker.removeEventListener("message", onmessage); + res(ev.data.args); + } + } + }; + worker.addEventListener("message", onmessage); + this.transmit(req, worker, transfer); + }); + }; + let request = (message, transfer, method) => { + return new Promise((res, rej) => { + let callbackId = Math.random(); + let req = { route: "runRequest", args: [message, options._id, callbackId] }; + if (method) + req.method = method; + let onmessage = (ev) => { + if (typeof ev.data === "object") { + if (ev.data.callbackId === callbackId) { + worker.removeEventListener("message", onmessage); + res(ev.data.args); + } + } + }; + worker.addEventListener("message", onmessage); + this.transmit(req, worker, transfer); + }); + }; + let workerSubs = {}; + let subscribe = (route, callback, blocking) => { + return this.subscribeToWorker(route, options._id, callback, blocking); + }; + let unsubscribe = (route, sub) => { + return run("unsubscribe", [route, sub]); + }; + let start = async (route, portId, callback, blocking) => { + if (route) + await run("subscribeToWorker", [route, portId, callback, blocking]).then((sub) => { + if (sub) + workerSubs[route + portId] = { sub, route, portId, callback, blocking }; + }); + else + for (const key in workerSubs) { + if (typeof workerSubs[key].sub !== "number") + await run("subscribeToWorker", [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].callback, workerSubs[key].blocking]).then((sub) => { + workerSubs[key].sub = sub; + }); + } + return true; + }; + let stop = async (route, portId) => { + if (route && portId && workerSubs[route + portId]) { + await run("unsubscribe", [route, workerSubs[route + portId].sub]); + workerSubs[route + portId].sub = false; + } else { + for (const key in workerSubs) { + if (typeof workerSubs[key].sub === "number") { + await run("unpipeWorkers", [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]); + } + workerSubs[key].sub = false; + } + } + return true; + }; + let terminate = () => { + for (const key in workerSubs) { + if (typeof workerSubs[key].sub === "number") { + run("unpipeWorkers", [workerSubs[key].route, workerSubs[key].portId, workerSubs[key].sub]); + } + workerSubs[key].sub = false; + } + return this.terminate(options._id); + }; + if (!options.onmessage) + options.onmessage = (ev) => { + this.receive(ev.data); + this.setState({ [options._id]: ev.data }); + }; + if (!options.onerror) { + options.onerror = (ev) => { + console.error(ev.data); + }; + } + worker.onmessage = options.onmessage; + worker.onerror = options.onerror; + this.workers[options._id] = { + worker, + send, + post, + run, + request, + subscribe, + unsubscribe, + terminate, + start, + stop, + postMessage: worker.postMessage, + workerSubs, + graph: this, + ...options + }; + return this.workers[options._id]; + }; + this.toObjectURL = (scriptTemplate) => { + let blob = new Blob([scriptTemplate], { type: "text/javascript" }); + return URL.createObjectURL(blob); + }; + this.transmit = (message, worker, transfer) => { + if (!transfer) { + transfer = this.getTransferable(message); + } + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) { + worker.postMessage(message, transfer); + } else if (typeof worker === "string") { + if (this.workers[worker]) { + if (this.workers[worker].port) + this.workers[worker].port.postMessage(message, transfer); + else if (this.workers[worker].worker) + this.workers[worker].worker.postMessage(message, transfer); + } + } else { + let keys = Object.keys(this.workers); + this.workers[keys[this.threadRot]].worker.postMessage(message, transfer); + this.threadRot++; + if (this.threadRot === keys.length) + this.threadRot = 0; + } + return message; + }; + this.terminate = (worker) => { + let onclose; + if (typeof worker === "string") { + let obj = this.workers[worker]; + if (obj) { + delete this.workers[worker]; + worker = obj.worker; + if (obj.onclose) + onclose = obj.onclose; + } + } + if (worker instanceof import_web_worker.default) { + worker.terminate(); + if (onclose) + onclose(worker); + return true; + } + if (worker instanceof MessagePort) { + worker.close(); + if (onclose) + onclose(worker); + return true; + } + return false; + }; + this.establishMessageChannel = (worker, worker2) => { + let workerId; + if (typeof worker === "string") { + workerId = worker; + if (this.workers[worker]) { + if (this.workers[worker].port) + worker = this.workers[worker].port; + else + worker2 = this.workers[worker].worker; + } + } else if (worker?.worker) { + worker = worker.worker; + } + if (typeof worker2 === "string") { + if (this.workers[worker2]) { + if (this.workers[worker2].port) + worker2 = this.workers[worker2].port; + else + worker2 = this.workers[worker2].worker; + } + } else if (worker2?.worker) { + worker2 = worker2.worker; + } + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) { + let channel = new MessageChannel(); + let portId = `port${Math.floor(Math.random() * 1e15)}`; + worker.postMessage({ route: "addWorker", args: { port: channel.port1, _id: portId } }, [channel.port1]); + if (worker2 instanceof import_web_worker.default || worker2 instanceof MessagePort) { + worker2.postMessage({ route: "addWorker", args: { port: channel.port2, _id: portId } }, [channel.port2]); + } else if (workerId && this.workers[workerId]) { + channel.port2.onmessage = this.workers[workerId].onmessage; + this.workers[workerId].port = channel.port2; + } + return portId; + } + return false; + }; + this.request = (message, workerId, transfer, method) => { + let worker = this.workers[workerId].worker; + return new Promise((res, rej) => { + let callbackId = Math.random(); + let req = { route: "runRequest", args: [message, callbackId] }; + if (method) + req.method = method; + let onmessage = (ev) => { + if (typeof ev.data === "object") { + if (ev.data.callbackId === callbackId) { + worker.removeEventListener("message", onmessage); + res(ev.data.args); + } + } + }; + worker.addEventListener("message", onmessage); + this.transmit(req, worker, transfer); + }); + }; + this.runRequest = (message, worker, callbackId) => { + let res = this.receive(message); + if (typeof worker === "string" && this.workers[worker]) { + if (this.workers[worker].port) + worker = this.workers[worker].port; + else + worker = this.workers[worker].worker; + } + if (res instanceof Promise) { + res.then((r) => { + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) + worker.postMessage({ args: r, callbackId }); + else if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) + globalThis.postMessage({ args: r, callbackId }); + }); + } else { + if (worker instanceof import_web_worker.default || worker instanceof MessagePort) + worker.postMessage({ args: res, callbackId }); + else if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) + globalThis.postMessage({ args: res, callbackId }); + } + return res; + }; + this.subscribeWorker = (route, worker, blocking, key, subInput) => { + let callback; + if (blocking) { + let blocked = false; + callback = (res) => { + if (!blocked) { + blocked = true; + if (res instanceof Promise) { + res.then((r) => { + if (worker?.run) + worker.run("triggerSubscription", [route, worker._id, r]).then((ret2) => { + blocked = false; + }); + }); + } else { + if (worker?.run) + worker.run("triggerSubscription", [route, worker._id, res]).then((ret2) => { + blocked = false; + }); + } + } + }; + } else { + callback = (res) => { + if (res instanceof Promise) { + res.then((r) => { + if (worker?.postMessage) + worker.postMessage({ args: r, callbackId: route }); + else if (globalThis.postMessage) + globalThis.postMessage({ args: r, callbackId: route }); + }); + } else { + if (worker?.postMessage) + worker.postMessage({ args: res, callbackId: route }); + else if (globalThis.postMessage) + globalThis.postMessage({ args: res, callbackId: route }); + } + }; + } + if (!blocking && worker?.port) { + worker = worker.port; + } else if (!blocking && worker?.worker) { + worker = worker.worker; + } else if (typeof worker === "string" && this.workers[worker]) { + if (blocking) + worker = this.workers[worker]; + else if (this.workers[worker].port) + worker = this.workers[worker].port; + else + worker = this.workers[worker].worker; + } + return this.subscribe(route, callback, key, subInput); + }; + this.subscribeToWorker = (route, workerId, callback, blocking, key, subInput) => { + if (typeof workerId === "string" && this.workers[workerId]) { + this.__node.state.subscribeTrigger(workerId, (res) => { + if (res?.callbackId === route) { + if (!callback) + this.setState({ [workerId]: res.args }); + else if (typeof callback === "string") { + this.run(callback, res.args); + } else + callback(res.args); + } + }); + return this.workers[workerId].run("subscribeWorker", [route, workerId, blocking, key, subInput]); + } + }; + this.triggerSubscription = async (route, workerId, result) => { + if (this.__node.state.triggers[workerId]) + for (let i = 0; i < this.__node.state.triggers[workerId].length; i++) { + await this.__node.state.triggers[workerId][i].onchange({ args: result, callbackId: route }); + } + return true; + }; + this.pipeWorkers = (sourceWorker, listenerWorker, sourceRoute, listenerRoute, portId, blocking) => { + if (typeof sourceWorker === "string") + sourceWorker = this.workers[sourceWorker]; + if (typeof listenerWorker === "string") + listenerWorker = this.workers[listenerWorker]; + if (!portId) { + portId = this.establishMessageChannel(sourceWorker.worker, listenerWorker.worker); + } + return listenerWorker.run("subscribeToWorker", [sourceRoute, portId, listenerRoute, blocking]); + }; + this.unpipeWorkers = (sourceRoute, sourceWorker, sub) => { + if (typeof sourceWorker === "string") + sourceWorker = this.workers[sourceWorker]; + if (sourceWorker) + return sourceWorker.run("unsubscribe", [sourceRoute, sub]); + }; + this.connections = { + workers: this.workers + }; + if (options?.services) + this.addServices(options.services); + this.setLoaders(this.workerloader); + if (options) + this.init(options); + if (typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope) { + this.addDefaultMessageListener(); + } + } + getTransferable(message) { + let transfer; + if (typeof message === "object") { + if (message.args) { + if (message.args?.constructor?.name === "Object") { + for (const key in message.args) { + if (ArrayBuffer.isView(message.args[key])) { + if (!transfer) + transfer = [message.args[key].buffer]; + else + transfer.push(message.args[key].buffer); + } else if (message.args[key]?.constructor?.name === "ArrayBuffer") { + if (!transfer) + transfer = [message.args[key]]; + else + transfer.push(message.args[key]); + } + } + } else if (Array.isArray(message.args) && message.args.length < 11) { + message.args.forEach((arg) => { + if (ArrayBuffer.isView(arg)) { + transfer = [arg.buffer]; + } else if (arg?.constructor?.name === "ArrayBuffer") + transfer = [arg]; + }); + } else if (ArrayBuffer.isView(message.args)) { + transfer = [message.args.buffer]; + } else if (message.args?.constructor?.name === "ArrayBuffer") { + transfer = [message]; + } + } else if (message?.constructor?.name === "Object") { + for (const key in message) { + if (ArrayBuffer.isView(message[key])) { + if (!transfer) + transfer = [message[key].buffer]; + else + transfer.push(message[key].buffer); + } else if (message[key]?.constructor?.name === "ArrayBuffer") { + if (!transfer) + transfer = [message[key]]; + else + transfer.push(message[key]); + } + } + } else if (Array.isArray(message) && message.length < 11) { + message.forEach((arg) => { + if (ArrayBuffer.isView(arg)) { + transfer = [arg.buffer]; + } else if (arg.constructor?.name === "ArrayBuffer") + transfer = [arg]; + }); + } else if (ArrayBuffer.isView(message)) { + transfer = [message.buffer]; + } else if (message.constructor?.name === "ArrayBuffer") { + transfer = [message]; + } + } + return transfer; + } + transferFunction(worker, fn, fnName) { + if (!fnName) + fnName = fn.name; + return worker.request({ + route: "setRoute", + args: [ + fn.toString(), + fnName + ] + }); + } + transferClass(worker, cls, className) { + if (!className) + className = cls.name; + return worker.request({ + route: "receiveClass", + args: [ + cls.toString(), + className + ] + }); + } + }; + + // ../../services/worker/ProxyListener.ts + var mouseEventHandler = makeSendPropertiesHandler([ + "ctrlKey", + "metaKey", + "shiftKey", + "button", + "pointerType", + "clientX", + "clientY", + "pageX", + "pageY" + ]); + var wheelEventHandlerImpl = makeSendPropertiesHandler([ + "deltaX", + "deltaY" + ]); + var keydownEventHandler = makeSendPropertiesHandler([ + "ctrlKey", + "metaKey", + "shiftKey", + "keyCode" + ]); + function wheelEventHandler(event, sendFn) { + event.preventDefault(); + wheelEventHandlerImpl(event, sendFn); + } + function preventDefaultHandler(event) { + event.preventDefault(); + } + function copyProperties(src, properties, dst) { + for (const name of properties) { + dst[name] = src[name]; + } + } + function makeSendPropertiesHandler(properties) { + return function sendProperties(event, sendFn) { + const data = { type: event.type }; + copyProperties(event, properties, data); + sendFn(data); + }; + } + function touchEventHandler(event, sendFn) { + const touches = []; + const data = { type: event.type, touches }; + for (let i = 0; i < event.touches.length; ++i) { + const touch = event.touches[i]; + touches.push({ + pageX: touch.pageX, + pageY: touch.pageY + }); + } + sendFn(data); + } + var orbitKeys = { + "37": true, + "38": true, + "39": true, + "40": true + }; + function filteredKeydownEventHandler(event, sendFn) { + const { keyCode } = event; + if (orbitKeys[keyCode]) { + event.preventDefault(); + keydownEventHandler(event, sendFn); + } + } + var eventHandlers = { + contextmenu: preventDefaultHandler, + mousedown: mouseEventHandler, + mousemove: mouseEventHandler, + mouseup: mouseEventHandler, + pointerdown: mouseEventHandler, + pointermove: mouseEventHandler, + pointerup: mouseEventHandler, + touchstart: touchEventHandler, + touchmove: touchEventHandler, + touchend: touchEventHandler, + wheel: wheelEventHandler, + keydown: filteredKeydownEventHandler + }; + function initProxyElement(element, worker, id) { + if (!id) + id = "proxy" + Math.floor(Math.random() * 1e15); + const sendEvent = (data) => { + if (!worker) { + handleProxyEvent(data, id); + } else + worker.postMessage({ route: "handleProxyEvent", args: [data, id] }); + }; + let entries = Object.entries(eventHandlers); + for (const [eventName, handler2] of entries) { + element.addEventListener(eventName, function(event) { + handler2(event, sendEvent); + }); + } + const sendSize = () => { + const rect = element.getBoundingClientRect(); + sendEvent({ + type: "resize", + left: rect.left, + top: rect.top, + width: element.clientWidth, + height: element.clientHeight + }); + }; + sendSize(); + globalThis.addEventListener("resize", sendSize); + return id; + } + var EventDispatcher = class { + addEventListener(type, listener) { + if (this.__listeners === void 0) + this.__listeners = {}; + const listeners2 = this.__listeners; + if (listeners2[type] === void 0) { + listeners2[type] = []; + } + if (listeners2[type].indexOf(listener) === -1) { + listeners2[type].push(listener); + } + } + hasEventListener(type, listener) { + if (this.__listeners === void 0) + return false; + const listeners2 = this.__listeners; + return listeners2[type] !== void 0 && listeners2[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + if (this.__listeners === void 0) + return; + const listeners2 = this.__listeners; + const listenerArray = listeners2[type]; + if (listenerArray !== void 0) { + const index = listenerArray.indexOf(listener); + if (index !== -1) { + listenerArray.splice(index, 1); + } + } + } + dispatchEvent(event, target) { + if (this.__listeners === void 0) + return; + const listeners2 = this.__listeners; + const listenerArray = listeners2[event.type]; + if (listenerArray !== void 0) { + if (!target) + event.target = this; + else + event.target = target; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length; i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } + }; + function noop() { + } + var ElementProxyReceiver = class extends EventDispatcher { + constructor() { + super(); + this.__listeners = {}; + this.style = {}; + this.setPointerCapture = () => { + }; + this.releasePointerCapture = () => { + }; + this.getBoundingClientRect = () => { + return { + left: this.left, + top: this.top, + width: this.width, + height: this.height, + right: this.left + this.width, + bottom: this.top + this.height + }; + }; + this.handleEvent = (data) => { + if (data.type === "resize") { + this.left = data.left; + this.top = data.top; + this.width = data.width; + this.height = data.height; + if (typeof this.proxied === "object") { + this.proxied.style.width = this.width + "px"; + this.proxied.style.height = this.height + "px"; + this.proxied.clientWidth = this.width; + this.proxied.clientHeight = this.height; + } + } + data.preventDefault = noop; + data.stopPropagation = noop; + this.dispatchEvent(data, this.proxied); + }; + this.style = {}; + } + get clientWidth() { + return this.width; + } + get clientHeight() { + return this.height; + } + focus() { + } + }; + var ProxyManager = class { + constructor() { + this.targets = {}; + this.makeProxy = (id, addTo = void 0) => { + if (!id) + id = `proxyReceiver${Math.floor(Math.random() * 1e15)}`; + let proxy; + if (this.targets[id]) + proxy = this.targets[id]; + else { + proxy = new ElementProxyReceiver(); + this.targets[id] = proxy; + } + if (typeof addTo === "object") { + addTo.proxy = proxy; + proxy.proxied = addTo; + if (typeof WorkerGlobalScope !== "undefined") + addTo.style = proxy.style; + if (proxy.width) { + addTo.style.width = proxy.width + "px"; + addTo.clientWidth = proxy.width; + } + if (proxy.height) { + addTo.style.height = proxy.height + "px"; + addTo.clientHeight = proxy.height; + } + addTo.setPointerCapture = proxy.setPointerCapture.bind(proxy); + addTo.releasePointerCapture = proxy.releasePointerCapture.bind(proxy); + addTo.getBoundingClientRect = proxy.getBoundingClientRect.bind(proxy); + addTo.addEventListener = proxy.addEventListener.bind(proxy); + addTo.removeEventListener = proxy.removeEventListener.bind(proxy); + addTo.handleEvent = proxy.handleEvent.bind(proxy); + addTo.dispatchEvent = proxy.dispatchEvent.bind(proxy); + addTo.focus = proxy.focus.bind(proxy); + } + }; + this.getProxy = (id) => { + return this.targets[id]; + }; + this.handleEvent = (data, id) => { + if (!this.targets[id]) + this.makeProxy(id); + if (this.targets[id]) { + this.targets[id].handleEvent(data); + return true; + } + return void 0; + }; + if (!globalThis.document) + globalThis.document = {}; + } + }; + function makeProxy(id, elm) { + if (this?.__node?.graph) { + if (!this.__node.graph.ProxyManager) + this.__node.graph.ProxyManager = new ProxyManager(); + this.__node.graph.ProxyManager.makeProxy(id, elm); + } else { + if (!globalThis.ProxyManager) + globalThis.ProxyManager = new ProxyManager(); + globalThis.ProxyManager.makeProxy(id, elm); + } + return id; + } + function handleProxyEvent(data, id) { + if (this?.__node?.graph) { + if (!this.__node.graph.ProxyManager) + this.__node.graph.ProxyManager = new ProxyManager(); + if (this.__node.graph.ProxyManager.handleEvent(data, id)) + return data; + } else { + if (!globalThis.ProxyManager) + globalThis.ProxyManager = new ProxyManager(); + if (globalThis.ProxyManager.handleEvent(data, id)) + return data; + } + } + var proxyElementWorkerRoutes = { + initProxyElement, + makeProxy, + handleProxyEvent + }; + + // ../../services/worker/WorkerCanvas.ts + function Renderer(options) { + if (options.worker) { + let worker = options.worker; + let route = options.route; + if (worker instanceof Blob || typeof worker === "string") { + worker = new Worker(worker); + } + delete options.worker; + delete options.route; + return transferCanvas(worker, options, route); + } else { + initProxyElement(options.canvas, void 0, options._id); + return setupCanvas(options); + } + } + function transferCanvas(worker, options, route) { + if (!options) + return void 0; + if (!options._id) + options._id = `canvas${Math.floor(Math.random() * 1e15)}`; + let offscreen = options.canvas.transferControlToOffscreen(); + if (!options.width) + options.width = options.canvas.clientWidth; + if (!options.height) + options.height = options.canvas.clientHeight; + let message = { route: route ? route : "setupCanvas", args: { + ...options, + canvas: offscreen + } }; + if (this?.__node?.graph) + this.__node.graph.run("initProxyElement", options.canvas, worker, options._id); + else + initProxyElement(options.canvas, worker, options._id); + if (options.draw) { + if (typeof options.draw === "function") + message.args.draw = options.draw.toString(); + else + message.args.draw = options.draw; + } + if (options.update) { + if (typeof options.update === "function") + message.args.update = options.update.toString(); + else + message.args.update = options.update; + } + if (options.init) { + if (typeof options.init === "function") + message.args.init = options.init.toString(); + else + message.args.init = options.init; + } + if (options.clear) { + if (typeof options.clear === "function") + message.args.clear = options.clear.toString(); + else + message.args.clear = options.clear; + } + let transfer = [offscreen]; + if (options.transfer) { + transfer.push(...options.transfer); + delete options.transfer; + } + worker.postMessage(message, transfer); + const canvascontrols = { + _id: options._id, + width: options.width, + height: options.height, + worker, + draw: (props) => { + worker.postMessage({ route: "drawFrame", args: [props, options._id] }); + }, + update: (props) => { + worker.postMessage({ route: "updateCanvas", args: [props, options._id] }); + }, + clear: () => { + worker.postMessage({ route: "clearCanvas", args: options._id }); + }, + init: () => { + worker.postMessage({ route: "initCanvas", args: options._id }); + }, + stop: () => { + worker.postMessage({ route: "stopAnim", args: options._id }); + }, + start: () => { + worker.postMessage({ route: "startAnim", args: options._id }); + }, + set: (newDrawProps) => { + worker.postMessage({ route: "setDraw", args: [newDrawProps, options._id] }); + }, + terminate: () => { + worker.terminate(); + } + }; + return canvascontrols; + } + function setDraw(settings, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (_id) + canvasopts = this.__node.graph.CANVASES?.[settings._id]; + else if (settings._id) + canvasopts = this.__node.graph.CANVASES?.[settings._id]; + else + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + } else { + if (_id) + canvasopts = globalThis.CANVASES?.[settings._id]; + else if (settings._id) + canvasopts = globalThis.CANVASES?.[settings._id]; + else + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + } + if (canvasopts) { + if (settings.canvas) { + canvasopts.canvas = settings.canvas; + if (this?.__node?.graph) + this.__node.graph.run("makeProxy", canvasopts._id, canvasopts.canvas); + else + proxyElementWorkerRoutes.makeProxy(canvasopts._id, canvasopts.canvas); + } + if (typeof settings.context === "string") + canvasopts.context = canvasopts.canvas.getContext(settings.context); + else if (settings.context) + canvasopts.context = settings.context; + if (settings.width) + canvasopts.canvas.width = settings.width; + if (settings.height) + canvasopts.canvas.height = settings.height; + if (typeof settings.draw === "string") + settings.draw = parseFunctionFromText3(settings.draw); + if (typeof settings.draw === "function") { + canvasopts.draw = settings.draw; + } + if (typeof settings.update === "string") + settings.update = parseFunctionFromText3(settings.update); + if (typeof settings.update === "function") { + canvasopts.update = settings.update; + } + if (typeof settings.init === "string") + settings.init = parseFunctionFromText3(settings.init); + if (typeof settings.init === "function") { + canvasopts.init = settings.init; + } + if (typeof settings.clear === "string") + settings.clear = parseFunctionFromText3(settings.clear); + if (typeof settings.clear === "function") { + canvasopts.clear = settings.clear; + } + return settings._id; + } + return void 0; + } + function setupCanvas(options) { + if (this?.__node?.graph) { + if (!this.__node.graph.CANVASES) + this.__node.graph.CANVASES = {}; + } else if (!globalThis.CANVASES) + globalThis.CANVASES = {}; + let canvasOptions = options; + options._id ? canvasOptions._id = options._id : canvasOptions._id = `canvas${Math.floor(Math.random() * 1e15)}`; + typeof options.context === "string" ? canvasOptions.context = options.canvas.getContext(options.context) : canvasOptions.context = options.context; + "animating" in options ? canvasOptions.animating = options.animating : canvasOptions.animating = true; + if (this?.__node?.graph?.CANVASES[canvasOptions._id]) { + this.__node.graph.run("setDraw", canvasOptions); + } else if (globalThis.CANVASES?.[canvasOptions._id]) { + setDraw(canvasOptions); + } else { + if (this?.__node?.graph) + canvasOptions.graph = this.__node.graph; + if (this?.__node?.graph) + this.__node.graph.CANVASES[canvasOptions._id] = canvasOptions; + else + globalThis.CANVASES[canvasOptions._id] = canvasOptions; + if (this?.__node?.graph) + this.__node.graph.run("makeProxy", canvasOptions._id, canvasOptions.canvas); + else + proxyElementWorkerRoutes.makeProxy(canvasOptions._id, canvasOptions.canvas); + if (options.width) + canvasOptions.canvas.width = options.width; + if (options.height) + canvasOptions.canvas.height = options.height; + if (typeof canvasOptions.draw === "string") { + canvasOptions.draw = parseFunctionFromText3(canvasOptions.draw); + } else if (typeof canvasOptions.draw === "function") { + canvasOptions.draw = canvasOptions.draw; + } + if (typeof canvasOptions.update === "string") { + canvasOptions.update = parseFunctionFromText3(canvasOptions.update); + } else if (typeof canvasOptions.update === "function") { + canvasOptions.update = canvasOptions.update; + } + if (typeof canvasOptions.init === "string") { + canvasOptions.init = parseFunctionFromText3(canvasOptions.init); + } else if (typeof canvasOptions.init === "function") { + canvasOptions.init = canvasOptions.init; + } + if (typeof canvasOptions.clear === "string") { + canvasOptions.clear = parseFunctionFromText3(canvasOptions.clear); + } else if (typeof canvasOptions.clear === "function") { + canvasOptions.clear = canvasOptions.clear; + } + if (typeof canvasOptions.init === "function") + canvasOptions.init(canvasOptions, canvasOptions.canvas, canvasOptions.context); + canvasOptions.stop = () => { + stopAnim(canvasOptions._id); + }; + canvasOptions.start = (draw) => { + startAnim(canvasOptions._id, draw); + }; + canvasOptions.set = (settings) => { + setDraw(settings, canvasOptions._id); + }; + if (typeof canvasOptions.draw === "function" && canvasOptions.animating) { + let draw = (s, canvas, context) => { + if (s.animating) { + s.draw(s, canvas, context); + requestAnimationFrame(() => { + draw(s, canvas, context); + }); + } + }; + draw(canvasOptions, canvasOptions.canvas, canvasOptions.context); + } + } + if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) + return canvasOptions._id; + else { + const canvascontrols = { + _id: options._id, + width: options.width, + height: options.height, + draw: (props) => { + drawFrame(props, options._id); + }, + update: (props) => { + updateCanvas(props, options._id); + }, + clear: () => { + clearCanvas(options._id); + }, + init: () => { + initCanvas(options._id); + }, + stop: () => { + stopAnim(options._id); + }, + start: () => { + startAnim(options._id); + }, + set: (newDrawProps) => { + setDraw(newDrawProps, options._id); + }, + terminate: () => { + stopAnim(options._id); + } + }; + return canvascontrols; + } + } + function drawFrame(props, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts) { + if (props) + Object.assign(canvasopts, props); + if (canvasopts.draw) { + canvasopts.draw(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + } + return void 0; + } + function clearCanvas(_id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts?.clear) { + canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + function initCanvas(_id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts?.init) { + canvasopts.init(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + function updateCanvas(input, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts?.update) { + canvasopts.update(canvasopts, canvasopts.canvas, canvasopts.context, input); + return _id; + } + return void 0; + } + function setProps(props, _id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts) { + Object.assign(canvasopts, props); + if (props.width) + canvasopts.canvas.width = props.width; + if (props.height) + canvasopts.canvas.height = props.height; + return _id; + } + return void 0; + } + function startAnim(_id, draw) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + canvasopts.animating = true; + if (canvasopts && draw) { + if (typeof draw === "string") + draw = parseFunctionFromText3(draw); + if (typeof draw === "function") { + canvasopts.draw = draw; + } + return _id; + } + if (typeof canvasopts?.draw === "function") { + let draw2 = (s, canvas, context) => { + if (s.animating) { + s.draw(s, canvas, context); + requestAnimationFrame(() => { + draw2(s, canvas, context); + }); + } + }; + if (typeof canvasopts.clear === "function") + canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + if (typeof canvasopts.init === "function") + canvasopts.init(canvasopts, canvasopts.canvas, canvasopts.context); + draw2(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + function stopAnim(_id) { + let canvasopts; + if (this?.__node?.graph) { + if (!_id) + canvasopts = this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]; + else + canvasopts = this.__node.graph.CANVASES?.[_id]; + } else { + if (!_id) + canvasopts = globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]; + else + canvasopts = globalThis.CANVASES?.[_id]; + } + if (canvasopts) { + canvasopts.animating = false; + if (typeof canvasopts.clear === "function") + canvasopts.clear(canvasopts, canvasopts.canvas, canvasopts.context); + return _id; + } + return void 0; + } + var workerCanvasRoutes = { + ...proxyElementWorkerRoutes, + Renderer, + transferCanvas, + setupCanvas, + setDraw, + drawFrame, + clearCanvas, + initCanvas, + updateCanvas, + setProps, + startAnim, + stopAnim + }; + function parseFunctionFromText3(method = "") { + let getFunctionBody = (methodString) => { + return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, "$2$3$4"); + }; + let getFunctionHead = (methodString) => { + let startindex = methodString.indexOf("=>") + 1; + if (startindex <= 0) { + startindex = methodString.indexOf("){"); + } + if (startindex <= 0) { + startindex = methodString.indexOf(") {"); + } + return methodString.slice(0, methodString.indexOf("{", startindex) + 1); + }; + let newFuncHead = getFunctionHead(method); + let newFuncBody = getFunctionBody(method); + let newFunc; + if (newFuncHead.includes("function")) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody); + } else { + if (newFuncHead.substring(0, 6) === newFuncBody.substring(0, 6)) { + let varName = newFuncHead.split("(")[1].split(")")[0]; + newFunc = new Function(varName, newFuncBody.substring(newFuncBody.indexOf("{") + 1, newFuncBody.length - 1)); + } else { + try { + newFunc = (0, eval)(newFuncHead + newFuncBody + "}"); + } catch { + } + } + } + return newFunc; + } + + // ../../services/worker/Subprocess.ts + var algorithms = {}; + var loadAlgorithms = (settings) => { + return Object.assign(algorithms, settings); + }; + function createSubprocess(options, inputs) { + let ctx = { + _id: options._id ? options._id : `algorithm${Math.floor(Math.random() * 1e15)}`, + ondata: options.ondata, + run: (data) => { + return ctx.ondata(ctx, data); + } + }; + if (options.structs) + recursivelyAssign3(ctx, JSON.parse(JSON.stringify(options.structs))); + if (inputs) + recursivelyAssign3(ctx, JSON.parse(JSON.stringify(inputs))); + if (options.oncreate) { + ctx.oncreate = options.oncreate; + } + if (ctx.oncreate) { + ctx.oncreate(ctx); + } + return ctx; + } + var recursivelyAssign3 = (target, obj) => { + for (const key in obj) { + if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { + if (typeof target[key] === "object" && !Array.isArray(target[key])) + recursivelyAssign3(target[key], obj[key]); + else + target[key] = recursivelyAssign3({}, obj[key]); + } else + target[key] = obj[key]; + } + return target; + }; + var subprocessRoutes = { + ...unsafeRoutes, + loadAlgorithms, + "initSubprocesses": async function initSubprocesses(subprocesses, service) { + if (!service) + service = this.__node.graph; + if (!service) + return void 0; + for (const p in subprocesses) { + let s = subprocesses[p]; + if (!s.worker && s.url) + s.worker = service.addWorker({ url: s.url }); + if (!s.worker) + continue; + let w = s.worker; + let wpId; + wpId = service.establishMessageChannel(w.worker, s.source?.worker); + if (!s.source) + s.source = service; + if (typeof s.subprocess === "object") { + const p2 = s.subprocess; + if (!p2.name) + continue; + if (typeof p2.oncreate === "function") { + p2.oncreate = p2.oncreate.toString(); + } + if (typeof p2.ondata === "function") { + p2.ondata = p2.ondata.toString(); + } + s.worker.post("addSubprocessTemplate", [ + p2.name, + p2.structs, + p2.oncreate, + p2.ondata, + p2.props + ]); + s.subprocess = p2.name; + } + if (s.init) { + let r = await w.run(s.init, s.initArgs); + s.otherArgs = r; + } + if (s.otherArgs) { + w.run("setValue", ["otherArgsProxy", Array.isArray(s.otherArgs) ? s.otherArgs : [s.otherArgs]]); + } + if (s.pipeTo) { + w.run("setValue", ["routeProxy", s.route]); + w.run("setValue", ["pipeRoute", s.pipeTo.route]); + if (s.url && !s.pipeTo.worker) { + let w2 = service.addWorker({ url: s.url }); + s.pipeTo.portId = service.establishMessageChannel(w.worker, w2.worker); + s.pipeTo.worker = w2; + } + if (s.pipeTo.init) { + s.pipeTo.otherArgs = await s.pipeTo.worker.run(s.pipeTo.init, s.pipeTo.initArgs); + } + w.run("setValue", ["pipePort", s.pipeTo.portId]); + if (s.pipeTo.otherArgs) + w.run("setValue", ["otherPipeArgs", s.pipeTo.otherArgs]); + service.transferFunction(w, function pipeResults(data) { + let inp = data; + if (this.__node.graph.otherArgsProxy) + inp = [data, ...this.__node.graph.otherArgsProxy]; + let r = this.__node.graph.run(this.__node.graph.routeProxy, inp); + if (!s.blocking) + return new Promise((res) => { + if (r instanceof Promise) { + r.then((rr) => { + if (rr !== void 0) { + let args = rr; + if (this.__node.graph.otherPipeArgs) + args = [rr, ...this.__node.graph.otherPipeArgs]; + if (this.workers[this.__node.graph.pipePort]) { + s.blocking = true; + this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute, args).then((result) => { + s.blocking = false; + res(result); + }); + } + } + }); + } else if (r !== void 0) { + let args = r; + if (this.__node.graph.otherPipeArgs) + args = [r, ...this.__node.graph.otherPipeArgs]; + if (this.workers[this.__node.graph.pipePort]) { + s.blocking = true; + this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute, args).then((result) => { + s.blocking = false; + res(result); + }); + } + } + }); + return void 0; + }, s.route + "_pipeResults"); + s.route = s.route + "_pipeResults"; + } else { + w.run("setValue", ["routeProxy", s.route]); + service.transferFunction(w, function routeProxy(data) { + let r; + if (this.__node.graph.otherArgsProxy) + r = this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data, ...this.__node.graph.otherArgsProxy); + else + r = this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data); + if (this.__node.graph.state.triggers[this.__node.graph.routeProxy]) { + if (r instanceof Promise) { + r.then((rr) => { + this.setState({ [this.__node.graph.routeProxy]: rr }); + }); + } else + this.setState({ [this.__node.graph.routeProxy]: r }); + } + return r; + }, s.route + "_routeProxy"); + s.route = s.route + "_routeProxy"; + if (!s.stopped) + w.run("subscribeToWorker", [s.subscribeRoute, wpId, s.route]).then((sub) => { + s.sub = sub; + }); + } + s.stop = async () => { + if (s.source && typeof s.sub === "number") { + s.source.unsubscribe(s.subscribeRoute, s.sub); + return true; + } + return void 0; + }; + s.start = async () => { + if (typeof s.sub !== "number") + return w.run("subscribeToWorker", [s.subscribeRoute, wpId, s.route, s.blocking]).then((sub) => { + s.sub = sub; + }); + }; + s.setArgs = async (args) => { + if (Array.isArray(args)) + await w.run("setValue", ["otherArgsProxy", args]); + else if (typeof args === "object") { + for (const key in args) { + await w.run("setValue", [key, args[key]]); + } + } + return true; + }; + s.terminate = () => { + w.terminate(); + if (s.source?.worker && typeof s.sub === "number") { + s.source.post("unsubscribe", s.sub); + } + if (s.pipeTo?.worker) { + s.pipeTo.worker.terminate(); + } + }; + if (s.callback) + w.subscribe(s.route, (res) => { + if (typeof s.callback === "string") + this.__node.graph.run(s.callback, res); + else + s.callback(res); + }); + } + return subprocesses; + }, + "addSubprocessTemplate": function subprocesstempalte(name, structs, oncreate, ondata, props) { + if (typeof oncreate === "string") + oncreate = parseFunctionFromText(oncreate); + if (typeof ondata === "string") + ondata = parseFunctionFromText(ondata); + if (typeof ondata === "function") { + algorithms[name] = { + ondata, + oncreate: typeof oncreate === "function" ? oncreate : null, + structs + }; + if (typeof props === "object") + Object.assign(algorithms[name], props); + return true; + } + }, + "updateSubprocess": function updatesubprocess(structs, _id) { + if (!this.__node.graph.ALGORITHMS) + this.__node.graph.ALGORITHMS = {}; + if (!_id) + _id = Object.keys(this.__node.graph.ALGORITHMS)[0]; + if (!_id) + return; + Object.assign(this.__node.graph.ALGORITHMS[_id], structs); + }, + "createSubprocess": function creatsubprocess(options, inputs) { + if (!this.__node.graph.ALGORITHMS) + this.__node.graph.ALGORITHMS = {}; + if (typeof options === "string") { + options = algorithms[options]; + } + if (typeof options === "object") { + if (typeof options.ondata === "string") + options.ondata = parseFunctionFromText(options.ondata); + let ctx; + if (typeof options?.ondata === "function") + ctx = createSubprocess(options, inputs); + if (ctx) + this.__node.graph.ALGORITHMS[ctx._id] = ctx; + console.log(ctx, options); + if (ctx) + return ctx._id; + } + return false; + }, + "runSubprocess": function runsubprocess(data, _id) { + if (!this.__node.graph.ALGORITHMS) + this.__node.graph.ALGORITHMS = {}; + if (!_id) + _id = Object.keys(this.__node.graph.ALGORITHMS)[0]; + if (!_id) + return; + let res = this.__node.graph.ALGORITHMS[_id].run(data); + if (res !== void 0) { + if (Array.isArray(res)) { + let pass = []; + res.forEach((r) => { + if (r !== void 0) { + pass.push(r); + this.__node.graph.setState({ [_id]: r }); + } + }); + if (pass.length > 0) { + return pass; + } + } else { + this.__node.graph.setState({ [_id]: res }); + return res; + } + } + } + }; + + // ../../services/router/Router.ts + var Router = class extends Service { + constructor(options) { + super(options); + this.name = "router"; + this.connections = {}; + this.sources = {}; + this.services = {}; + this.serviceConnections = {}; + this.users = {}; + this.addUser = async (info2, connections, config, receiving) => { + if (!info2._id) { + info2._id = `user${Math.floor(Math.random() * 1e15)}`; + } + let user = Object.assign({}, info2); + if (connections) { + for (const key in connections) { + if (typeof connections[key] === "object") { + if (!connections[key].connection._id) { + await new Promise((res, rej) => { + let start = performance.now(); + let checker = () => { + if (!connections[key].connection._id) { + if (performance.now() - start > 3e3) { + delete connections[key]; + rej(false); + } else { + setTimeout(() => { + checker(); + }, 100); + } + } else { + res(true); + } + }; + checker(); + }).catch((er) => { + console.error("Connections timed out:", er); + }); + } + } + } + for (const key in connections) { + connections[key] = this.addConnection(connections[key], user._id); + } + } + if (config) { + for (const c in config) { + this.openConnection(config[c].service, config[c], user._id, config[c].args); + } + } + let send = (message, ...a) => { + let connection = this.getConnection(user._id, "send"); + if (connection?.send) + return connection.send(message, ...a); + }; + let request = (message, method, ...a) => { + let connection = this.getConnection(user._id, "request"); + if (connection?.request) + return connection.request(message, method, ...a); + }; + let post = (route, args, method, ...a) => { + let connection = this.getConnection(user._id, "post"); + if (connection?.post) + return connection.post(route, args, method, ...a); + }; + let run = (route, args, method, ...a) => { + let connection = this.getConnection(user._id, "run"); + if (connection?.run) + return connection.run(route, args, method, ...a); + }; + let subscribe = (route, callback, ...a) => { + let connection = this.getConnection(user._id, "subscribe"); + if (connection?.subscribe) + return connection.subscribe(route, callback, ...a); + }; + let unsubscribe = (route, sub, ...a) => { + let connection = this.getConnection(user._id, "unsubscribe"); + if (connection?.unsubscribe) + return connection.unsubscribe(route, sub, ...a); + }; + let terminate = () => { + return this.removeUser(user); + }; + user.send = send; + user.request = request; + user.post = post; + user.run = run; + user.subscribe = subscribe; + user.unsubscribe = unsubscribe; + user.terminate = terminate; + this.users[user._id] = user; + if (connections && !receiving) { + let connectionIds = {}; + let pass = false; + Object.keys(connections).map((k, i) => { + if (connections[k]?._id) { + connectionIds[`${i}`] = connections[k]?._id; + pass = true; + } + }); + if (pass) { + user.send({ + route: "addUser", + args: [ + { _id: user._id }, + connectionIds, + void 0, + true + ] + }); + } + } + return user; + }; + this.getConnection = (sourceId, hasMethod) => { + if (this.sources[sourceId]) { + if (this.order) { + for (let i = 0; i < this.order.length; i++) { + let k = this.order[i]; + for (const key in this.sources[sourceId]) { + if (this.sources[sourceId][key].service) { + if (typeof this.sources[sourceId][key].service === "object") { + if (this.sources[sourceId][key].service.__node.tag === k) { + if (this.sources[sourceId][key].connectionType && this.sources[sourceId][key].service?.name) { + if (!this.serviceConnections[this.sources[sourceId][key].service.name]) { + this.removeConnection(this.sources[sourceId][key]); + continue; + } + } + return this.sources[sourceId][key]; + } + } else if (this.sources[sourceId][key].service === k) { + if (this.sources[sourceId][key].connectionType && this.sources[sourceId][key].service?.name) { + if (!this.serviceConnections[this.sources[sourceId][key].service.name]) + this.removeConnection(this.sources[sourceId][key]); + continue; + } + return this.sources[sourceId][key]; + } + } + } + } + } else { + for (const k in this.sources[sourceId]) { + if (this.sources[sourceId][k].connectionType && this.sources[sourceId][k].service?.name) { + if (!this.serviceConnections[this.sources[sourceId][k].service.name]) { + this.removeConnection(this.sources[sourceId][k]); + continue; + } + } + if (hasMethod && this.sources[sourceId][k][hasMethod]) { + return this.sources[sourceId][k]; + } else { + return this.sources[sourceId][k]; + } + } + } + } else if (this.order) { + for (let i = 0; i < this.order.length; i++) { + let k = this.order[i]; + if (this.sources[k]?.[sourceId]) { + if (this.sources[k][sourceId].connectionType && this.sources[k][sourceId].service?.name) { + if (!this.serviceConnections[this.sources[k][sourceId].service.service.name]) { + this.removeConnection(this.sources[k][sourceId].service); + continue; + } + } + if (hasMethod && this.sources[k][sourceId]?.[hasMethod]) { + return this.sources[k][sourceId]; + } else { + return this.sources[k][sourceId]; + } + } + } + } + if (typeof sourceId === "string" && this.connections[sourceId] && this.connections[sourceId].send) { + return this.connections[sourceId]; + } + }; + this.getConnections = (sourceId, hasMethod, props) => { + if (this.sources[sourceId]) { + if (!props && !hasMethod) + return this.sources[sourceId]; + let found = {}; + for (const key in this.sources[sourceId]) { + if (typeof this.sources[sourceId][key] === "object") { + if (!this.sources[sourceId][key]._id) { + for (const k in this.sources[sourceId][key]) { + if (typeof this.sources[sourceId][key][k] === "object") { + let pass = true; + if (hasMethod && !this.sources[sourceId][key][k][hasMethod]) + pass = false; + for (const p in props) { + if (typeof this.sources[sourceId][key][k][p] === "object" && typeof props[p] === "object") { + for (const pp in props[p]) { + if (props[p][pp] !== this.sources[sourceId][key][k][p][pp]) { + pass = false; + break; + } + } + } else if (this.sources[sourceId][key][k][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; + } + } + if (pass) { + found[this.sources[sourceId][key][k]._id] = this.sources[sourceId][key][k]; + } + } + } + } else { + let pass = true; + if (hasMethod && !this.sources[sourceId][key][hasMethod]) + pass = false; + for (const p in props) { + if (typeof this.sources[sourceId][key][p] === "object" && typeof props[p] === "object") { + for (const pp in props[p]) { + if (props[p][pp] !== this.sources[sourceId][key][p][pp]) { + pass = false; + break; + } + } + } else if (this.sources[sourceId][key][p] !== props[p]) { + pass = false; + } else { + pass = false; + break; + } + } + if (pass) { + if (this.getConnection(this.sources[sourceId][key], hasMethod)) + found[this.sources[sourceId][key]._id] = this.sources[sourceId][key]; + } + } + } + } + } + }; + this.addConnection = (options, source) => { + let settings = {}; + if (typeof options === "string") { + if (this.connections[options]) { + options = this.connections[options]; + } else { + for (const j in this.serviceConnections) { + for (const k in this.serviceConnections[j]) { + if (this.serviceConnections[j][k][options]) { + options = { connection: this.serviceConnections[j][k][options] }; + options.service = j; + settings.connectionType = j; + settings.connectionsKey = k; + break; + } + } + } + } + if (typeof options === "string" && this.__node.nodes.get(options)) + options = { connection: this.__node.nodes.get(options) }; + } + if (!options || typeof options === "string") + return void 0; + if (source) + settings.source = source; + if (options.connection instanceof GraphNode) { + settings.connection = options.connection; + let node = settings.connection; + settings.send = async (message) => { + if (message.method) { + if (Array.isArray(message.args)) { + return node[message.method]?.(...message.args); + } else + return node[message.method]?.(message.args); + } else { + if (!node.__operator) + return; + if (Array.isArray(message.args)) { + return node.__operator(...message.args); + } else + return node.__operator(message.args); + } + }; + settings.request = async (message, method) => { + if (method) { + if (Array.isArray(message.args)) { + return node[method]?.(...message.args); + } else + return node[method]?.(message.args); + } else { + if (!node.__operator) + return; + if (Array.isArray(message.args)) { + return node.__operator(...message.args); + } else + return node.__operator(message.args); + } + }; + settings.post = async (route, args, method) => { + if (route && node.__node.graph.get(route)) { + let n = node.__node.graph.get(route); + if (method) { + if (Array.isArray(args)) { + return n[method]?.(...args); + } else + return n[method]?.(args); + } else { + if (Array.isArray(args)) { + return n.__operator(...args); + } else + return n.__operator(args); + } + } else { + if (method) { + if (Array.isArray(args)) { + return node[method]?.(...args); + } else + return node[method]?.(args); + } else { + if (Array.isArray(args)) { + return node.__operator(...args); + } else + return node.__operator(args); + } + } + }; + settings.run = settings.post; + settings.subscribe = async (callback) => { + return node.__subscribe(callback); + }; + settings.unsubscribe = async (sub) => { + return node.__unsubscribe(sub); + }; + settings.terminate = () => { + node.__node.graph.remove(node); + return true; + }; + settings.onclose = options.onclose; + if (settings.onclose) { + node.__addOndisconnected((n) => { + if (settings.onclose) + settings.onclose(settings, n); + }); + } + } else if (options.connection instanceof Graph) { + if (options.connection.__node.nodes.get("open")) + settings.service = options.connection; + let graph = settings.connection; + settings.send = async (message) => { + if (Array.isArray(message.args)) + graph.run(message.route, ...message.args); + else + graph.run(message.route, message.args); + }; + settings.request = async (message, method) => { + if (!message.route) + return void 0; + if (method) { + if (Array.isArray(message.args)) { + return graph.__node.nodes.get(message.route)[method]?.(...message.args); + } else + return graph.__node.nodes.get(message.route)[method]?.(message.args); + } else { + if (Array.isArray(message.args)) { + return graph.run(message.route, ...message.args); + } else + return graph.run(message.route, message.args); + } + }; + settings.post = async (route, args, method) => { + if (route && graph.get(route)) { + let n = graph.get(route); + if (method) { + if (Array.isArray(args)) { + return n[method]?.(...args); + } else + return n[method]?.(args); + } else { + if (Array.isArray(args)) { + return n.run(...args); + } else + return n.run(args); + } + } + }; + settings.run = settings.post; + settings.subscribe = async (route, callback) => { + return graph.subscribe(route, callback); + }; + settings.unsubscribe = async (route, sub) => { + return graph.unsubscribe(route, sub); + }; + settings.terminate = (n) => { + graph.remove(n); + return true; + }; + } else if (!(options._id && this.connections[options._id])) { + let c = options.connection; + if (typeof c === "string") { + if (this.connections[c]) + c = this.connections[c]; + else if (options.service) { + if (typeof options.service === "string") { + options.service = this.services[options.service]; + } + if (typeof options.service === "object") { + if (options.service.connections) { + for (const key in options.service.connections) { + if (options.service.connections[key][c]) { + c = options.service.connections[key][c]; + settings.connectionType = key; + settings.connectionsKey = c; + break; + } + } + } + } + } else { + for (const j in this.serviceConnections) { + for (const k in this.serviceConnections[j]) { + if (this.serviceConnections[j][k][c]) { + c = this.serviceConnections[j][k][c]; + options.service = j; + settings.connectionType = j; + settings.connectionsKey = k; + break; + } + } + } + } + } + if (typeof c !== "object") + return void 0; + settings._id = c._id; + settings.send = c.send; + settings.request = c.request; + settings.run = c.run; + settings.post = c.post; + settings.subscribe = c.subscribe; + settings.unsubscribe = c.unsubscribe; + settings.terminate = c.terminate; + settings.onclose = options.onclose; + if (settings.onclose) { + if (!(c.onclose && settings.onclose.toString() === c.onclose.toString())) { + let oldonclose = c.onclose; + c.onclose = (...args) => { + if (settings.onclose) + settings.onclose(settings, ...args); + if (this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { + this.removeUser(settings.source, false); + } + if (oldonclose) + oldonclose(...args); + }; + } + } else { + let oldonclose = c.onclose; + c.onclose = (...args) => { + this.removeConnection(settings); + if (this.users[settings.source] && Object.keys(this.sources[settings.source]).length === 0) { + this.removeUser(settings.source, false); + } + if (oldonclose) + oldonclose(...args); + }; + } + if (options.service) { + if (typeof options.service === "string") + options.service = this.services[options.service]; + settings.service = options.service; + } else if (c.graph) + settings.service = c.graph; + } + if (!settings.source && options.source) { + settings.source = options.source; + } else if (!settings.source && options.service) { + settings.source = typeof options.service === "object" ? options.service?.name : void 0; + } else if (!settings.source && (settings.connection instanceof GraphNode || settings.connection instanceof Graph)) { + settings.source = "local"; + if (!this.order.indexOf("local")) + this.order.unshift("local"); + } + if (!settings._id) + settings._id = `connection${Math.floor(Math.random() * 1e15)}`; + if (settings.source) { + if (!this.sources[settings.source]) + this.sources[settings.source] = {}; + this.sources[settings.source][settings._id] = settings; + } + if (!this.connections[settings._id]) + this.connections[settings._id] = settings; + return settings; + }; + this.removeConnection = (connection, terminate = false) => { + if (typeof connection === "object" && connection._id) + connection = connection._id; + if (typeof connection === "string") { + if (this.connections[connection]) { + if (terminate && this.connections[connection]) + this.connections[connection].terminate(); + delete this.connections[connection]; + for (const key in this.sources) { + if (this.sources[key][connection]) + delete this.sources[key][connection]; + else { + for (const k in this.sources[key]) { + if (this.sources[key][k]?.[connection]) { + delete this.sources[key][connection]; + } + } + } + } + return true; + } else if (this.sources[connection]) { + for (const key in this.sources[connection]) { + this.removeConnection(this.sources[connection][key], terminate); + } + return true; + } + } + }; + this.routeService = (service, connections, source, order) => { + this.services[service.name] = service; + if (service.__node?.nodes) + this.__node.nodes.forEach((n, k) => { + if (!service.__node?.nodes.get(k)) { + service.__node?.nodes.set(k, n); + } else + service.__node?.nodes.set(this.name + "." + k, n); + }); + if (service.users) + service.users = this.users; + if (connections) { + if (typeof connections === "string") + this.addServiceConnections(service, connections, source); + else { + for (const c in connections) { + this.addServiceConnections(service, c, source); + } + } + } + if (order) + this.order = order; + else { + if (!this.order) + this.order = []; + this.order.push(service.name); + } + }; + this.addServiceConnections = (service, connectionsKey, source) => { + if (typeof service === "string") { + service = this.services[service]; + } + if (connectionsKey && service[connectionsKey]) { + let newConnections = {}; + if (!this.serviceConnections[service.name]) + this.serviceConnections[service.name] = {}; + this.serviceConnections[service.name][connectionsKey] = service[connectionsKey]; + for (const key in service[connectionsKey]) { + if (!this.connections[key]) { + const res = this.addConnection({ connection: service[connectionsKey][key], service }, source); + if (res) { + newConnections[key] = res; + newConnections[key].connectionType = connectionsKey; + } else { + console.log("Could not make connection", service[connectionsKey][key], service, source); + } + } + } + return newConnections; + } + }; + this.openConnection = async (service, options, source, ...args) => { + if (typeof service === "string") { + service = this.services[service]; + } + if (service?.__node.nodes) { + let connection = service.run("open", options, ...args); + if (connection instanceof Promise) { + return connection.then(async (info2) => { + if (!info2._id) { + await new Promise((res, rej) => { + let start = performance.now(); + let checker = () => { + if (!info2._id) { + if (performance.now() - start > 3e3) { + rej(false); + } else { + setTimeout(() => { + checker(); + }, 100); + } + } else { + res(true); + } + }; + checker(); + }).catch((er) => { + console.error("Connections timed out:", er); + }); + } + if (info2._id) + this.addConnection({ connection: info2, service }, source); + }); + } else if (connection) { + if (!connection._id) { + await new Promise((res, rej) => { + let start = performance.now(); + let checker = () => { + if (!connection._id) { + if (performance.now() - start > 3e3) { + rej(false); + } else { + setTimeout(() => { + checker(); + }, 100); + } + } else { + res(true); + } + }; + checker(); + }).catch((er) => { + console.error("Connections timed out:", er); + }); + } + if (connection._id) + return this.addConnection({ connection, service }, source); + } + } + }; + this.terminate = (connection) => { + if (typeof connection === "string") + connection = this.connections[connection]; + return connection.terminate(); + }; + this.subscribeThroughConnection = (route, relay, endpoint, callback, ...args) => { + if (typeof relay === "string") { + relay = this.getConnection(relay, "run"); + } + if (typeof relay === "object") + return new Promise((res, rej) => { + relay.run("routeConnections", [route, endpoint, relay._id, ...args]).then((sub) => { + this.__node.state.subscribeTrigger(endpoint, (res2) => { + if (res2?.callbackId === route) { + if (!callback) + this.setState({ [endpoint]: res2.args }); + else if (typeof callback === "string") { + this.setState({ [callback]: res2.args }); + } else + callback(res2.args); + } + }); + res(sub); + }).catch(rej); + }); + }; + this.routeConnections = (route, transmitter, receiver, ...args) => { + let rxsrc; + if (typeof receiver === "string") { + if (this.sources[receiver]) { + rxsrc = receiver; + } + receiver = this.getConnection(receiver, "send"); + } + if (typeof transmitter === "string") { + transmitter = this.getConnection(transmitter, "subscribe"); + } + if (transmitter?.subscribe && receiver?.send) { + let res = new Promise((res2, rej) => { + transmitter.subscribe(route, transmitter._id, (res3) => { + if (!this.connections[receiver._id] && rxsrc) { + if (this.sources[rxsrc]) { + rxsrc = receiver; + Object.keys(this.sources[rxsrc]).forEach((k) => { + if (this.sources[receiver][k].send) { + receiver = this.sources[receiver][k]; + } + }); + } + } + if (this.connections[receiver._id]) + receiver.send({ callbackId: route, args: res3 }); + }, ...args).then((sub) => { + res2(sub); + }); + }); + return res; + } + }; + this.setUserData = (user, data) => { + if (user) { + if (typeof user === "string") { + user = this.users[user]; + if (!user) + return false; + } + } + if (data) { + if (typeof data === "string") { + data = JSON.parse(data); + } + } + if (typeof data === "object") { + this.recursivelyAssign(user, data); + return true; + } + }; + this.setTree(this); + if (options) { + if (options.order) + this.order = options.order; + if (options.graph) { + for (const key in options.graph) { + let opt = options.graph[key]; + if (typeof opt === "function") + opt = new opt(); + if (opt?.__node?.nodes) { + opt.name = key; + opt.__node.tag = key; + this.addServices({ [opt.name]: opt }); + this.routeService(opt, opt.connections); + } else { + if (typeof opt?.service === "function") + opt.service = new opt.service(); + if (opt?.service?.__node?.nodes) { + opt.service.name = key; + opt.service.__node.tag = key; + this.addServices({ [opt.service.name]: opt.service }); + this.routeService(opt.service); + } + if (typeof opt?.service === "object") { + if (opt.connections) { + if (Array.isArray(opt.connections)) { + opt.connections.forEach((k) => { + this.addServiceConnections(opt[key].service, k); + }); + } else + this.addServiceConnections(opt.service, opt.connections); + } + if (opt.config) { + for (const c in opt.config) { + this.openConnection(opt.service, opt.config[c], opt.config[c].source, opt.config[c].args); + } + } + } + } + } + } + } + } + removeUser(profile, terminate) { + if (terminate) + this.removeConnection(profile, terminate); + if (typeof profile === "string") + profile = this.users[profile]; + if (typeof profile === "object" && profile._id) { + delete this.users[profile._id]; + if (profile.onclose) + profile.onclose(profile); + } + return true; + } + }; + + // worker.ts + var url = URL.createObjectURL(new Blob([String('(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error(\'Dynamic require of "\'+x2+\'" is not supported\')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __accessCheck=(obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)};var __privateGet=(obj,member,getter)=>{__accessCheck(obj,member,"read from private field");return getter?getter.call(obj):member.get(obj)};var __privateAdd=(obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)};var __privateSet=(obj,member,value,setter)=>{__accessCheck(obj,member,"write to private field");setter?setter.call(obj,value):member.set(obj,value);return value};var require_sjcl=__commonJS({"../../services/e2ee/sjcl.js"(exports,module){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x2=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x2[e>>>24]<<24^x2[f>>16&255]<<16^x2[g>>8&255]<<8^x2[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn\'t "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn\'t base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn\'t match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn\'t match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can\'t attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto[\'randomBytes\']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto[\'getRandomValues\']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{try{return _Buffer}catch(_){try{return Buffer}catch(_2){return null}}})();var isBuffer=function(obj){return!!(obj!=null&&obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj))};var hexTable=[];for(i=0;i<256;i++){hexTable[i]=(i<=15?"0":"")+i.toString(16)}var i;var checkForHexRegExp=new RegExp("^[0-9a-fA-F]{24}$");var decodeLookup=[];i=0;while(i<10)decodeLookup[48+i]=i++;while(i<16)decodeLookup[65-10+i]=decodeLookup[97-10+i]=i++;function ObjectID2(id2){if(!(this instanceof ObjectID2))return new ObjectID2(id2);if(id2&&(id2 instanceof ObjectID2||id2._bsontype==="ObjectID"))return id2;this._bsontype="ObjectID";if(id2==null||typeof id2==="number"){this.id=this.generate(id2);return}var valid=ObjectID2.isValid(id2);if(!valid&&id2!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(valid&&typeof id2==="string"&&id2.length===24){return ObjectID2.createFromHexString(id2)}else if(id2!=null&&id2.length===12){this.id=id2}else if(id2!=null&&typeof id2.toHexString==="function"){return id2}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}}module.exports=ObjectID2;ObjectID2.default=ObjectID2;ObjectID2.createFromTime=function(time){time=parseInt(time,10)%4294967295;return new ObjectID2(hex(8,time)+"0000000000000000")};ObjectID2.createFromHexString=function(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}var data="";var i2=0;while(i2<24){data+=String.fromCharCode(decodeLookup[hexString.charCodeAt(i2++)]<<4|decodeLookup[hexString.charCodeAt(i2++)])}return new ObjectID2(data)};ObjectID2.isValid=function(id2){if(id2==null)return false;if(typeof id2==="number"){return true}if(typeof id2==="string"){return id2.length===12||id2.length===24&&checkForHexRegExp.test(id2)}if(id2 instanceof ObjectID2){return true}if(isBuffer(id2)){return ObjectID2.isValid(id2.toString("hex"))}if(typeof id2.toHexString==="function"){if(BufferCtr&&(id2.id instanceof BufferCtr||typeof id2.id==="string")){return id2.id.length===12||id2.id.length===24&&checkForHexRegExp.test(id2.id)}}return false};ObjectID2.prototype={constructor:ObjectID2,toHexString:function(){if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id.length===24){return this.id}if(isBuffer(this.id)){return this.id.toString("hex")}var hexString="";for(var i2=0;i2>24&255,time>>16&255,time>>8&255,time&255,MACHINE_ID>>16&255,MACHINE_ID>>8&255,MACHINE_ID&255,pid>>8&255,pid&255,inc>>16&255,inc>>8&255,inc&255)}};function next(){return index=(index+1)%16777215}function hex(length,n){n=n.toString(16);return n.length===length?n:"00000000".substring(n.length,length)+n}var inspect=Symbol&&Symbol.for&&Symbol.for("nodejs.util.inspect.custom")||"inspect";ObjectID2.prototype[inspect]=function(){return"ObjectID("+this+")"};ObjectID2.prototype.toJSON=ObjectID2.prototype.toHexString;ObjectID2.prototype.toString=ObjectID2.prototype.toHexString}});var props_loader_default=node=>{if(node.__properties.__props)node.____apply(node.__properties.__props,true)};var __defProp2=Object.defineProperty;var __export2=(target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:true})};var moduleStringTag="[object Module]";var esm=object=>{const res=object&&(!!Object.keys(object).reduce((a,b)=>{const desc=Object.getOwnPropertyDescriptor(object,b);const isModule=desc&&desc.get&&!desc.set?1:0;return a+isModule},0)||Object.prototype.toString.call(object)===moduleStringTag);return!!res};var isSame=(a,b)=>{if(a&&typeof a==="object"&&b&&typeof b==="object"){const jA=JSON.stringify(a);const jB=JSON.stringify(b);return jA===jB}else return a===b};var iterateSymbols=(obj,callback)=>{return Promise.all(Object.getOwnPropertySymbols(obj).map(sym=>callback(sym,obj[sym])))};var getPath=(type,info2)=>{const pathType=info2.path[type];if(!pathType)throw new Error("Invalid Path Type");const filtered=pathType.filter(v=>typeof v==="string");return filtered.join(info2.keySeparator)};var getPathInfo=(path,options)=>{let splitPath=path;if(typeof path==="string")splitPath=path.split(options.keySeparator);else if(typeof path==="symbol")splitPath=[path];return{id:splitPath[0],path:splitPath.slice(1)}};var runCallback=(callback,path,info2,output,setGlobal=true)=>{if(callback instanceof Function){if(output&&typeof output==="object"&&typeof output.then==="function")output.then(value=>callback(path,info2,value));else callback(path,info2,output)}if(setGlobal&&globalThis.ESMonitorState){const callback2=globalThis.ESMonitorState.callback;globalThis.ESMonitorState.state[path]={output,value:info2};runCallback(callback2,path,info2,output,false)}};var defaultSamplingRate=60;var _pollingId,_sps,_a;var Poller=(_a=class{constructor(listeners2,sps){__privateAdd(this,_pollingId,void 0);__privateAdd(this,_sps,void 0);this.listeners={};this.setOptions=(opts={})=>{for(let key in opts)this[key]=opts[key]};this.add=info2=>{const sub=info2.sub;this.listeners[sub]=info2;this.start();return true};this.get=sub=>this.listeners[sub];this.remove=sub=>{delete this.listeners[sub];if(!Object.keys(this.listeners).length)this.stop()};this.poll=listeners22=>{iterateSymbols(listeners22,(sym,o)=>{let{callback,current,history}=o;if(!o.path.resolved)o.path.resolved=getPath("output",o);if(!isSame(current,history)){runCallback(callback,o.path.resolved,{},current);if(typeof current==="object"){if(Array.isArray(current))history=[...current];else history={...current}}else listeners22[sym].history=current}})};this.start=(listeners22=this.listeners)=>{if(!this.sps)this.sps=defaultSamplingRate;else if(!__privateGet(this,_pollingId)){console.warn("[escode]: Starting Polling!");__privateSet(this,_pollingId,setInterval(()=>this.poll(listeners22),1e3/this.sps))}};this.stop=()=>{if(__privateGet(this,_pollingId)){console.warn("[escode]: Stopped Polling!");clearInterval(__privateGet(this,_pollingId));__privateSet(this,_pollingId,void 0)}};if(listeners2)this.listeners=listeners2;if(sps)this.sps=sps}get sps(){return __privateGet(this,_sps)}set sps(sps){__privateSet(this,_sps,sps);const listeners2=this.listeners;const nListeners=Object.keys(listeners2).length;if(nListeners){this.stop();this.start()}}},_pollingId=new WeakMap,_sps=new WeakMap,_a);var listeners_exports={};__export2(listeners_exports,{functionExecution:()=>functionExecution,functions:()=>functions2,getProxyFunction:()=>getProxyFunction,info:()=>info,register:()=>register,set:()=>set,setterExecution:()=>setterExecution,setters:()=>setters});globalThis.ESMonitorState={state:{},callback:void 0,info:{}};var global_default=globalThis.ESMonitorState;var performance2=async(callback,args)=>{const tic=globalThis.performance.now();const output=await callback(...args);const toc=globalThis.performance.now();return{output,value:toc-tic}};var infoFunctions={performance:performance2};var get=(func,args,info2)=>{let result={value:{},output:void 0};const infoToGet={...global_default.info,...info2};for(let key in infoToGet){if(infoToGet[key]&&infoFunctions[key]){const ogFunc=func;func=async(...args2)=>{const o=await infoFunctions[key](ogFunc,args2);result.value[key]=o.value;return o.output}}}result.output=func(...args);return result};var isProxy=Symbol("isProxy");var fromInspectable=Symbol("fromInspectable");var fromInspectableHandler=Symbol("fromInspectableHandler");var keySeparator=".";var hasKey=(key,obj)=>key in obj;var getShortcut=(path,shortcuts,keySeparator2)=>{const sc=shortcuts[path[0]];if(sc){const value=sc[path.slice(1).join(keySeparator2)];if(value)return value}};var getFromPath=(baseObject,path,opts={})=>{const fallbackKeys=opts.fallbacks??[];const keySeparator2=opts.keySeparator??keySeparator;if(opts.shortcuts){const shortcut=getShortcut(path,opts.shortcuts,keySeparator2);if(shortcut){if(opts.output==="info")return{value:shortcut,exists:true,shortcut:true};else return shortcut}}if(typeof path==="string")path=path.split(keySeparator2).flat();else if(typeof path=="symbol")path=[path];let exists;path=[...path];path=path.map(o=>typeof o==="string"?o.split(keySeparator2):o).flat();let ref=baseObject;for(let i=0;i{const create=opts?.create??false;const keySeparator2=opts?.keySeparator??keySeparator;if(typeof path==="string")path=path.split(keySeparator2);else if(typeof path=="symbol")path=[path];path=[...path];const copy=[...path];const last=copy.pop();if(ref.__children)ref=ref.__children;for(let i=0;ifunctions,objects:()=>objects});function define2(key,registerAsNewKey){const inspectable=this;const target=this.target;if(!this.parent){let value=target[key];if(typeof value==="function"){target[key]=async(...args)=>await this.proxy[key]({[fromInspectable]:true,value},...args)}else{try{Object.defineProperty(target,key,{get:()=>value,set:function(val){value=val;inspectable.proxy[key]={[isProxy]:this[isProxy],[fromInspectable]:true,value:val}},enumerable:true,configurable:true})}catch(e){console.error(`Could not reassign ${key} to a top-level setter...`)}}}if(registerAsNewKey)this.newKeys.add(key);this.create(key,target,void 0,true)}var define_default=define2;var functions=function(){const inspectable=this;return{apply:async function(target,thisArg,argumentsList){try{let foo=target;const isFromInspectable=argumentsList[0]?.[fromInspectable];if(isFromInspectable){foo=argumentsList[0].value;argumentsList=argumentsList.slice(1)}let listeners2=inspectable.listeners.functions;const pathStr=inspectable.path.join(inspectable.options.keySeparator);const toActivate=listeners2?listeners2[pathStr]:void 0;let output,executionInfo={};if(toActivate){executionInfo=functionExecution(thisArg,toActivate,foo,argumentsList);output=executionInfo.output}else{output=foo.apply(thisArg,argumentsList);executionInfo=inspectable?.state?.[pathStr]?.value??{}}const callback=inspectable.options.callback;runCallback(callback,pathStr,executionInfo,output);return output}catch(e){console.warn(`Function failed:`,e,inspectable.path)}}}};var objects=function(){const inspectable=this;return{get(target,prop,receiver){if(prop===isProxy)return true;return Reflect.get(target,prop,receiver)},set(target,prop,newVal,receiver){if(prop===isProxy)return true;const pathStr=[...inspectable.path,prop].join(inspectable.options.keySeparator);const isFromProxy=newVal?.[isProxy];const isFromInspectable=newVal?.[fromInspectable];if(isFromInspectable)newVal=newVal.value;const listeners2=inspectable.listeners.setters;const desc=Object.getOwnPropertyDescriptor(target,prop);const createListener=desc&&!desc.get&&!desc.set;if(createListener){if(typeof inspectable.options.globalCallback==="function"){const id2=inspectable.path[0];define_default.call(inspectable,prop,true);set("setters",pathStr,newVal,inspectable.options.globalCallback,{[id2]:inspectable.root},inspectable.listeners,inspectable.options)}}if(newVal){const newProxy=inspectable.create(prop,target,newVal);if(newProxy)newVal=newProxy}const toActivate=!isFromProxy;if(listeners2&&toActivate&&!inspectable.newKeys.has(prop)){const toActivate2=listeners2[pathStr];if(toActivate2)setterExecution(toActivate2,newVal)}const callback=inspectable.options.callback;const info2=inspectable?.state?.[pathStr]?.value??{};runCallback(callback,pathStr,info2,newVal);if(isFromInspectable||!toActivate)return true;else return Reflect.set(target,prop,newVal,receiver)}}};var canCreate=(parent,key,val)=>{try{if(val===void 0)val=parent[key]}catch(e){return e}const alreadyIs=parent[key]&&parent[key][isProxy];if(alreadyIs)return false;const type=typeof val;const isObject=type==="object";const isFunction=type=="function";const notObjOrFunc=!val||!(isObject||isFunction);if(notObjOrFunc)return false;if(val instanceof Element)return false;if(val instanceof EventTarget)return false;const isESM=isObject&&esm(val);if(isFunction)return true;else{const desc=Object.getOwnPropertyDescriptor(parent,key);if(desc&&(desc.value&&desc.writable||desc.set)){if(!isESM)return true}else if(!parent.hasOwnProperty(key))return true}return false};var Inspectable=class{constructor(target={},opts={},name,parent){this.path=[];this.listeners={};this.newKeys=new Set;this.state={};this.set=(path,info2,update)=>{this.state[path]={output:update,value:info2};setFromPath(path,update,this.proxy,{create:true})};this.check=canCreate;this.create=(key,parent2,val,set2=false)=>{const create=this.check(parent2,key,val);if(val===void 0)val=parent2[key];if(create&&!(create instanceof Error)){parent2[key]=new Inspectable(val,this.options,key,this);return parent2[key]}if(set2){try{this.proxy[key]=val??parent2[key]}catch(e){const isESM=esm(parent2);const path=[...this.path,key];console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM?" because the parent is an ESM.":""}`,isESM?"":e)}}return};if(!opts.pathFormat)opts.pathFormat="relative";if(!opts.keySeparator)opts.keySeparator=keySeparator;if(target.__proxy)this.proxy=target.__proxy;else if(target[isProxy])this.proxy=target;else{this.target=target;this.options=opts;this.parent=parent;if(this.parent){this.root=this.parent.root;this.path=[...this.parent.path];this.state=this.parent.state??{}}else this.root=target;if(name)this.path.push(name);if(this.options.listeners)this.listeners=this.options.listeners;if(this.options.path){if(this.options.path instanceof Function)this.path=this.options.path(this.path);else if(Array.isArray(this.options.path))this.path=this.options.path;else console.log("Invalid path",this.options.path)}if(this.path)this.path=this.path.filter(str2=>typeof str2==="string");if(!this.options.keySeparator)this.options.keySeparator=keySeparator;let type=this.options.type;if(type!="object")type=typeof target==="function"?"function":"object";const handler2=handlers_exports[`${type}s`].call(this);this.proxy=new Proxy(target,handler2);Object.defineProperty(target,"__proxy",{value:this.proxy,enumerable:false});Object.defineProperty(target,"__esInspectable",{value:this,enumerable:false});for(let key in target)define_default.call(this,key)}return this.proxy}};var setFromOptions=(path,value,baseOptions,opts)=>{const ref=opts.reference;const id2=Array.isArray(path)?path[0]:typeof path==="string"?path.split(baseOptions.keySeparator)[0]:path;let isDynamic=opts.hasOwnProperty("static")?!opts.static:false;if(isDynamic&&!globalThis.Proxy){isDynamic=false;console.warn("Falling back to using function interception and setters...")}if(isDynamic){value=new Inspectable(value,{pathFormat:baseOptions.pathFormat,keySeparator:baseOptions.keySeparator,listeners:opts.listeners,path:path2=>path2.filter(str2=>!baseOptions.fallbacks||!baseOptions.fallbacks.includes(str2))},id2)}let options={keySeparator:baseOptions.keySeparator,...opts};setFromPath(path,value,ref,options);return value};var info=(id2,callback,path,originalValue,base,listeners2,options,refShortcut={})=>{if(typeof path==="string")path=path.split(options.keySeparator);const relativePath=path.join(options.keySeparator);const refs=base;const shortcutRef=refShortcut.ref;const shortcutPath=refShortcut.path;const get3=path2=>{const thisBase=shortcutRef??base;const res=getFromPath(thisBase,path2,{keySeparator:options.keySeparator,fallbacks:options.fallbacks});return res};const set2=(path2,value)=>{const thisBase=shortcutRef??base;setFromOptions(path2,value,options,{reference:thisBase,listeners:listeners2})};let onUpdate=options.onUpdate;let infoToOutput={};if(onUpdate&&typeof onUpdate==="object"&&onUpdate.callback instanceof Function){infoToOutput=onUpdate.info??{};onUpdate=onUpdate.callback}const absolute=[id2,...path];let pathInfo={absolute,relative:relativePath.split(options.keySeparator),parent:absolute.slice(0,-1)};pathInfo.output=pathInfo[options.pathFormat];const completePathInfo=pathInfo;const info2={id:id2,path:completePathInfo,keySeparator:options.keySeparator,infoToOutput,callback:(...args)=>{const output=callback(...args);if(onUpdate instanceof Function)onUpdate(...args);return output},get current(){return get3(shortcutPath??info2.path.absolute)},set current(val){set2(shortcutPath??info2.path.absolute,val)},get parent(){return get3(shortcutPath?shortcutPath?.slice(0,-1):info2.path.parent)},get reference(){return refs[id2]},set reference(val){refs[id2]=val},original:originalValue,history:typeof originalValue==="object"?Object.assign({},originalValue):originalValue,sub:Symbol("subscription"),last:path.slice(-1)[0]};return info2};var registerInLookup=(name,sub,lookups)=>{if(lookups){const id2=Math.random();lookups.symbol[sub]={name,id:id2};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id2]=sub}};var register=(info2,collection,lookups)=>{const absolute=getPath("absolute",info2);if(!collection[absolute])collection[absolute]={};collection[absolute][info2.sub]=info2;registerInLookup(absolute,info2.sub,lookups);return true};var listeners={functions:functions2,setters};var set=(type,absPath,value,callback,base,allListeners,options)=>{const{id:id2,path}=getPathInfo(absPath,options);const fullInfo=info(id2,callback,path,value,base,listeners,options);if(listeners[type])listeners[type](fullInfo,allListeners[type],allListeners.lookup);else{const path2=getPath("absolute",fullInfo);allListeners[type][path2][fullInfo.sub]=fullInfo;if(allListeners.lookup)registerInLookup(path2,fullInfo.sub,allListeners.lookup)}};var get2=(info2,collection)=>collection[getPath("absolute",info2)];var handler=(info2,collection,subscribeCallback,lookups)=>{let success=!!get2(info2,collection);if(!success){let parent=info2.parent;let val=parent?.[info2.last];success=subscribeCallback(val,parent)}return register(info2,collection,lookups)};var setterExecution=(listeners2,value)=>{return iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,{},value)})};function setters(info2,collection,lookups){const thisValue=this;return handler(info2,collection["setters"],(value,parent)=>{let val=value;if(!parent)return;if(!parent[isProxy]){let redefine=true;try{delete parent[info2.last]}catch(e){console.error("Unable to redeclare setters. May already be a dynamic object...");redefine=false}if(redefine){try{Object.defineProperty(parent,info2.last,{get:()=>val,set:async v=>{const isFunction=typeof val==="function";val=v;if(!isFunction){const listeners2=Object.assign({},collection["setters"][getPath("absolute",info2)]);setterExecution(listeners2,v)}else val=getProxyFunction.call(thisValue,info2,collection,val)},enumerable:true,configurable:true})}catch(e){throw e}}}},lookups)}function getProxyFunction(info2,collection,fn){return function(...args){const listeners2=collection["functions"][getPath("absolute",info2)];return functionExecution(this,listeners2,fn??info2.original,args)}}var functionExecution=(context,listeners2,func,args)=>{listeners2=Object.assign({},listeners2);const keys=Object.getOwnPropertySymbols(listeners2);const infoTemplate=listeners2[keys[0]]??{};const executionInfo=get((...args2)=>func.call(context,...args2),args,infoTemplate.infoToOutput);iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,executionInfo.value,executionInfo.output)});return executionInfo};function functions2(info2,collection,lookups){return handler(info2,collection["functions"],(_,parent)=>{if(!parent[isProxy]){parent[info2.last]=getProxyFunction.call(this,info2,collection);return setters(info2,collection,lookups)}},lookups)}var drillSimple=(obj,callback,options)=>{let accumulator=options.accumulator;if(!accumulator)accumulator=options.accumulator={};const ignore=options.ignore||[];const path=options.path||[];const condition=options.condition||true;const seen=[];const fromSeen=[];let drill=(obj2,acc={},globalInfo)=>{for(let key in obj2){if(ignore.includes(key))continue;const val=obj2[key];const newPath=[...globalInfo.path,key];const info2={typeof:typeof val,name:val?.constructor?.name,simple:true,object:val&&typeof val==="object",path:newPath};if(info2.object){const name=info2.name;const isESM=esm(val);if(isESM||name==="Object"||name==="Array"){info2.simple=true;const idx=seen.indexOf(val);if(idx!==-1)acc[key]=fromSeen[idx];else{seen.push(val);const pass=condition instanceof Function?condition(key,val,info2):condition;info2.pass=pass;acc[key]=callback(key,val,info2);if(pass){fromSeen.push(acc[key]);acc[key]=drill(val,acc[key],{...globalInfo,path:newPath})}}}else{info2.simple=false;acc[key]=callback(key,val,info2)}}else acc[key]=callback(key,val,info2)}return acc};return drill(obj,accumulator,{path})};var createLookup=()=>{return{symbol:{},name:{}}};var Monitor=class{constructor(opts={}){this.poller=new Poller;this.options={pathFormat:"relative",keySeparator};this.listeners={polling:this.poller.listeners,functions:{},setters:{},lookup:createLookup()};this.references={};this.get=(path,output,reference=this.references,throwError=true)=>{return getFromPath(reference,path,{keySeparator:this.options.keySeparator,fallbacks:this.options.fallbacks,output},throwError)};this.set=(path,value,opts2={})=>{const optsCopy={...opts2};if(!optsCopy.reference)optsCopy.reference=this.references;if(!optsCopy.listeners)optsCopy.listeners=this.listeners;return setFromOptions(path,value,this.options,optsCopy)};this.on=(absPath,callback)=>{const info2=getPathInfo(absPath,this.options);return this.listen(info2.id,callback,info2.path)};this.getInfo=(label,callback,path,original)=>{const info2=info(label,callback,path,original,this.references,this.listeners,this.options);const id2=Math.random();const lookups=this.listeners.lookup;const name=getPath("absolute",info2);lookups.symbol[info2.sub]={name,id:id2};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id2]=info2.sub;return info2};this.listen=(id2,callback,path=[],__internal={})=>{if(typeof path==="string")path=path.split(this.options.keySeparator);else if(typeof path==="symbol")path=[path];const arrayPath=path;let baseRef=this.get(id2);if(!baseRef){console.error(`Reference does not exist.`,id2);return}if(!__internal.poll)__internal.poll=esm(baseRef);if(!__internal.seen)__internal.seen=[];const __internalComplete=__internal;const thisPath=[id2,...arrayPath];const ref=this.get(thisPath);const toMonitorInternally=(val,allowArrays=false)=>{const first=val&&typeof val==="object";if(!first)return false;const isEl=val instanceof Element;if(isEl)return false;if(allowArrays)return true;else return!Array.isArray(val)};let subs={};const subscribeAll=toMonitorInternally(ref,true);if(subscribeAll){if(ref.__esInspectable)ref.__esInspectable.options.globalCallback=callback;drillSimple(ref,(_,__,drillInfo)=>{if(drillInfo.pass)return;else{const fullPath=[...arrayPath,...drillInfo.path];const internalSubs=this.listen(id2,callback,fullPath,__internalComplete);Object.assign(subs,internalSubs)}},{condition:(_,val)=>toMonitorInternally(val)})}let info2;let success=false;try{info2=this.getInfo(id2,callback,arrayPath,ref);if(info2){if(__internalComplete.poll)success=this.poller.add(info2);else{let type="setters";if(typeof ref==="function")type="functions";success=this.add(type,info2)}}}catch(e){console.error("Fallback to polling:",path,e);success=this.poller.add(info2)}if(success){subs[getPath("absolute",info2)]=info2.sub;if(this.options.onInit instanceof Function){const executionInfo={};for(let key in info2.infoToOutput)executionInfo[key]=void 0;this.options.onInit(getPath("output",info2),executionInfo)}return subs}else{console.error("Failed to subscribe to:",path);return}};this.add=(type,info2)=>{if(listeners_exports[type])return listeners_exports[type](info2,this.listeners,this.listeners.lookup);else{this.listeners[type][getPath("absolute",info2)][info2.sub]=info2;return true}};this.remove=subs=>{if(!subs){subs={...this.listeners.functions,...this.listeners.setters,...this.listeners.polling}}if(typeof subs!=="object")subs={sub:subs};for(let key in subs){let innerSub=subs[key];const handleUnsubscribe=sub=>{const res=this.unsubscribe(sub);if(res===false)console.warn(`Subscription for ${key} does not exist.`,sub)};if(typeof innerSub!=="symbol")iterateSymbols(innerSub,handleUnsubscribe);else handleUnsubscribe(innerSub)}return true};this.unsubscribe=sub=>{const info2=this.listeners.lookup.symbol[sub];const absPath=info2.name;const polling=this.poller.get(sub);const funcs=this.listeners.functions[absPath];const func=funcs?.[sub];const setters2=this.listeners.setters[absPath];const setter=setters2?.[sub];if(polling)this.poller.remove(sub);else if(func){delete funcs[sub];if(!Object.getOwnPropertySymbols(funcs).length){Object.defineProperty(func.parent,func.last,{value:func.original,writable:true});delete this.listeners.functions[absPath]}}else if(setter){delete setters2[sub];if(!Object.getOwnPropertySymbols(setters2).length){const parent=setter.parent;if(parent){const last=setter.last;const value=parent[last];Object.defineProperty(parent,last,{value,writable:true})}delete this.listeners.setters[absPath]}}else return false;delete this.listeners.lookup.symbol[sub];const nameLookup=this.listeners.lookup.name[info2.name];delete nameLookup[info2.id];if(!Object.getOwnPropertyNames(nameLookup).length)delete this.listeners.lookup.name[info2.name]};Object.defineProperty(this.listeners,"lookup",{value:createLookup(),enumerable:false,configurable:false});Object.assign(this.options,opts);this.poller.setOptions(opts.polling)}};var src_default=Monitor;var defaultPath="default";var operatorPath="__operator";var specialKeys={path:"__path",isGraphScript:"__",listeners:{value:"__listeners",branch:"__branch",bind:"__bind",trigger:"__trigger",format:"__format"}};var listenerObject=Symbol("listenerObject");var toSet=Symbol("toSet");var subscriptionKey=Symbol("subscriptionKey");var configKey=Symbol("configKey");var toResolveWithKey=Symbol("toResolveWithKey");var isConfigObject=o=>specialKeys.listeners.format in o||specialKeys.listeners.branch in o||specialKeys.listeners.trigger in o||specialKeys.listeners.bind in o;var initializedStatus="INITIALIZED";var registeredStatus="REGISTERED";var globalFrom={};var globalTo={};var globalActive={};var _triggers,_queue,_toResolveWith,_initialize,_getAbsolutePath,_getPathInfo;var Edgelord=class{constructor(listeners2,root,context){this.original={};this.active={};this.globals={};this.context={options:{}};this.rootPath="";this.status="";__privateAdd(this,_triggers,[]);__privateAdd(this,_queue,[]);__privateAdd(this,_toResolveWith,void 0);this.setInitialProperties=(listeners2={},root,context={})=>{Object.assign(this.context,context);if(root)this.rootPath=root;if(!this.context.options.keySeparator)this.context.options.keySeparator=this.context.monitor.options.keySeparator;this.original=listeners2;const globals=[{name:"active",ref:globalActive},{name:"from",ref:globalFrom},{name:"to",ref:globalTo}];globals.forEach(o=>{if(!o.ref[this.context.id])o.ref[this.context.id]={};this.globals[o.name]=o.ref[this.context.id]});__privateSet(this,_toResolveWith,this.getManager());this.runEachListener(listeners2,this.addToGlobalLog)};this.getManager=(mode="from")=>{let target=mode==="to"?this.globals.to:this.globals.from;this.rootPath.split(this.context.options.keySeparator).forEach(key=>{if(!target[key])target[key]={};target=target[key]});return target[toResolveWithKey]??this};this.onStart=f=>{const res=__privateGet(this,_toResolveWith);const isSame2=res===this;if(isSame2){if(this.status===initializedStatus)f();else __privateGet(this,_queue).push(f)}else res.onStart(f)};this.runEachListener=(listeners2,callback)=>{if(!callback)return;for(const first in listeners2){const second=listeners2[first];if(!second){console.warn("Skipping empty listener:",first);continue}if(second&&typeof second==="object"){const from=second;const to=first;for(let fromPath in from){callback(fromPath,to,from[fromPath])}}else{const from=first;const to=second;const typeOf=typeof to;if(typeOf==="function")callback(from,"",to);else if(typeOf==="string")callback(from,to,to);else console.error("Improperly Formatted Listener",to)}}};this.register=(listeners2=this.original)=>{this.runEachListener(listeners2,this.add);this.status=registeredStatus};__privateAdd(this,_initialize,o=>{const res=this.context.monitor.get(o.path,"info");if(typeof res.value==="function"){const args=Array.isArray(o.args)?o.args:[o.args];res.value(...args)}else console.error("Cannot yet trigger values...",o)});this.initialize=o=>{if(!this.status)__privateGet(this,_triggers).push(o);else if(this.status===registeredStatus){this.status=initializedStatus;__privateGet(this,_triggers).forEach(__privateGet(this,_initialize));__privateGet(this,_queue).forEach(f=>f());__privateSet(this,_queue,[]);__privateSet(this,_triggers,[])}else __privateGet(this,_initialize).call(this,o)};this.start=()=>{this.register();this.initialize()};__privateAdd(this,_getAbsolutePath,name=>{const sep=this.context.monitor.options.keySeparator;return!name||!this.rootPath||this.rootPath===name.slice(0,this.rootPath.length)&&name[this.rootPath.length]===sep?name:[this.rootPath,name].join(sep)});__privateAdd(this,_getPathInfo,path=>{const output={absolute:{},relative:{}};path=__privateGet(this,_getAbsolutePath).call(this,path);let rel=this.rootPath?path.replace(`${this.rootPath}.`,""):path;const baseArr=path.split(this.context.options.keySeparator);output.absolute.array=[this.context.id,...baseArr];output.relative.array=rel.split(this.context.options.keySeparator);let obj=this.context.monitor.get(output.relative.array,void 0,this.context.instance,false);if(this.context.graph){if(obj&&this.context.bound){output.absolute.array=[this.context.id,this.context.bound,...output.absolute.array.slice(1)];output.relative.array.unshift(this.context.bound)}else if(!obj){const rel2=output.relative.array.join(this.context.options.keySeparator);obj=this.context.graph.get(rel2)}}const isGraphScript=obj&&typeof obj==="object"&&specialKeys.isGraphScript in obj;if(isGraphScript){if(obj[operatorPath]){output.absolute.array.push(operatorPath);output.relative.array.push(operatorPath)}else if(obj[defaultPath]){output.absolute.array.push(defaultPath);output.relative.array.push(defaultPath)}}output.absolute.value=output.absolute.array.slice(1).join(this.context.options.keySeparator);output.relative.value=output.relative.array.join(this.context.options.keySeparator);return output});this.add=(from,to,value=true,subscription)=>{if(typeof to=="function"){value=to;to=""}else if(typeof to!=="string"){console.error("Improperly Formatted Listener",from,to,value);return}if(!value)return;const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const absPath=fromInfo.absolute.value;if(!subscription)subscription=this.globals.active[absPath]?.[subscriptionKey];if(!subscription){subscription=this.context.monitor.on(fromInfo.absolute.array,(path,_,update)=>this.activate(path,update),{ref:this.context.instance,path:fromInfo.relative.array})}if(typeof value=="string")value=toInfo.absolute.array.slice(1).join(this.context.options.keySeparator);const info2={value,[listenerObject]:true};const refs=[this.active,this.globals.active];refs.forEach(ref=>{if(!ref[absPath])ref[absPath]={};const base=ref[absPath];if(!base[subscriptionKey]){Object.defineProperty(base,subscriptionKey,{value:subscription,configurable:true})}base[toInfo.absolute.value]=info2});const args=value[specialKeys.listeners.trigger];if(args)__privateGet(this,_toResolveWith).initialize({path:fromInfo.absolute.array,args});this.addToGlobalLog(absPath);return info2};this.addToGlobalLog=(path,mode="from")=>{const absolutePath=__privateGet(this,_getAbsolutePath).call(this,path);let target=mode==="to"?this.globals.to:this.globals.from;const globalPath=absolutePath.split(this.context.options.keySeparator);globalPath.forEach(key=>{if(!target[key])target[key]={};target=target[key];if(!target[toResolveWithKey])target[toResolveWithKey]=this})};this.remove=(from,to)=>{const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const path=[fromInfo.absolute.value,toInfo.absolute.value];const toRemove=[{ref:this.active,path},{ref:this.globals.active,path,unlisten:true}];toRemove.forEach(o=>{const{ref,path:path2,unlisten}=o;let base=ref[path2[0]];if(typeof base==="object"){delete base[path2[1]];if(Object.keys(base).length===0){delete ref[path2[0]];const sub=base[subscriptionKey];if(unlisten&&sub){this.context.monitor.remove(sub)}delete base[subscriptionKey]}}else delete ref[path2[0]]})};this.clear=name=>{const value=__privateGet(this,_getAbsolutePath).call(this,name);Object.keys(this.active).forEach(from=>{Object.keys(this.active[from]).forEach(to=>{if(!value||from.slice(0,value.length)===value||to.slice(0,value.length)===value)this.remove(from,to)})})};this.has=(from,ref=this.active)=>!!ref[from];this.get=(from,ref=this.active)=>ref[from];this.activate=(from,update)=>{const listenerGroups=[{info:this.get(from,this.globals.active),name:from}];listenerGroups.forEach(group=>{const info2=group.info;if(info2){if(info2[listenerObject]){this.pass(from,{value:info2.value,parent:this.active,key:group.name,subscription:info2.subscription,__value:true},update)}else if(typeof info2==="object"){for(let key in info2){this.pass(from,{parent:info2,key,subscription:info2[key].subscription,value:info2[key].value},update)}}else console.error("Improperly Formatted Listener",info2)}})};this.pass=(from,target,update)=>{const id2=this.context.id;const isValue=target?.__value;let parent=target.parent;let to=target.key;const info2=target.parent[to];target=info2.value;let config=info2?.[configKey];let ogValue=target;const type=typeof target;const checkIfSetter=(path,willSet)=>{const info3=this.context.monitor.get(path,"info");if(info3.exists){const val=info3.value;const noDefault=typeof val!=="function"&&!val?.default;const value=noDefault?toSet:val;const res={value};if(willSet){target=res.value;parent[to]=res}return res}else return{value:void 0}};const transform=willSet=>{const fullPath=[id2];fullPath.push(...to.split(this.context.options.keySeparator));return checkIfSetter(fullPath,willSet)};const getPathArray=latest=>{const path=[id2];const topPath=[];if(this.rootPath)topPath.push(...this.rootPath.split(this.context.options.keySeparator));topPath.push(...latest.split(this.context.options.keySeparator));path.push(...topPath);return path};if(typeof target==="boolean"){if(!isValue)transform(true);else console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`)}else if(type==="string"){const path=getPathArray(ogValue);checkIfSetter(path,true);if(isValue){parent[to]={[ogValue]:parent[to]};to=ogValue}}else if(target&&type==="object"){const isConfig=isConfigObject(ogValue);if(isConfig){if("value"in ogValue){if(isValue){target=parent[to]=ogValue.value}else{target=parent[to].value=ogValue.value}}else transform(true);if(ogValue){if(ogValue)config=ogValue}Object.defineProperty(parent[to],configKey,{value:config})}}let isValidInput=true;if(config){const bindKey=specialKeys.listeners.value;if(bindKey in config){const path=getPathArray(config[bindKey].original??config[bindKey]);if(typeof config[bindKey]==="string"){const res=this.context.monitor.get(path);if(!res)target=`because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.`;else{config[bindKey]={value:res,original:config[bindKey]}}}else if(!config[bindKey].value.__parent){target=`because ${config[bindKey].original??id2.toString()} has become unparented.`}}else{const branchKey=specialKeys.listeners.branch;const formatKey=specialKeys.listeners.format;if(branchKey in config){const isValid=config[branchKey].find(o=>{let localValid=[];if("if"in o)localValid.push(o.if(update));if("is"in o)localValid.push(o.is===update);const isValidLocal=localValid.length>0&&localValid.reduce((a,b)=>a&&b,true);if(isValidLocal){if("value"in o)update=o.value}return isValidLocal});if(!isValid)isValidInput=false}if(formatKey in config){try{update=config[formatKey](update);if(update===void 0)isValidInput=false}catch(e){console.error("Failed to format arguments",e)}}}}if(isValidInput&&update!==void 0){const arrayUpdate=Array.isArray(update)?update:[update];if(target===toSet){const parentPath=[id2];parentPath.push(...to.split(this.context.options.keySeparator));const idx=parentPath.pop();const info3=this.context.monitor.get(parentPath,"info");if(info3.value)info3.value[idx]=update;else console.error(`Cannot set value on ${parentPath.filter(str2=>typeof str2!=="symbol").join(this.context.options.keySeparator)} from ${from}`)}else if(target?.default)target.default.call(target,...arrayUpdate);else if(typeof target==="function"){const noContext=parent[to][listenerObject];if(noContext)target.call(config?.[specialKeys.listeners.bind]?.value??this.context.instance,...arrayUpdate);else target(...arrayUpdate)}else{let baseMessage=to?`listener: ${from} \\u2014> ${to}`:`listener from ${from}`;if(parent){console.warn(`Deleting ${baseMessage}`,target);delete parent[to]}else console.error(`Failed to add ${baseMessage}`,target)}}};if(listeners2||root||context)this.setInitialProperties(listeners2,root,context)}};_triggers=new WeakMap;_queue=new WeakMap;_toResolveWith=new WeakMap;_initialize=new WeakMap;_getAbsolutePath=new WeakMap;_getPathInfo=new WeakMap;var edgelord_default=Edgelord;function applyLoader(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loader){const args=[node,parent,graph,tree,properties,tag];if(typeof loader==="object"){if(loader.init)loader(...args);if(loader.connected)node.__addOnconnected(loader.connect);if(loader.disconnected)node.__addOndisconnected(loader.disconnect)}else if(typeof loader==="function")loader(...args)}function applyLoaders(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loaders2=this.__node.loaders){for(const l in loaders2)applyLoader(node,parent,graph,tree,properties,tag,loaders2[l])}var _parent,_graph,_properties,_options,_applied,_applySetters;var GraphNode=class{constructor(properties,parent,graph,options){this.__=Symbol("graphscript");this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,ref:this,flow:new edgelord_default};__privateAdd(this,_parent,void 0);__privateAdd(this,_graph,void 0);__privateAdd(this,_properties,{});__privateAdd(this,_options,{});__privateAdd(this,_applied,[]);__privateAdd(this,_applySetters,(properties=__privateGet(this,_properties),proxy=__privateGet(this,_properties),ignore=[])=>{const isProxy2=proxy===true;let keys=Object.getOwnPropertyNames(properties);if(isProxy2){proxy=properties;keys=getAllPropertyNames(properties)}for(const key of keys){if(ignore.includes(key))continue;if(__privateGet(this,_applied).includes(key))continue;__privateGet(this,_applied).push(key);if(key==="__properties")Object.defineProperty(this,key,{get:()=>__privateGet(this,_properties),enumerable:true});else if(key==="__props"){Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>{proxy[key]=value;__privateGet(this,_applySetters).call(this,value,true)},enumerable:true,configurable:true})}else{Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>proxy[key]=value,enumerable:true,configurable:false})}}});this.____apply=__privateGet(this,_applySetters);this.__init=(properties,parent=__privateGet(this,_parent),graph=__privateGet(this,_graph),options=__privateGet(this,_options))=>{__privateSet(this,_parent,parent);__privateSet(this,_graph,graph);__privateSet(this,_options,options);if(properties){let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(typeof properties==="object"){if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}properties=properties.__node.tree}__privateSet(this,_properties,properties);if(!properties.__node)properties.__node={};if(!properties.__node.initial)this.__node.initial=orig;if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph)properties.__node.graph=graph;if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;properties.__node=Object.assign(this.__node,properties.__node);const ogProperties=properties;__privateGet(this,_applySetters).call(this);applyLoaders.call(graph,this,parent,graph,graph?.__node?.tree,properties);__privateGet(this,_applySetters).call(this,void 0,void 0,["__props"]);if(properties instanceof Graph)this.__node.source=properties;if(typeof options.onInit==="function")options.onInit();if(graph){const symbol=(graph.__node.ref??this).__;const monitor=graph.monitor;this.__node.flow.setInitialProperties(this.__listeners,void 0,{id:symbol,instance:this,monitor,graph,bound:this.__node.tag})}else console.error("No flow manager created for "+this.__node.tag)}}};this.__init(properties,parent,graph,options)}get __properties(){return __privateGet(this,_properties)}__addOnconnected(callback){if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o.call(this,this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o.call(this,this)})}}};_parent=new WeakMap;_graph=new WeakMap;_properties=new WeakMap;_options=new WeakMap;_applied=new WeakMap;_applySetters=new WeakMap;var _init;var _Graph=class{constructor(options){this.monitor=new src_default({keySeparator:".",fallbacks:["__children"]});this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,ref:new GraphNode,loaders:[props_loader_default]};this.init=options=>{if(options){if(options.loaders){this.setLoaders(options.loaders);delete options.loaders}recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};__privateAdd(this,_init,properties=>{const node=this.__node.ref;node.__init(properties,this,this,{onInit:()=>{this.monitor.set(node.__,node.__properties)}});return node});this.setTree=tree=>{const hasGraphscriptProperties=Object.keys(tree).find(str2=>{const slice=str2.slice(0,2);return slice==="__"&&str2!=="__node"});if(!hasGraphscriptProperties)tree={__children:tree};if(!tree.__node)tree.__node={};this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners2=this.recursiveSet(cpy,this,void 0,tree);if(!tree.__node.tag)tree.__node.tag=this.__node.tag;const node=__privateGet(this,_init).call(this,tree);const children=node.__children;const copy=Object.assign({},children);if(children)listeners2=this.recursiveSet(copy,this,void 0,children);if(node.__listeners)listeners2[node.__node.tag]=node.__listeners;this.__node.nodes.forEach(n=>n.__node.flow.start());node.__callConnected();return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else{if(Array.isArray(this.__node.loaders)){if(Array.isArray(loaders2))this.__node.loaders=[...this.__node.loaders,...loaders2];else this.__node.loaders=[...this.__node.loaders,...Object.values(loaders2)]}else Object.assign(this.__node.loaders,loaders2)}return this.__node.loaders};this.add=(properties,parent)=>{let listeners2={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}node.__callConnected();return node}return};this.recursiveSet=(t,parent,listeners2={},origin=t)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent,this);this.set(node.__node.tag,node);t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}let parentNode=parent instanceof _Graph?parent.__node.ref:parent;parentNode.__addOnconnected(()=>node.__callConnected())}}return listeners2};this.remove=node=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];this.clearListeners(node);node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){const node2=t[key].__node.ref;this.clearListeners(node2);this.delete(node2.__node.tag);delete this.__node.tree[node2.__node.tag];this.delete(key);delete this.__node.tree[key];node2.__node.tag=node2.__node.tag.substring(node2.__node.tag.lastIndexOf(".")+1);this.clearListeners(node2);node2.__callDisconnected();if(node2.__children)recursiveRemove(node2.__children)}};if(node.__children)recursiveRemove(node.__children)}if(node?.__node.tag&&node?.__parent){node.__parent=void 0;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.clearListeners=node=>{this.unsubscribe(node);this.clear(node)};this.get=(tag,base)=>{if(base instanceof GraphNode)base=base.__node.tag;if(tag===this.__node.tag)return this.__node.ref;if(base){const relFrom=[base,tag].join(".");const got=this.get(relFrom);if(got)return got}return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(from,to,value=true,bound=this.__node.ref)=>{if(typeof from!=="string")from=from.__node.tag;if(typeof bound==="string")bound=this.get(bound);if(bound)bound.__node.flow.add(from,to,value)};this.unsubscribe=(node,from,to)=>this.clear(from,to,node);this.clear=(from,to,bound)=>{const nd=typeof bound==="string"?this.get(bound):bound;if(typeof from==="symbol")return this.__node.flow.remove(from);let fromString=from instanceof GraphNode?from.__node.tag:from;let toString=to instanceof GraphNode?to.__node.tag:to;const remove=n=>{const flow=n.__node.flow;toString?flow.remove(fromString,toString):flow.clear(fromString)};if(nd)remove(nd);else{remove(this.__node.ref);this.__node.nodes.forEach(remove)}};this.activate=(from,value)=>this.__node.ref.__node.flow.activate(from,value);this.setState=update=>{for(let key in update)this.activate(key,update)};this.init(options)}};var Graph=_Graph;_init=new WeakMap;function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllPropertyNames(obj){var props=[];do{if(obj.constructor.name==="Object")props.push(...Object.keys(obj));else Object.getOwnPropertyNames(obj).forEach(function(prop){if(props.indexOf(prop)===-1)props.push(prop)})}while(obj=Object.getPrototypeOf(obj));return props}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode)graph.subscribe(parent.__node.tag,node.__node.tag)};var loop=(node,parent,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;const delay=(...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})};node.__operator=delay}else if(node.__node.frame===true){let fn=node.__operator;const frame=(...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})};node.__operator=frame}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;const repeat=async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result};node.__operator=repeat}if(node.__node.loop&&typeof node.__node.loop==="number"){let ogFunction=node.__operator;const looper=function(...args){if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){const res=ogFunction.call(node,...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop);return res}};node.__operator=looper;node.__addOnconnected(node2=>{if(node2.__node.looping)node2.__operator()});let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;const animate2=(...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn.call(node,...args);requestAnimationFrame(()=>{node.__operator(...args)})}return true};node.__operator=animate2;node.__addOnconnected(node2=>{if(node2.__node.animating||(!("animating"in node2.__node)||node2.__node.animating)&&node2.__animation)setTimeout(()=>{requestAnimationFrame(node2.__operator)},10)});node.__addOndisconnected(node2=>{if(node2.__node.animating)node2.__node.animating=false})}};var branching=(node,parent,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__operator=node.post}else if(!node.__operator&&typeof node.get=="function"){node.__operator=node.get}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set2=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set2(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\\\"))args[0]=args[0].replace(/\\\\/g,"");if(args[0][0]===\'"\'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var ECSService=class extends Service{constructor(options){super(options);this.entities={};this.systems={};this.entityMap=new Map;this.entityKeyMap=new Map;this.order=[];this.animating=false;this.entityCt=0;this.systemCt=0;this.updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};this.animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};this.stop=()=>{this.animating=false};this.start=filter=>{this.animateEntities(filter)};this.addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};this.addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};this.addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};this.setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};this.removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};this.removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};this.setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};this.setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};this.bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j{this.removeEntity(t)})}filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}};var import_sjcl=__toESM(require_sjcl());var _HTTPfrontend=class extends Service{constructor(options,path,fetched){super(options);this.name="http";this.fetchProxied=false;this.listening={};this.GET=(url="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{let obj=message;if(typeof obj==="object"){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url);return this.POST(message,url)};this.transponder=(url,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url,data:message,responseType:type,onload:ev2=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\\\"))body=body.replace(/\\\\/g,"");if(body[0]===\'"\'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};this.listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch2,that,args){const result=fetch2.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};this.stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}};this.setTree(this);this.listen(path,fetched)}};var HTTPfrontend=_HTTPfrontend;HTTPfrontend.request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id2)}else worker.postMessage({route:"handleProxyEvent",args:[data,id2]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler2]of entries){element.addEventListener(eventName,function(event){handler2(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id2}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners2=this.__listeners;if(listeners2[type]===void 0){listeners2[type]=[]}if(listeners2[type].indexOf(listener)===-1){listeners2[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners2=this.__listeners;return listeners2[type]!==void 0&&listeners2[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id2,addTo=void 0)=>{if(!id2)id2=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id2])proxy=this.targets[id2];else{proxy=new ElementProxyReceiver;this.targets[id2]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id2=>{return this.targets[id2]};this.handleEvent=(data,id2)=>{if(!this.targets[id2])this.makeProxy(id2);if(this.targets[id2]){this.targets[id2].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id2,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id2,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id2,elm)}return id2}function handleProxyEvent(data,id2){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id2))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id2))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id2){let canvasopts;if(this?.__node?.graph){if(_id2)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id2)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText2(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText2(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText2(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText2(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText2(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText2(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText2(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText2(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}}return void 0}function clearCanvas(_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}function initCanvas(_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}function updateCanvas(input,_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id2}return void 0}function setProps(props,_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id2}return void 0}function startAnim(_id2,draw){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText2(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id2}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}function stopAnim(_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\\W*(function[^{]+\\{([\\s\\S]*)\\}|[^=]+=>[^{]*\\{([\\s\\S]*)\\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w=s.worker;let wpId;wpId=service.establishMessageChannel(w.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w.run("setValue",["routeProxy",s.route]);w.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w2=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w.worker,w2.worker);s.pipeTo.worker=w2}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w.run("setValue",["routeProxy",s.route]);service.transferFunction(w,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id2){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id2)_id2=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id2)return;Object.assign(this.__node.graph.ALGORITHMS[_id2],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id2){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id2)_id2=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id2)return;let res=this.__node.graph.ALGORITHMS[_id2].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id2]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id2]:res});return res}}}};var import_bson_objectid=__toESM(require_objectid());var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp2={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp2);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u=(dot11*dot02-dot01*dot12)*_denom;let v=(dot00*dot12-dot01*dot02)*_denom;if(u>=0&&v>=0&&u+v<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v=>{let magnitude=0;for(const key in v){magnitude+=v[key]*v[key]}return Math.sqrt(magnitude)},normalize:v=>{let magnitude=Systems.collision.magnitude(v);let _mag=magnitude?1/magnitude:0;let vn=Object.assign({},v);for(const key in v){vn[key]=v[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now2=performance.now();let timeStep=now2-this.lastTime;this.lastTime=now2;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var __defProp3=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp3(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField2=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y2)=>{return v+x2+y2}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y2)=>{return[x2*10,y2*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize2=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y2=0;y2{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField2(Math2,"TWO_PI",Math.PI*2);__publicField2(Math2,"C",299792458);__publicField2(Math2,"G",66743e-15);__publicField2(Math2,"h",662607015e-42);__publicField2(Math2,"R",8314.32);__publicField2(Math2,"Ra",287);__publicField2(Math2,"H",69.3);__publicField2(Math2,"kbar",1054571817e-43);__publicField2(Math2,"kB",1380649e-29);__publicField2(Math2,"ke",89875517923e-1);__publicField2(Math2,"me",91093837015e-41);__publicField2(Math2,"mp",167262192369e-38);__publicField2(Math2,"mn",167492749804e-38);__publicField2(Math2,"P0",101325);__publicField2(Math2,"T0",288.15);__publicField2(Math2,"p0",1.225);__publicField2(Math2,"Na",60220978e16);__publicField2(Math2,"y",1.405);__publicField2(Math2,"M0",28.96643);__publicField2(Math2,"g0",9.80665);__publicField2(Math2,"Re",6378100);__publicField2(Math2,"B",1458e-9);__publicField2(Math2,"S",110.4);__publicField2(Math2,"Sigma",365e-12);__publicField2(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField2(Math2,"integral",(func=x2=>{let y2=x2;return y2},range=[],stepx=.01)=>{let area2=0;for(let i=range[0];i{let z=x2+y2;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y2+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x2;return y2},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y2=0;y2{function lerp2(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp2(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField2(Math2,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;ikey in obj?__defProp4(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField3=(obj,key,value)=>{__defNormalProp2(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math22=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y2)=>{return v+x2+y2}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math22.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y2)=>{return[x2*10,y2*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize2=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math22.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y2=0;y2{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math22.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math22=_Math22;__publicField3(Math22,"TWO_PI",Math.PI*2);__publicField3(Math22,"C",299792458);__publicField3(Math22,"G",66743e-15);__publicField3(Math22,"h",662607015e-42);__publicField3(Math22,"R",8314.32);__publicField3(Math22,"Ra",287);__publicField3(Math22,"H",69.3);__publicField3(Math22,"kbar",1054571817e-43);__publicField3(Math22,"kB",1380649e-29);__publicField3(Math22,"ke",89875517923e-1);__publicField3(Math22,"me",91093837015e-41);__publicField3(Math22,"mp",167262192369e-38);__publicField3(Math22,"mn",167492749804e-38);__publicField3(Math22,"P0",101325);__publicField3(Math22,"T0",288.15);__publicField3(Math22,"p0",1.225);__publicField3(Math22,"Na",60220978e16);__publicField3(Math22,"y",1.405);__publicField3(Math22,"M0",28.96643);__publicField3(Math22,"g0",9.80665);__publicField3(Math22,"Re",6378100);__publicField3(Math22,"B",1458e-9);__publicField3(Math22,"S",110.4);__publicField3(Math22,"Sigma",365e-12);__publicField3(Math22,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField3(Math22,"integral",(func=x2=>{let y2=x2;return y2},range=[],stepx=.01)=>{let area2=0;for(let i=range[0];i{let z=x2+y2;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y2+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x2;return y2},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y2=0;y2{function lerp2(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp2(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField3(Math22,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{if(!("ax"in data)&&!("gx"in data))return void 0;if(!data.timestamp){if(data.ax&&Array.isArray(data.ax)||data.gx&&Array.isArray(data.gx)){let len=data.ax?data.ax.length:data.gx.length;let now2=Date.now();let toInterp=[now2-len*ctx.sps*1e3,now2];data.timestamp=Math22.upsample(toInterp,len)}else{data.timestamp=Date.now()}}let result;if(data.ax){let apass=(timestamp,ax,ay,az)=>{ax=ax*ctx.accelConstant;ay=ay*ctx.accelConstant;az=az*ctx.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+ctx.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+ctx.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v,i)=>{return apass(v,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-ctx.lastGyroTime;ctx.lastGyroTime=timestamp;gx=gx*ctx.gyroConstant+ctx.gyroXError;gy=gy*ctx.gyroConstant+ctx.gyroYError;gz=gz*ctx.gyroConstant+ctx.gyroZError;ctx.gyroXAngle+=gx*elapsed;ctx.gyroYAngle+=gy*elapsed;ctx.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:ctx.gyroXAngle,pitch:ctx.gyroYAngle,yaw:ctx.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v,i)=>{if(result){let r=gpass(v,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(ctx.gyroXAngle||ctx.gyroYAngle||ctx.gyroZAngle){result.roll=result.roll*.04+ctx.gyroXAngle*.96;result.pitch=result.pitch*.04+ctx.gyroYAngle*.96;result.yaw=ctx.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-ctx.lastAccelTime;ctx.lastAccelTime=timestamp;ctx.px+=result2.ax*elapsed*elapsed*Math.cos(ctx.pitch*Math.PI*.005555555555);ctx.py+=result2.ay*elapsed*elapsed*Math.cos(ctx.roll*Math.PI*.005555555555);ctx.pz+=result2.az*elapsed*elapsed*Math.sin(ctx.pitch*Math.PI*.005555555555);result2.px=ctx.px;result2.py=ctx.py;result2.pz=ctx.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){this.a0=0;this.a1=0;this.a2=0;this.b0=0;this.b1=0;this.b2=0;this.x1=0;this.x2=0;this.y1=0;this.y2=0;let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: \'lowpass\',\'highpass\',\'bandpass\',\'notch\',\'peak\',\'lowshelf\',\'highshelf\'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A+A);this[type](A,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A,sn,cs,alpha,beta){this.b0=1+alpha*A;this.b1=-2*cs;this.b2=1-alpha*A;this.a0=1+alpha/A;this.a1=-2*cs;this.a2=1-alpha/A}lowshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1-(A-1)*cs+beta*sn);this.b1=2*A*(A-1-(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1+(A+1)*cs+beta*sn;this.a1=2*(A-1+(A+1)*cs);this.a2=A+1+(A-1)*cs-beta*sn}highshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1+(A-1)*cs+beta*sn);this.b1=2*A*(A-1+(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1-(A+1)*cs-beta*sn;this.a1=2*(A-1-(A+1)*cs);this.a2=A+1-(A-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={structs:{refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10},oncreate:context=>{if(!context.lowpass){let freq=context.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;context.lowpass=new Biquad("lowpass",context.maxFreq,context.sps);context.peakFinderWindow=Math.floor(context.sps/context.maxFreq);if(context.peakFinderWindow%2===0)context.peakFinderWindow+=1;if(context.peakFinderWindow<5)context.peakFinderWindow=5;context.midpoint=Math.round(context.peakFinderWindow*.5)}},ondata:(context,data)=>{if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now2=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now2-refdata.length*context.sps*1e3,now2];data.timestamp=Math22.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){context.refdata.push(amplitude)}context.timestamp.push(timestamp);let beat;if(context.refdata.length>context.peakFinderWindow){context.refdata.shift();context.timestamp.shift()}context.smoothed.push(context.lowpass.applyFilter(context.refdata[context.refdata.length-1]));if(context.smoothed.length>context.peakFinderWindow){context.smoothed.shift()}if(context.smoothed.length===context.peakFinderWindow){if(Math22.isExtrema(context.smoothed,"valley")){context.valleys.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}else if(Math22.isExtrema(context.smoothed,"peak")){context.peaks.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}if(context.valleys.length>2&&context.peaks.length>2){if(context.valleys[context.valleys.length-1].timestamp1&&context.valley_distances.length>1){if(context.lastPeakcontext.peak_distances[context.peak_distances.length-1].timestamp){let bpm,change=0;if(context.beats.length<1){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].distance+context.valley_distances[context.valley_distances.length-1].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-1].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].dt+context.valley_distances[context.valley_distances.length-1].dt));change=Math.abs(bpm-context.beats[context.beats.length-1].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-1].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-1].peak0-context.valley_distances[context.valley_distances.length-1].peak0,height1:context.peak_distances[context.peak_distances.length-1].peak1-context.valley_distances[context.valley_distances.length-1].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}else{let bpm,change=0;if(context.beats.length<2){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-2].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance));change=Math.abs(bpm-context.beats[context.beats.length-2].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-2].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-2].peak0-context.valley_distances[context.valley_distances.length-2].peak0,height1:context.peak_distances[context.peak_distances.length-2].peak1-context.valley_distances[context.valley_distances.length-2].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}}}if(context.peaks.length>context.limit){context.peaks.shift()}if(context.valleys.length>context.limit){context.valleys.shift()}if(context.peak_distances.length>context.limit){context.peak_distances.shift()}if(context.valley_distances.length>context.limit){context.valley_distances.shift()}if(context.beats.length>context.limit){context.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)data.red.map((v,i)=>{return pass(v+data.ir[i],data.timestamp[i])});else data.red.map((v,i)=>{return pass(v,data.timestamp[i])});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v,i)=>{return pass(v,data.timestamp[i])});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v,i)=>{return pass(v,data.timestamp[i])});return result}}};var blink_detect={structs:{sps:250,intervals:{},watch:["0"],tolerance:.2},oncreate:ctx=>{ctx.watch.forEach(ch=>ctx.intervals[ch]={lowpass:new Biquad("lowpass",20,ctx.sps),filtered:[],averaged:[]})},ondata:(ctx,data)=>{let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=ctx.intervals[key].lowpass.applyFilter(n);ctx.intervals[key].filtered.push(next);ctx.intervals[key].averaged.push(next);if(ctx.intervals[key].filtered.length>checkCt){if(ctx.intervals[key].averaged.length>averageCt){ctx.intervals[key].averaged.splice(0,checkCt);let mean=Math22.mean(ctx.intervals[key].averaged);if(Math.abs(Math.min(...ctx.intervals[key].filtered))>Math.abs(mean)+ctx.tolerance){ctx.intervals[key].filtered.length=0;passed=true;found[key]=true}}else ctx.intervals[key].filtered.shift()}};for(const key in ctx.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var _ArrayManip=class{constructor(){this.recursivelyAssign=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target}}static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp2){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp2){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp2){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now2=Date.now();let toInterp=[now2-ct*1e3/sps,now2];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d={};data.forEach((arr,i)=>{d[i]=arr});data=d;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\\r\\n")){let lines=data.split("\\r\\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var ArrayManip=_ArrayManip;ArrayManip.bufferValues=(objects2,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects2);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects2[object_keys[0]][property]==="object"){keys=Object.keys(objects2[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects2){if(objects2[key][property]){if(keys){for(let j=0;j])?(([1-9]\\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\\d*)?([xcbB?hHiIfdsp])/g;var str=(v,o,c)=>String.fromCharCode(...new Uint8Array(v.buffer,v.byteOffset+o,c));var rts=(v,o,c,s)=>new Uint8Array(v.buffer,v.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v,o,c)=>str(v,o+1,Math.min(v.getUint8(o),c-1));var tsp=(v,o,c,s)=>{v.setUint8(o,s.length);rts(v,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v=>str(v,o,1),p:(v,c2)=>rts(v,o,1,c2)})],"?":c=>[c,1,o=>({u:v=>Boolean(v.getUint8(o)),p:(v,B)=>v.setUint8(o,B)})],b:c=>[c,1,o=>({u:v=>v.getInt8(o),p:(v,b)=>v.setInt8(o,b)})],B:c=>[c,1,o=>({u:v=>v.getUint8(o),p:(v,B)=>v.setUint8(o,B)})],h:c=>[c,2,o=>({u:v=>v.getInt16(o,le),p:(v,h)=>v.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v=>v.getUint16(o,le),p:(v,H)=>v.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v=>v.getInt32(o,le),p:(v,i)=>v.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v=>v.getUint32(o,le),p:(v,I)=>v.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v=>v.getFloat32(o,le),p:(v,f)=>v.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v=>v.getFloat64(o,le),p:(v,d)=>v.setFloat64(o,d,le)})],s:c=>[1,c,o=>({u:v=>str(v,o,c),p:(v,s)=>rts(v,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v=>pst(v,o,c),p:(v,s)=>tsp(v,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var _ByteParser=class extends ArrayManip{static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp2=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp2)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp2)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp2)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x2){let int24=(255&x0)<<16|(255&x1)<<8|255&x2;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x2){return x0*65536+x1*256+x2}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x2,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x2)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x2,x3){return x0*16777216+x1*65536+x2*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M=pattern.length;if(M===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R=256;var rightmost_positions=new Int32Array(R);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v=new DataView(arrb,offs|0);return fns.map(f=>f.u(v))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var ByteParser=_ByteParser;ByteParser.codes={"\\\\n":10,"\\\\r":13,"\\\\t":9,"\\\\s":32,"\\\\b":8,"\\\\f":12,"\\\\":92};var rms={structs:{sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{}},ondata:(ctx,data)=>{ctx.watch.forEach(key=>{if(data[key]){if(!ctx.data[key]){if(Array.isArray(data[key])){ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key][0])}else ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key])}ByteParser.circularBuffer(ctx.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){ctx.rms.timestamp=data.timestamp[data.timestamp.length-1]}else ctx.rms.timestamp=data.timestamp}else ctx.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(ctx.watch.map(async key=>{if(ctx.data[key])ctx.rms[key]=Math.sqrt(Math.abs(ctx.data[key].reduce((p,v,i)=>p+v*v)/ctx.data[key].length));else delete ctx.rms[key]}));res(ctx.rms)})}};var circularBuffer2d={structs:{bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false},oncreate:ctx=>{for(const key in ctx.watch){ctx.data[key]=new Array(ctx.bufferSize).fill(0)}},ondata:(ctx,data)=>{let buffer2d=[];ctx.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(ctx.data[key],data[key]);buffer2d.push(ctx.data[key])}});return buffer2d}};Object.assign(algorithms,{beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d});algorithms["breath"].structs=JSON.parse(JSON.stringify(algorithms["breath"].structs));algorithms["breath"].structs.maxFreq=.2;var three_module_exports={};__export(three_module_exports,{ACESFilmicToneMapping:()=>ACESFilmicToneMapping,AddEquation:()=>AddEquation,AddOperation:()=>AddOperation,AdditiveAnimationBlendMode:()=>AdditiveAnimationBlendMode,AdditiveBlending:()=>AdditiveBlending,AlphaFormat:()=>AlphaFormat,AlwaysDepth:()=>AlwaysDepth,AlwaysStencilFunc:()=>AlwaysStencilFunc,AmbientLight:()=>AmbientLight,AmbientLightProbe:()=>AmbientLightProbe,AnimationClip:()=>AnimationClip,AnimationLoader:()=>AnimationLoader,AnimationMixer:()=>AnimationMixer,AnimationObjectGroup:()=>AnimationObjectGroup,AnimationUtils:()=>AnimationUtils,ArcCurve:()=>ArcCurve,ArrayCamera:()=>ArrayCamera,ArrowHelper:()=>ArrowHelper,Audio:()=>Audio,AudioAnalyser:()=>AudioAnalyser,AudioContext:()=>AudioContext,AudioListener:()=>AudioListener,AudioLoader:()=>AudioLoader,AxesHelper:()=>AxesHelper,BackSide:()=>BackSide,BasicDepthPacking:()=>BasicDepthPacking,BasicShadowMap:()=>BasicShadowMap,Bone:()=>Bone,BooleanKeyframeTrack:()=>BooleanKeyframeTrack,Box2:()=>Box2,Box3:()=>Box3,Box3Helper:()=>Box3Helper,BoxBufferGeometry:()=>BoxGeometry,BoxGeometry:()=>BoxGeometry,BoxHelper:()=>BoxHelper,BufferAttribute:()=>BufferAttribute,BufferGeometry:()=>BufferGeometry,BufferGeometryLoader:()=>BufferGeometryLoader,ByteType:()=>ByteType,Cache:()=>Cache,Camera:()=>Camera,CameraHelper:()=>CameraHelper,CanvasTexture:()=>CanvasTexture,CapsuleBufferGeometry:()=>CapsuleGeometry,CapsuleGeometry:()=>CapsuleGeometry,CatmullRomCurve3:()=>CatmullRomCurve3,CineonToneMapping:()=>CineonToneMapping,CircleBufferGeometry:()=>CircleGeometry,CircleGeometry:()=>CircleGeometry,ClampToEdgeWrapping:()=>ClampToEdgeWrapping,Clock:()=>Clock,Color:()=>Color,ColorKeyframeTrack:()=>ColorKeyframeTrack,ColorManagement:()=>ColorManagement,CompressedTexture:()=>CompressedTexture,CompressedTextureLoader:()=>CompressedTextureLoader,ConeBufferGeometry:()=>ConeGeometry,ConeGeometry:()=>ConeGeometry,CubeCamera:()=>CubeCamera,CubeReflectionMapping:()=>CubeReflectionMapping,CubeRefractionMapping:()=>CubeRefractionMapping,CubeTexture:()=>CubeTexture,CubeTextureLoader:()=>CubeTextureLoader,CubeUVReflectionMapping:()=>CubeUVReflectionMapping,CubicBezierCurve:()=>CubicBezierCurve,CubicBezierCurve3:()=>CubicBezierCurve3,CubicInterpolant:()=>CubicInterpolant,CullFaceBack:()=>CullFaceBack,CullFaceFront:()=>CullFaceFront,CullFaceFrontBack:()=>CullFaceFrontBack,CullFaceNone:()=>CullFaceNone,Curve:()=>Curve,CurvePath:()=>CurvePath,CustomBlending:()=>CustomBlending,CustomToneMapping:()=>CustomToneMapping,CylinderBufferGeometry:()=>CylinderGeometry,CylinderGeometry:()=>CylinderGeometry,Cylindrical:()=>Cylindrical,Data3DTexture:()=>Data3DTexture,DataArrayTexture:()=>DataArrayTexture,DataTexture:()=>DataTexture,DataTexture2DArray:()=>DataTexture2DArray,DataTexture3D:()=>DataTexture3D,DataTextureLoader:()=>DataTextureLoader,DataUtils:()=>DataUtils,DecrementStencilOp:()=>DecrementStencilOp,DecrementWrapStencilOp:()=>DecrementWrapStencilOp,DefaultLoadingManager:()=>DefaultLoadingManager,DepthFormat:()=>DepthFormat,DepthStencilFormat:()=>DepthStencilFormat,DepthTexture:()=>DepthTexture,DirectionalLight:()=>DirectionalLight,DirectionalLightHelper:()=>DirectionalLightHelper,DiscreteInterpolant:()=>DiscreteInterpolant,DodecahedronBufferGeometry:()=>DodecahedronGeometry,DodecahedronGeometry:()=>DodecahedronGeometry,DoubleSide:()=>DoubleSide,DstAlphaFactor:()=>DstAlphaFactor,DstColorFactor:()=>DstColorFactor,DynamicCopyUsage:()=>DynamicCopyUsage,DynamicDrawUsage:()=>DynamicDrawUsage,DynamicReadUsage:()=>DynamicReadUsage,EdgesGeometry:()=>EdgesGeometry,EllipseCurve:()=>EllipseCurve,EqualDepth:()=>EqualDepth,EqualStencilFunc:()=>EqualStencilFunc,EquirectangularReflectionMapping:()=>EquirectangularReflectionMapping,EquirectangularRefractionMapping:()=>EquirectangularRefractionMapping,Euler:()=>Euler,EventDispatcher:()=>EventDispatcher2,ExtrudeBufferGeometry:()=>ExtrudeGeometry,ExtrudeGeometry:()=>ExtrudeGeometry,FileLoader:()=>FileLoader,FlatShading:()=>FlatShading,Float16BufferAttribute:()=>Float16BufferAttribute,Float32BufferAttribute:()=>Float32BufferAttribute,Float64BufferAttribute:()=>Float64BufferAttribute,FloatType:()=>FloatType,Fog:()=>Fog,FogExp2:()=>FogExp2,Font:()=>Font,FontLoader:()=>FontLoader,FramebufferTexture:()=>FramebufferTexture,FrontSide:()=>FrontSide,Frustum:()=>Frustum,GLBufferAttribute:()=>GLBufferAttribute,GLSL1:()=>GLSL1,GLSL3:()=>GLSL3,GreaterDepth:()=>GreaterDepth,GreaterEqualDepth:()=>GreaterEqualDepth,GreaterEqualStencilFunc:()=>GreaterEqualStencilFunc,GreaterStencilFunc:()=>GreaterStencilFunc,GridHelper:()=>GridHelper,Group:()=>Group,HalfFloatType:()=>HalfFloatType,HemisphereLight:()=>HemisphereLight,HemisphereLightHelper:()=>HemisphereLightHelper,HemisphereLightProbe:()=>HemisphereLightProbe,IcosahedronBufferGeometry:()=>IcosahedronGeometry,IcosahedronGeometry:()=>IcosahedronGeometry,ImageBitmapLoader:()=>ImageBitmapLoader,ImageLoader:()=>ImageLoader,ImageUtils:()=>ImageUtils,ImmediateRenderObject:()=>ImmediateRenderObject,IncrementStencilOp:()=>IncrementStencilOp,IncrementWrapStencilOp:()=>IncrementWrapStencilOp,InstancedBufferAttribute:()=>InstancedBufferAttribute,InstancedBufferGeometry:()=>InstancedBufferGeometry,InstancedInterleavedBuffer:()=>InstancedInterleavedBuffer,InstancedMesh:()=>InstancedMesh,Int16BufferAttribute:()=>Int16BufferAttribute,Int32BufferAttribute:()=>Int32BufferAttribute,Int8BufferAttribute:()=>Int8BufferAttribute,IntType:()=>IntType,InterleavedBuffer:()=>InterleavedBuffer,InterleavedBufferAttribute:()=>InterleavedBufferAttribute,Interpolant:()=>Interpolant,InterpolateDiscrete:()=>InterpolateDiscrete,InterpolateLinear:()=>InterpolateLinear,InterpolateSmooth:()=>InterpolateSmooth,InvertStencilOp:()=>InvertStencilOp,KeepStencilOp:()=>KeepStencilOp,KeyframeTrack:()=>KeyframeTrack,LOD:()=>LOD,LatheBufferGeometry:()=>LatheGeometry,LatheGeometry:()=>LatheGeometry,Layers:()=>Layers,LessDepth:()=>LessDepth,LessEqualDepth:()=>LessEqualDepth,LessEqualStencilFunc:()=>LessEqualStencilFunc,LessStencilFunc:()=>LessStencilFunc,Light:()=>Light,LightProbe:()=>LightProbe,Line:()=>Line,Line3:()=>Line3,LineBasicMaterial:()=>LineBasicMaterial,LineCurve:()=>LineCurve,LineCurve3:()=>LineCurve3,LineDashedMaterial:()=>LineDashedMaterial,LineLoop:()=>LineLoop,LineSegments:()=>LineSegments,LinearEncoding:()=>LinearEncoding,LinearFilter:()=>LinearFilter,LinearInterpolant:()=>LinearInterpolant,LinearMipMapLinearFilter:()=>LinearMipMapLinearFilter,LinearMipMapNearestFilter:()=>LinearMipMapNearestFilter,LinearMipmapLinearFilter:()=>LinearMipmapLinearFilter,LinearMipmapNearestFilter:()=>LinearMipmapNearestFilter,LinearSRGBColorSpace:()=>LinearSRGBColorSpace,LinearToneMapping:()=>LinearToneMapping,Loader:()=>Loader,LoaderUtils:()=>LoaderUtils,LoadingManager:()=>LoadingManager,LoopOnce:()=>LoopOnce,LoopPingPong:()=>LoopPingPong,LoopRepeat:()=>LoopRepeat,LuminanceAlphaFormat:()=>LuminanceAlphaFormat,LuminanceFormat:()=>LuminanceFormat,MOUSE:()=>MOUSE,Material:()=>Material,MaterialLoader:()=>MaterialLoader,MathUtils:()=>MathUtils,Matrix3:()=>Matrix3,Matrix4:()=>Matrix4,MaxEquation:()=>MaxEquation,Mesh:()=>Mesh,MeshBasicMaterial:()=>MeshBasicMaterial,MeshDepthMaterial:()=>MeshDepthMaterial,MeshDistanceMaterial:()=>MeshDistanceMaterial,MeshLambertMaterial:()=>MeshLambertMaterial,MeshMatcapMaterial:()=>MeshMatcapMaterial,MeshNormalMaterial:()=>MeshNormalMaterial,MeshPhongMaterial:()=>MeshPhongMaterial,MeshPhysicalMaterial:()=>MeshPhysicalMaterial,MeshStandardMaterial:()=>MeshStandardMaterial,MeshToonMaterial:()=>MeshToonMaterial,MinEquation:()=>MinEquation,MirroredRepeatWrapping:()=>MirroredRepeatWrapping,MixOperation:()=>MixOperation,MultiplyBlending:()=>MultiplyBlending,MultiplyOperation:()=>MultiplyOperation,NearestFilter:()=>NearestFilter,NearestMipMapLinearFilter:()=>NearestMipMapLinearFilter,NearestMipMapNearestFilter:()=>NearestMipMapNearestFilter,NearestMipmapLinearFilter:()=>NearestMipmapLinearFilter,NearestMipmapNearestFilter:()=>NearestMipmapNearestFilter,NeverDepth:()=>NeverDepth,NeverStencilFunc:()=>NeverStencilFunc,NoBlending:()=>NoBlending,NoColorSpace:()=>NoColorSpace,NoToneMapping:()=>NoToneMapping,NormalAnimationBlendMode:()=>NormalAnimationBlendMode,NormalBlending:()=>NormalBlending,NotEqualDepth:()=>NotEqualDepth,NotEqualStencilFunc:()=>NotEqualStencilFunc,NumberKeyframeTrack:()=>NumberKeyframeTrack,Object3D:()=>Object3D,ObjectLoader:()=>ObjectLoader,ObjectSpaceNormalMap:()=>ObjectSpaceNormalMap,OctahedronBufferGeometry:()=>OctahedronGeometry,OctahedronGeometry:()=>OctahedronGeometry,OneFactor:()=>OneFactor,OneMinusDstAlphaFactor:()=>OneMinusDstAlphaFactor,OneMinusDstColorFactor:()=>OneMinusDstColorFactor,OneMinusSrcAlphaFactor:()=>OneMinusSrcAlphaFactor,OneMinusSrcColorFactor:()=>OneMinusSrcColorFactor,OrthographicCamera:()=>OrthographicCamera,PCFShadowMap:()=>PCFShadowMap,PCFSoftShadowMap:()=>PCFSoftShadowMap,PMREMGenerator:()=>PMREMGenerator,ParametricGeometry:()=>ParametricGeometry,Path:()=>Path,PerspectiveCamera:()=>PerspectiveCamera,Plane:()=>Plane,PlaneBufferGeometry:()=>PlaneGeometry,PlaneGeometry:()=>PlaneGeometry,PlaneHelper:()=>PlaneHelper,PointLight:()=>PointLight,PointLightHelper:()=>PointLightHelper,Points:()=>Points,PointsMaterial:()=>PointsMaterial,PolarGridHelper:()=>PolarGridHelper,PolyhedronBufferGeometry:()=>PolyhedronGeometry,PolyhedronGeometry:()=>PolyhedronGeometry,PositionalAudio:()=>PositionalAudio,PropertyBinding:()=>PropertyBinding,PropertyMixer:()=>PropertyMixer,QuadraticBezierCurve:()=>QuadraticBezierCurve,QuadraticBezierCurve3:()=>QuadraticBezierCurve3,Quaternion:()=>Quaternion,QuaternionKeyframeTrack:()=>QuaternionKeyframeTrack,QuaternionLinearInterpolant:()=>QuaternionLinearInterpolant,REVISION:()=>REVISION,RGBADepthPacking:()=>RGBADepthPacking,RGBAFormat:()=>RGBAFormat,RGBAIntegerFormat:()=>RGBAIntegerFormat,RGBA_ASTC_10x10_Format:()=>RGBA_ASTC_10x10_Format,RGBA_ASTC_10x5_Format:()=>RGBA_ASTC_10x5_Format,RGBA_ASTC_10x6_Format:()=>RGBA_ASTC_10x6_Format,RGBA_ASTC_10x8_Format:()=>RGBA_ASTC_10x8_Format,RGBA_ASTC_12x10_Format:()=>RGBA_ASTC_12x10_Format,RGBA_ASTC_12x12_Format:()=>RGBA_ASTC_12x12_Format,RGBA_ASTC_4x4_Format:()=>RGBA_ASTC_4x4_Format,RGBA_ASTC_5x4_Format:()=>RGBA_ASTC_5x4_Format,RGBA_ASTC_5x5_Format:()=>RGBA_ASTC_5x5_Format,RGBA_ASTC_6x5_Format:()=>RGBA_ASTC_6x5_Format,RGBA_ASTC_6x6_Format:()=>RGBA_ASTC_6x6_Format,RGBA_ASTC_8x5_Format:()=>RGBA_ASTC_8x5_Format,RGBA_ASTC_8x6_Format:()=>RGBA_ASTC_8x6_Format,RGBA_ASTC_8x8_Format:()=>RGBA_ASTC_8x8_Format,RGBA_BPTC_Format:()=>RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:()=>RGBA_ETC2_EAC_Format,RGBA_PVRTC_2BPPV1_Format:()=>RGBA_PVRTC_2BPPV1_Format,RGBA_PVRTC_4BPPV1_Format:()=>RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:()=>RGBA_S3TC_DXT1_Format,RGBA_S3TC_DXT3_Format:()=>RGBA_S3TC_DXT3_Format,RGBA_S3TC_DXT5_Format:()=>RGBA_S3TC_DXT5_Format,RGBFormat:()=>RGBFormat,RGB_ETC1_Format:()=>RGB_ETC1_Format,RGB_ETC2_Format:()=>RGB_ETC2_Format,RGB_PVRTC_2BPPV1_Format:()=>RGB_PVRTC_2BPPV1_Format,RGB_PVRTC_4BPPV1_Format:()=>RGB_PVRTC_4BPPV1_Format,RGB_S3TC_DXT1_Format:()=>RGB_S3TC_DXT1_Format,RGFormat:()=>RGFormat,RGIntegerFormat:()=>RGIntegerFormat,RawShaderMaterial:()=>RawShaderMaterial,Ray:()=>Ray,Raycaster:()=>Raycaster,RectAreaLight:()=>RectAreaLight,RedFormat:()=>RedFormat,RedIntegerFormat:()=>RedIntegerFormat,ReinhardToneMapping:()=>ReinhardToneMapping,RepeatWrapping:()=>RepeatWrapping,ReplaceStencilOp:()=>ReplaceStencilOp,ReverseSubtractEquation:()=>ReverseSubtractEquation,RingBufferGeometry:()=>RingGeometry,RingGeometry:()=>RingGeometry,SRGBColorSpace:()=>SRGBColorSpace,Scene:()=>Scene,ShaderChunk:()=>ShaderChunk,ShaderLib:()=>ShaderLib,ShaderMaterial:()=>ShaderMaterial,ShadowMaterial:()=>ShadowMaterial,Shape:()=>Shape,ShapeBufferGeometry:()=>ShapeGeometry,ShapeGeometry:()=>ShapeGeometry,ShapePath:()=>ShapePath,ShapeUtils:()=>ShapeUtils,ShortType:()=>ShortType,Skeleton:()=>Skeleton,SkeletonHelper:()=>SkeletonHelper,SkinnedMesh:()=>SkinnedMesh,SmoothShading:()=>SmoothShading,Source:()=>Source,Sphere:()=>Sphere,SphereBufferGeometry:()=>SphereGeometry,SphereGeometry:()=>SphereGeometry,Spherical:()=>Spherical,SphericalHarmonics3:()=>SphericalHarmonics3,SplineCurve:()=>SplineCurve,SpotLight:()=>SpotLight,SpotLightHelper:()=>SpotLightHelper,Sprite:()=>Sprite,SpriteMaterial:()=>SpriteMaterial,SrcAlphaFactor:()=>SrcAlphaFactor,SrcAlphaSaturateFactor:()=>SrcAlphaSaturateFactor,SrcColorFactor:()=>SrcColorFactor,StaticCopyUsage:()=>StaticCopyUsage,StaticDrawUsage:()=>StaticDrawUsage,StaticReadUsage:()=>StaticReadUsage,StereoCamera:()=>StereoCamera,StreamCopyUsage:()=>StreamCopyUsage,StreamDrawUsage:()=>StreamDrawUsage,StreamReadUsage:()=>StreamReadUsage,StringKeyframeTrack:()=>StringKeyframeTrack,SubtractEquation:()=>SubtractEquation,SubtractiveBlending:()=>SubtractiveBlending,TOUCH:()=>TOUCH,TangentSpaceNormalMap:()=>TangentSpaceNormalMap,TetrahedronBufferGeometry:()=>TetrahedronGeometry,TetrahedronGeometry:()=>TetrahedronGeometry,TextGeometry:()=>TextGeometry,Texture:()=>Texture,TextureLoader:()=>TextureLoader,TorusBufferGeometry:()=>TorusGeometry,TorusGeometry:()=>TorusGeometry,TorusKnotBufferGeometry:()=>TorusKnotGeometry,TorusKnotGeometry:()=>TorusKnotGeometry,Triangle:()=>Triangle,TriangleFanDrawMode:()=>TriangleFanDrawMode,TriangleStripDrawMode:()=>TriangleStripDrawMode,TrianglesDrawMode:()=>TrianglesDrawMode,TubeBufferGeometry:()=>TubeGeometry,TubeGeometry:()=>TubeGeometry,UVMapping:()=>UVMapping,Uint16BufferAttribute:()=>Uint16BufferAttribute,Uint32BufferAttribute:()=>Uint32BufferAttribute,Uint8BufferAttribute:()=>Uint8BufferAttribute,Uint8ClampedBufferAttribute:()=>Uint8ClampedBufferAttribute,Uniform:()=>Uniform,UniformsGroup:()=>UniformsGroup,UniformsLib:()=>UniformsLib,UniformsUtils:()=>UniformsUtils,UnsignedByteType:()=>UnsignedByteType,UnsignedInt248Type:()=>UnsignedInt248Type,UnsignedIntType:()=>UnsignedIntType,UnsignedShort4444Type:()=>UnsignedShort4444Type,UnsignedShort5551Type:()=>UnsignedShort5551Type,UnsignedShortType:()=>UnsignedShortType,VSMShadowMap:()=>VSMShadowMap,Vector2:()=>Vector2,Vector3:()=>Vector3,Vector4:()=>Vector4,VectorKeyframeTrack:()=>VectorKeyframeTrack,VideoTexture:()=>VideoTexture,WebGL1Renderer:()=>WebGL1Renderer,WebGL3DRenderTarget:()=>WebGL3DRenderTarget,WebGLArrayRenderTarget:()=>WebGLArrayRenderTarget,WebGLCubeRenderTarget:()=>WebGLCubeRenderTarget,WebGLMultipleRenderTargets:()=>WebGLMultipleRenderTargets,WebGLMultisampleRenderTarget:()=>WebGLMultisampleRenderTarget,WebGLRenderTarget:()=>WebGLRenderTarget,WebGLRenderer:()=>WebGLRenderer,WebGLUtils:()=>WebGLUtils,WireframeGeometry:()=>WireframeGeometry,WrapAroundEnding:()=>WrapAroundEnding,ZeroCurvatureEnding:()=>ZeroCurvatureEnding,ZeroFactor:()=>ZeroFactor,ZeroSlopeEnding:()=>ZeroSlopeEnding,ZeroStencilOp:()=>ZeroStencilOp,_SRGBAFormat:()=>_SRGBAFormat,sRGBEncoding:()=>sRGBEncoding});var REVISION="143";var MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2};var TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3};var CullFaceNone=0;var CullFaceBack=1;var CullFaceFront=2;var CullFaceFrontBack=3;var BasicShadowMap=0;var PCFShadowMap=1;var PCFSoftShadowMap=2;var VSMShadowMap=3;var FrontSide=0;var BackSide=1;var DoubleSide=2;var FlatShading=1;var SmoothShading=2;var NoBlending=0;var NormalBlending=1;var AdditiveBlending=2;var SubtractiveBlending=3;var MultiplyBlending=4;var CustomBlending=5;var AddEquation=100;var SubtractEquation=101;var ReverseSubtractEquation=102;var MinEquation=103;var MaxEquation=104;var ZeroFactor=200;var OneFactor=201;var SrcColorFactor=202;var OneMinusSrcColorFactor=203;var SrcAlphaFactor=204;var OneMinusSrcAlphaFactor=205;var DstAlphaFactor=206;var OneMinusDstAlphaFactor=207;var DstColorFactor=208;var OneMinusDstColorFactor=209;var SrcAlphaSaturateFactor=210;var NeverDepth=0;var AlwaysDepth=1;var LessDepth=2;var LessEqualDepth=3;var EqualDepth=4;var GreaterEqualDepth=5;var GreaterDepth=6;var NotEqualDepth=7;var MultiplyOperation=0;var MixOperation=1;var AddOperation=2;var NoToneMapping=0;var LinearToneMapping=1;var ReinhardToneMapping=2;var CineonToneMapping=3;var ACESFilmicToneMapping=4;var CustomToneMapping=5;var UVMapping=300;var CubeReflectionMapping=301;var CubeRefractionMapping=302;var EquirectangularReflectionMapping=303;var EquirectangularRefractionMapping=304;var CubeUVReflectionMapping=306;var RepeatWrapping=1e3;var ClampToEdgeWrapping=1001;var MirroredRepeatWrapping=1002;var NearestFilter=1003;var NearestMipmapNearestFilter=1004;var NearestMipMapNearestFilter=1004;var NearestMipmapLinearFilter=1005;var NearestMipMapLinearFilter=1005;var LinearFilter=1006;var LinearMipmapNearestFilter=1007;var LinearMipMapNearestFilter=1007;var LinearMipmapLinearFilter=1008;var LinearMipMapLinearFilter=1008;var UnsignedByteType=1009;var ByteType=1010;var ShortType=1011;var UnsignedShortType=1012;var IntType=1013;var UnsignedIntType=1014;var FloatType=1015;var HalfFloatType=1016;var UnsignedShort4444Type=1017;var UnsignedShort5551Type=1018;var UnsignedInt248Type=1020;var AlphaFormat=1021;var RGBFormat=1022;var RGBAFormat=1023;var LuminanceFormat=1024;var LuminanceAlphaFormat=1025;var DepthFormat=1026;var DepthStencilFormat=1027;var RedFormat=1028;var RedIntegerFormat=1029;var RGFormat=1030;var RGIntegerFormat=1031;var RGBAIntegerFormat=1033;var RGB_S3TC_DXT1_Format=33776;var RGBA_S3TC_DXT1_Format=33777;var RGBA_S3TC_DXT3_Format=33778;var RGBA_S3TC_DXT5_Format=33779;var RGB_PVRTC_4BPPV1_Format=35840;var RGB_PVRTC_2BPPV1_Format=35841;var RGBA_PVRTC_4BPPV1_Format=35842;var RGBA_PVRTC_2BPPV1_Format=35843;var RGB_ETC1_Format=36196;var RGB_ETC2_Format=37492;var RGBA_ETC2_EAC_Format=37496;var RGBA_ASTC_4x4_Format=37808;var RGBA_ASTC_5x4_Format=37809;var RGBA_ASTC_5x5_Format=37810;var RGBA_ASTC_6x5_Format=37811;var RGBA_ASTC_6x6_Format=37812;var RGBA_ASTC_8x5_Format=37813;var RGBA_ASTC_8x6_Format=37814;var RGBA_ASTC_8x8_Format=37815;var RGBA_ASTC_10x5_Format=37816;var RGBA_ASTC_10x6_Format=37817;var RGBA_ASTC_10x8_Format=37818;var RGBA_ASTC_10x10_Format=37819;var RGBA_ASTC_12x10_Format=37820;var RGBA_ASTC_12x12_Format=37821;var RGBA_BPTC_Format=36492;var LoopOnce=2200;var LoopRepeat=2201;var LoopPingPong=2202;var InterpolateDiscrete=2300;var InterpolateLinear=2301;var InterpolateSmooth=2302;var ZeroCurvatureEnding=2400;var ZeroSlopeEnding=2401;var WrapAroundEnding=2402;var NormalAnimationBlendMode=2500;var AdditiveAnimationBlendMode=2501;var TrianglesDrawMode=0;var TriangleStripDrawMode=1;var TriangleFanDrawMode=2;var LinearEncoding=3e3;var sRGBEncoding=3001;var BasicDepthPacking=3200;var RGBADepthPacking=3201;var TangentSpaceNormalMap=0;var ObjectSpaceNormalMap=1;var NoColorSpace="";var SRGBColorSpace="srgb";var LinearSRGBColorSpace="srgb-linear";var ZeroStencilOp=0;var KeepStencilOp=7680;var ReplaceStencilOp=7681;var IncrementStencilOp=7682;var DecrementStencilOp=7683;var IncrementWrapStencilOp=34055;var DecrementWrapStencilOp=34056;var InvertStencilOp=5386;var NeverStencilFunc=512;var LessStencilFunc=513;var EqualStencilFunc=514;var LessEqualStencilFunc=515;var GreaterStencilFunc=516;var NotEqualStencilFunc=517;var GreaterEqualStencilFunc=518;var AlwaysStencilFunc=519;var StaticDrawUsage=35044;var DynamicDrawUsage=35048;var StreamDrawUsage=35040;var StaticReadUsage=35045;var DynamicReadUsage=35049;var StreamReadUsage=35041;var StaticCopyUsage=35046;var DynamicCopyUsage=35050;var StreamCopyUsage=35042;var GLSL1="100";var GLSL3="300 es";var _SRGBAFormat=1035;var EventDispatcher2=class{addEventListener(type,listener){if(this._listeners===void 0)this._listeners={};const listeners2=this._listeners;if(listeners2[type]===void 0){listeners2[type]=[]}if(listeners2[type].indexOf(listener)===-1){listeners2[type].push(listener)}}hasEventListener(type,listener){if(this._listeners===void 0)return false;const listeners2=this._listeners;return listeners2[type]!==void 0&&listeners2[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this._listeners===void 0)return;const listeners2=this._listeners;const listenerArray=listeners2[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event){if(this._listeners===void 0)return;const listeners2=this._listeners;const listenerArray=listeners2[event.type];if(listenerArray!==void 0){event.target=this;const array=listenerArray.slice(0);for(let i=0,l=array.length;i>8&255]+_lut[d0>>16&255]+_lut[d0>>24&255]+"-"+_lut[d1&255]+_lut[d1>>8&255]+"-"+_lut[d1>>16&15|64]+_lut[d1>>24&255]+"-"+_lut[d2&63|128]+_lut[d2>>8&255]+"-"+_lut[d2>>16&255]+_lut[d2>>24&255]+_lut[d3&255]+_lut[d3>>8&255]+_lut[d3>>16&255]+_lut[d3>>24&255];return uuid.toLowerCase()}function clamp(value,min,max){return Math.max(min,Math.min(max,value))}function euclideanModulo(n,m){return(n%m+m)%m}function mapLinear(x2,a1,a2,b1,b2){return b1+(x2-a1)*(b2-b1)/(a2-a1)}function inverseLerp(x2,y2,value){if(x2!==y2){return(value-x2)/(y2-x2)}else{return 0}}function lerp(x2,y2,t){return(1-t)*x2+t*y2}function damp(x2,y2,lambda,dt){return lerp(x2,y2,1-Math.exp(-lambda*dt))}function pingpong(x2,length=1){return length-Math.abs(euclideanModulo(x2,length*2)-length)}function smoothstep(x2,min,max){if(x2<=min)return 0;if(x2>=max)return 1;x2=(x2-min)/(max-min);return x2*x2*(3-2*x2)}function smootherstep(x2,min,max){if(x2<=min)return 0;if(x2>=max)return 1;x2=(x2-min)/(max-min);return x2*x2*x2*(x2*(x2*6-15)+10)}function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1))}function randFloat(low,high){return low+Math.random()*(high-low)}function randFloatSpread(range){return range*(.5-Math.random())}function seededRandom(s){if(s!==void 0)_seed=s;let t=_seed+=1831565813;t=Math.imul(t^t>>>15,t|1);t^=t+Math.imul(t^t>>>7,t|61);return((t^t>>>14)>>>0)/4294967296}function degToRad(degrees){return degrees*DEG2RAD}function radToDeg(radians){return radians*RAD2DEG}function isPowerOfTwo(value){return(value&value-1)===0&&value!==0}function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2))}function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2))}function setQuaternionFromProperEuler(q,a,b,c,order){const cos=Math.cos;const sin=Math.sin;const c2=cos(b/2);const s2=sin(b/2);const c13=cos((a+c)/2);const s13=sin((a+c)/2);const c1_3=cos((a-c)/2);const s1_3=sin((a-c)/2);const c3_1=cos((c-a)/2);const s3_1=sin((c-a)/2);switch(order){case"XYX":q.set(c2*s13,s2*c1_3,s2*s1_3,c2*c13);break;case"YZY":q.set(s2*s1_3,c2*s13,s2*c1_3,c2*c13);break;case"ZXZ":q.set(s2*c1_3,s2*s1_3,c2*s13,c2*c13);break;case"XZX":q.set(c2*s13,s2*s3_1,s2*c3_1,c2*c13);break;case"YXY":q.set(s2*c3_1,c2*s13,s2*s3_1,c2*c13);break;case"ZYZ":q.set(s2*s3_1,s2*c3_1,c2*s13,c2*c13);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+order)}}function denormalize$1(value,array){switch(array.constructor){case Float32Array:return value;case Uint16Array:return value/65535;case Uint8Array:return value/255;case Int16Array:return Math.max(value/32767,-1);case Int8Array:return Math.max(value/127,-1);default:throw new Error("Invalid component type.")}}function normalize(value,array){switch(array.constructor){case Float32Array:return value;case Uint16Array:return Math.round(value*65535);case Uint8Array:return Math.round(value*255);case Int16Array:return Math.round(value*32767);case Int8Array:return Math.round(value*127);default:throw new Error("Invalid component type.")}}var MathUtils=Object.freeze({__proto__:null,DEG2RAD,RAD2DEG,generateUUID,clamp,euclideanModulo,mapLinear,inverseLerp,lerp,damp,pingpong,smoothstep,smootherstep,randInt,randFloat,randFloatSpread,seededRandom,degToRad,radToDeg,isPowerOfTwo,ceilPowerOfTwo,floorPowerOfTwo,setQuaternionFromProperEuler,normalize,denormalize:denormalize$1});var Vector2=class{constructor(x2=0,y2=0){Vector2.prototype.isVector2=true;this.x=x2;this.y=y2}get width(){return this.x}set width(value){this.x=value}get height(){return this.y}set height(value){this.y=value}set(x2,y2){this.x=x2;this.y=y2;return this}setScalar(scalar){this.x=scalar;this.y=scalar;return this}setX(x2){this.x=x2;return this}setY(y2){this.y=y2;return this}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;default:throw new Error("index is out of range: "+index)}return this}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+index)}}clone(){return new this.constructor(this.x,this.y)}copy(v){this.x=v.x;this.y=v.y;return this}add(v){this.x+=v.x;this.y+=v.y;return this}addScalar(s){this.x+=s;this.y+=s;return this}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this}sub(v){this.x-=v.x;this.y-=v.y;return this}subScalar(s){this.x-=s;this.y-=s;return this}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this}multiply(v){this.x*=v.x;this.y*=v.y;return this}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this}divide(v){this.x/=v.x;this.y/=v.y;return this}divideScalar(scalar){return this.multiplyScalar(1/scalar)}applyMatrix3(m){const x2=this.x,y2=this.y;const e=m.elements;this.x=e[0]*x2+e[3]*y2+e[6];this.y=e[1]*x2+e[4]*y2+e[7];return this}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this}clamp(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));return this}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));return this}clampLength(min,max){const length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);return this}negate(){this.x=-this.x;this.y=-this.y;return this}dot(v){return this.x*v.x+this.y*v.y}cross(v){return this.x*v.y-this.y*v.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){const angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle}distanceTo(v){return Math.sqrt(this.distanceToSquared(v))}distanceToSquared(v){const dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)}setLength(length){return this.normalize().multiplyScalar(length)}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;return this}equals(v){return v.x===this.x&&v.y===this.y}fromArray(array,offset=0){this.x=array[offset];this.y=array[offset+1];return this}toArray(array=[],offset=0){array[offset]=this.x;array[offset+1]=this.y;return array}fromBufferAttribute(attribute,index){this.x=attribute.getX(index);this.y=attribute.getY(index);return this}rotateAround(center,angle){const c=Math.cos(angle),s=Math.sin(angle);const x2=this.x-center.x;const y2=this.y-center.y;this.x=x2*c-y2*s+center.x;this.y=x2*s+y2*c+center.y;return this}random(){this.x=Math.random();this.y=Math.random();return this}*[Symbol.iterator](){yield this.x;yield this.y}};var Matrix3=class{constructor(){Matrix3.prototype.isMatrix3=true;this.elements=[1,0,0,0,1,0,0,0,1]}set(n11,n12,n13,n21,n22,n23,n31,n32,n33){const te=this.elements;te[0]=n11;te[1]=n21;te[2]=n31;te[3]=n12;te[4]=n22;te[5]=n32;te[6]=n13;te[7]=n23;te[8]=n33;return this}identity(){this.set(1,0,0,0,1,0,0,0,1);return this}copy(m){const te=this.elements;const me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];return this}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this}setFromMatrix4(m){const me=m.elements;this.set(me[0],me[4],me[8],me[1],me[5],me[9],me[2],me[6],me[10]);return this}multiply(m){return this.multiplyMatrices(this,m)}premultiply(m){return this.multiplyMatrices(m,this)}multiplyMatrices(a,b){const ae=a.elements;const be=b.elements;const te=this.elements;const a11=ae[0],a12=ae[3],a13=ae[6];const a21=ae[1],a22=ae[4],a23=ae[7];const a31=ae[2],a32=ae[5],a33=ae[8];const b11=be[0],b12=be[3],b13=be[6];const b21=be[1],b22=be[4],b23=be[7];const b31=be[2],b32=be[5],b33=be[8];te[0]=a11*b11+a12*b21+a13*b31;te[3]=a11*b12+a12*b22+a13*b32;te[6]=a11*b13+a12*b23+a13*b33;te[1]=a21*b11+a22*b21+a23*b31;te[4]=a21*b12+a22*b22+a23*b32;te[7]=a21*b13+a22*b23+a23*b33;te[2]=a31*b11+a32*b21+a33*b31;te[5]=a31*b12+a32*b22+a33*b32;te[8]=a31*b13+a32*b23+a33*b33;return this}multiplyScalar(s){const te=this.elements;te[0]*=s;te[3]*=s;te[6]*=s;te[1]*=s;te[4]*=s;te[7]*=s;te[2]*=s;te[5]*=s;te[8]*=s;return this}determinant(){const te=this.elements;const a=te[0],b=te[1],c=te[2],d=te[3],e=te[4],f=te[5],g=te[6],h=te[7],i=te[8];return a*e*i-a*f*h-b*d*i+b*f*g+c*d*h-c*e*g}invert(){const te=this.elements,n11=te[0],n21=te[1],n31=te[2],n12=te[3],n22=te[4],n32=te[5],n13=te[6],n23=te[7],n33=te[8],t11=n33*n22-n32*n23,t12=n32*n13-n33*n12,t13=n23*n12-n22*n13,det=n11*t11+n21*t12+n31*t13;if(det===0)return this.set(0,0,0,0,0,0,0,0,0);const detInv=1/det;te[0]=t11*detInv;te[1]=(n31*n23-n33*n21)*detInv;te[2]=(n32*n21-n31*n22)*detInv;te[3]=t12*detInv;te[4]=(n33*n11-n31*n13)*detInv;te[5]=(n31*n12-n32*n11)*detInv;te[6]=t13*detInv;te[7]=(n21*n13-n23*n11)*detInv;te[8]=(n22*n11-n21*n12)*detInv;return this}transpose(){let tmp2;const m=this.elements;tmp2=m[1];m[1]=m[3];m[3]=tmp2;tmp2=m[2];m[2]=m[6];m[6]=tmp2;tmp2=m[5];m[5]=m[7];m[7]=tmp2;return this}getNormalMatrix(matrix4){return this.setFromMatrix4(matrix4).invert().transpose()}transposeIntoArray(r){const m=this.elements;r[0]=m[0];r[1]=m[3];r[2]=m[6];r[3]=m[1];r[4]=m[4];r[5]=m[7];r[6]=m[2];r[7]=m[5];r[8]=m[8];return this}setUvTransform(tx,ty,sx,sy,rotation,cx,cy){const c=Math.cos(rotation);const s=Math.sin(rotation);this.set(sx*c,sx*s,-sx*(c*cx+s*cy)+cx+tx,-sy*s,sy*c,-sy*(-s*cx+c*cy)+cy+ty,0,0,1);return this}scale(sx,sy){const te=this.elements;te[0]*=sx;te[3]*=sx;te[6]*=sx;te[1]*=sy;te[4]*=sy;te[7]*=sy;return this}rotate(theta){const c=Math.cos(theta);const s=Math.sin(theta);const te=this.elements;const a11=te[0],a12=te[3],a13=te[6];const a21=te[1],a22=te[4],a23=te[7];te[0]=c*a11+s*a21;te[3]=c*a12+s*a22;te[6]=c*a13+s*a23;te[1]=-s*a11+c*a21;te[4]=-s*a12+c*a22;te[7]=-s*a13+c*a23;return this}translate(tx,ty){const te=this.elements;te[0]+=tx*te[2];te[3]+=tx*te[5];te[6]+=tx*te[8];te[1]+=ty*te[2];te[4]+=ty*te[5];te[7]+=ty*te[8];return this}equals(matrix){const te=this.elements;const me=matrix.elements;for(let i=0;i<9;i++){if(te[i]!==me[i])return false}return true}fromArray(array,offset=0){for(let i=0;i<9;i++){this.elements[i]=array[i+offset]}return this}toArray(array=[],offset=0){const te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];return array}clone(){return new this.constructor().fromArray(this.elements)}};function arrayNeedsUint32(array){for(let i=array.length-1;i>=0;--i){if(array[i]>65535)return true}return false}var TYPED_ARRAYS={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function getTypedArray(type,buffer){return new TYPED_ARRAYS[type](buffer)}function createElementNS(name){return document.createElementNS("http://www.w3.org/1999/xhtml",name)}function SRGBToLinear(c){return c<.04045?c*.0773993808:Math.pow(c*.9478672986+.0521327014,2.4)}function LinearToSRGB(c){return c<.0031308?c*12.92:1.055*Math.pow(c,.41666)-.055}var FN={[SRGBColorSpace]:{[LinearSRGBColorSpace]:SRGBToLinear},[LinearSRGBColorSpace]:{[SRGBColorSpace]:LinearToSRGB}};var ColorManagement={legacyMode:true,get workingColorSpace(){return LinearSRGBColorSpace},set workingColorSpace(colorSpace){console.warn("THREE.ColorManagement: .workingColorSpace is readonly.")},convert:function(color,sourceColorSpace,targetColorSpace){if(this.legacyMode||sourceColorSpace===targetColorSpace||!sourceColorSpace||!targetColorSpace){return color}if(FN[sourceColorSpace]&&FN[sourceColorSpace][targetColorSpace]!==void 0){const fn=FN[sourceColorSpace][targetColorSpace];color.r=fn(color.r);color.g=fn(color.g);color.b=fn(color.b);return color}throw new Error("Unsupported color space conversion.")},fromWorkingColorSpace:function(color,targetColorSpace){return this.convert(color,this.workingColorSpace,targetColorSpace)},toWorkingColorSpace:function(color,sourceColorSpace){return this.convert(color,sourceColorSpace,this.workingColorSpace)}};var _colorKeywords={"aliceblue":15792383,"antiquewhite":16444375,"aqua":65535,"aquamarine":8388564,"azure":15794175,"beige":16119260,"bisque":16770244,"black":0,"blanchedalmond":16772045,"blue":255,"blueviolet":9055202,"brown":10824234,"burlywood":14596231,"cadetblue":6266528,"chartreuse":8388352,"chocolate":13789470,"coral":16744272,"cornflowerblue":6591981,"cornsilk":16775388,"crimson":14423100,"cyan":65535,"darkblue":139,"darkcyan":35723,"darkgoldenrod":12092939,"darkgray":11119017,"darkgreen":25600,"darkgrey":11119017,"darkkhaki":12433259,"darkmagenta":9109643,"darkolivegreen":5597999,"darkorange":16747520,"darkorchid":10040012,"darkred":9109504,"darksalmon":15308410,"darkseagreen":9419919,"darkslateblue":4734347,"darkslategray":3100495,"darkslategrey":3100495,"darkturquoise":52945,"darkviolet":9699539,"deeppink":16716947,"deepskyblue":49151,"dimgray":6908265,"dimgrey":6908265,"dodgerblue":2003199,"firebrick":11674146,"floralwhite":16775920,"forestgreen":2263842,"fuchsia":16711935,"gainsboro":14474460,"ghostwhite":16316671,"gold":16766720,"goldenrod":14329120,"gray":8421504,"green":32768,"greenyellow":11403055,"grey":8421504,"honeydew":15794160,"hotpink":16738740,"indianred":13458524,"indigo":4915330,"ivory":16777200,"khaki":15787660,"lavender":15132410,"lavenderblush":16773365,"lawngreen":8190976,"lemonchiffon":16775885,"lightblue":11393254,"lightcoral":15761536,"lightcyan":14745599,"lightgoldenrodyellow":16448210,"lightgray":13882323,"lightgreen":9498256,"lightgrey":13882323,"lightpink":16758465,"lightsalmon":16752762,"lightseagreen":2142890,"lightskyblue":8900346,"lightslategray":7833753,"lightslategrey":7833753,"lightsteelblue":11584734,"lightyellow":16777184,"lime":65280,"limegreen":3329330,"linen":16445670,"magenta":16711935,"maroon":8388608,"mediumaquamarine":6737322,"mediumblue":205,"mediumorchid":12211667,"mediumpurple":9662683,"mediumseagreen":3978097,"mediumslateblue":8087790,"mediumspringgreen":64154,"mediumturquoise":4772300,"mediumvioletred":13047173,"midnightblue":1644912,"mintcream":16121850,"mistyrose":16770273,"moccasin":16770229,"navajowhite":16768685,"navy":128,"oldlace":16643558,"olive":8421376,"olivedrab":7048739,"orange":16753920,"orangered":16729344,"orchid":14315734,"palegoldenrod":15657130,"palegreen":10025880,"paleturquoise":11529966,"palevioletred":14381203,"papayawhip":16773077,"peachpuff":16767673,"peru":13468991,"pink":16761035,"plum":14524637,"powderblue":11591910,"purple":8388736,"rebeccapurple":6697881,"red":16711680,"rosybrown":12357519,"royalblue":4286945,"saddlebrown":9127187,"salmon":16416882,"sandybrown":16032864,"seagreen":3050327,"seashell":16774638,"sienna":10506797,"silver":12632256,"skyblue":8900331,"slateblue":6970061,"slategray":7372944,"slategrey":7372944,"snow":16775930,"springgreen":65407,"steelblue":4620980,"tan":13808780,"teal":32896,"thistle":14204888,"tomato":16737095,"turquoise":4251856,"violet":15631086,"wheat":16113331,"white":16777215,"whitesmoke":16119285,"yellow":16776960,"yellowgreen":10145074};var _rgb={r:0,g:0,b:0};var _hslA={h:0,s:0,l:0};var _hslB={h:0,s:0,l:0};function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*6*(2/3-t);return p}function toComponents(source,target){target.r=source.r;target.g=source.g;target.b=source.b;return target}var Color=class{constructor(r,g,b){this.isColor=true;this.r=1;this.g=1;this.b=1;if(g===void 0&&b===void 0){return this.set(r)}return this.setRGB(r,g,b)}set(value){if(value&&value.isColor){this.copy(value)}else if(typeof value==="number"){this.setHex(value)}else if(typeof value==="string"){this.setStyle(value)}return this}setScalar(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this}setHex(hex,colorSpace=SRGBColorSpace){hex=Math.floor(hex);this.r=(hex>>16&255)/255;this.g=(hex>>8&255)/255;this.b=(hex&255)/255;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}setRGB(r,g,b,colorSpace=LinearSRGBColorSpace){this.r=r;this.g=g;this.b=b;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}setHSL(h,s,l,colorSpace=LinearSRGBColorSpace){h=euclideanModulo(h,1);s=clamp(s,0,1);l=clamp(l,0,1);if(s===0){this.r=this.g=this.b=l}else{const p=l<=.5?l*(1+s):l+s-l*s;const q=2*l-p;this.r=hue2rgb(q,p,h+1/3);this.g=hue2rgb(q,p,h);this.b=hue2rgb(q,p,h-1/3)}ColorManagement.toWorkingColorSpace(this,colorSpace);return this}setStyle(style,colorSpace=SRGBColorSpace){function handleAlpha(string){if(string===void 0)return;if(parseFloat(string)<1){console.warn("THREE.Color: Alpha component of "+style+" will be ignored.")}}let m;if(m=/^((?:rgb|hsl)a?)\\(([^\\)]*)\\)/.exec(style)){let color;const name=m[1];const components=m[2];switch(name){case"rgb":case"rgba":if(color=/^\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*(\\d*\\.?\\d+)\\s*)?$/.exec(components)){this.r=Math.min(255,parseInt(color[1],10))/255;this.g=Math.min(255,parseInt(color[2],10))/255;this.b=Math.min(255,parseInt(color[3],10))/255;ColorManagement.toWorkingColorSpace(this,colorSpace);handleAlpha(color[4]);return this}if(color=/^\\s*(\\d+)\\%\\s*,\\s*(\\d+)\\%\\s*,\\s*(\\d+)\\%\\s*(?:,\\s*(\\d*\\.?\\d+)\\s*)?$/.exec(components)){this.r=Math.min(100,parseInt(color[1],10))/100;this.g=Math.min(100,parseInt(color[2],10))/100;this.b=Math.min(100,parseInt(color[3],10))/100;ColorManagement.toWorkingColorSpace(this,colorSpace);handleAlpha(color[4]);return this}break;case"hsl":case"hsla":if(color=/^\\s*(\\d*\\.?\\d+)\\s*,\\s*(\\d+)\\%\\s*,\\s*(\\d+)\\%\\s*(?:,\\s*(\\d*\\.?\\d+)\\s*)?$/.exec(components)){const h=parseFloat(color[1])/360;const s=parseInt(color[2],10)/100;const l=parseInt(color[3],10)/100;handleAlpha(color[4]);return this.setHSL(h,s,l,colorSpace)}break}}else if(m=/^\\#([A-Fa-f\\d]+)$/.exec(style)){const hex=m[1];const size=hex.length;if(size===3){this.r=parseInt(hex.charAt(0)+hex.charAt(0),16)/255;this.g=parseInt(hex.charAt(1)+hex.charAt(1),16)/255;this.b=parseInt(hex.charAt(2)+hex.charAt(2),16)/255;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}else if(size===6){this.r=parseInt(hex.charAt(0)+hex.charAt(1),16)/255;this.g=parseInt(hex.charAt(2)+hex.charAt(3),16)/255;this.b=parseInt(hex.charAt(4)+hex.charAt(5),16)/255;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}}if(style&&style.length>0){return this.setColorName(style,colorSpace)}return this}setColorName(style,colorSpace=SRGBColorSpace){const hex=_colorKeywords[style.toLowerCase()];if(hex!==void 0){this.setHex(hex,colorSpace)}else{console.warn("THREE.Color: Unknown color "+style)}return this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this}copySRGBToLinear(color){this.r=SRGBToLinear(color.r);this.g=SRGBToLinear(color.g);this.b=SRGBToLinear(color.b);return this}copyLinearToSRGB(color){this.r=LinearToSRGB(color.r);this.g=LinearToSRGB(color.g);this.b=LinearToSRGB(color.b);return this}convertSRGBToLinear(){this.copySRGBToLinear(this);return this}convertLinearToSRGB(){this.copyLinearToSRGB(this);return this}getHex(colorSpace=SRGBColorSpace){ColorManagement.fromWorkingColorSpace(toComponents(this,_rgb),colorSpace);return clamp(_rgb.r*255,0,255)<<16^clamp(_rgb.g*255,0,255)<<8^clamp(_rgb.b*255,0,255)<<0}getHexString(colorSpace=SRGBColorSpace){return("000000"+this.getHex(colorSpace).toString(16)).slice(-6)}getHSL(target,colorSpace=LinearSRGBColorSpace){ColorManagement.fromWorkingColorSpace(toComponents(this,_rgb),colorSpace);const r=_rgb.r,g=_rgb.g,b=_rgb.b;const max=Math.max(r,g,b);const min=Math.min(r,g,b);let hue,saturation;const lightness=(min+max)/2;if(min===max){hue=0;saturation=0}else{const delta=max-min;saturation=lightness<=.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g2048||canvas.height>2048){console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",image);return canvas.toDataURL("image/jpeg",.6)}else{return canvas.toDataURL("image/png")}}static sRGBToLinear(image){if(typeof HTMLImageElement!=="undefined"&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&image instanceof ImageBitmap){const canvas=createElementNS("canvas");canvas.width=image.width;canvas.height=image.height;const context=canvas.getContext("2d");context.drawImage(image,0,0,image.width,image.height);const imageData=context.getImageData(0,0,image.width,image.height);const data=imageData.data;for(let i=0;i1){switch(this.wrapS){case RepeatWrapping:uv.x=uv.x-Math.floor(uv.x);break;case ClampToEdgeWrapping:uv.x=uv.x<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.x)%2)===1){uv.x=Math.ceil(uv.x)-uv.x}else{uv.x=uv.x-Math.floor(uv.x)}break}}if(uv.y<0||uv.y>1){switch(this.wrapT){case RepeatWrapping:uv.y=uv.y-Math.floor(uv.y);break;case ClampToEdgeWrapping:uv.y=uv.y<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.y)%2)===1){uv.y=Math.ceil(uv.y)-uv.y}else{uv.y=uv.y-Math.floor(uv.y)}break}}if(this.flipY){uv.y=1-uv.y}return uv}set needsUpdate(value){if(value===true){this.version++;this.source.needsUpdate=true}}};Texture.DEFAULT_IMAGE=null;Texture.DEFAULT_MAPPING=UVMapping;var Vector4=class{constructor(x2=0,y2=0,z=0,w=1){Vector4.prototype.isVector4=true;this.x=x2;this.y=y2;this.z=z;this.w=w}get width(){return this.z}set width(value){this.z=value}get height(){return this.w}set height(value){this.w=value}set(x2,y2,z,w){this.x=x2;this.y=y2;this.z=z;this.w=w;return this}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this}setX(x2){this.x=x2;return this}setY(y2){this.y=y2;return this}setZ(z){this.z=z;return this}setW(w){this.w=w;return this}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;case 3:this.w=value;break;default:throw new Error("index is out of range: "+index)}return this}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+index)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;this.w=v.w!==void 0?v.w:1;return this}add(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;this.w+=v.w;return this}addScalar(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;this.w+=v.w*s;return this}sub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;this.w-=v.w;return this}subScalar(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this}multiply(v){this.x*=v.x;this.y*=v.y;this.z*=v.z;this.w*=v.w;return this}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this}applyMatrix4(m){const x2=this.x,y2=this.y,z=this.z,w=this.w;const e=m.elements;this.x=e[0]*x2+e[4]*y2+e[8]*z+e[12]*w;this.y=e[1]*x2+e[5]*y2+e[9]*z+e[13]*w;this.z=e[2]*x2+e[6]*y2+e[10]*z+e[14]*w;this.w=e[3]*x2+e[7]*y2+e[11]*z+e[15]*w;return this}divideScalar(scalar){return this.multiplyScalar(1/scalar)}setAxisAngleFromQuaternion(q){this.w=2*Math.acos(q.w);const s=Math.sqrt(1-q.w*q.w);if(s<1e-4){this.x=1;this.y=0;this.z=0}else{this.x=q.x/s;this.y=q.y/s;this.z=q.z/s}return this}setAxisAngleFromRotationMatrix(m){let angle,x2,y2,z;const epsilon=.01,epsilon2=.1,te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10];if(Math.abs(m12-m21)yy&&xx>zz){if(xxzz){if(yy=0?1:-1,sqrSin=1-cos*cos;if(sqrSin>Number.EPSILON){const sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin}const tDir=t*dir;x0=x0*s+x1*tDir;y0=y0*s+y1*tDir;z0=z0*s+z1*tDir;w0=w0*s+w1*tDir;if(s===1-t){const f=1/Math.sqrt(x0*x0+y0*y0+z0*z0+w0*w0);x0*=f;y0*=f;z0*=f;w0*=f}}dst[dstOffset]=x0;dst[dstOffset+1]=y0;dst[dstOffset+2]=z0;dst[dstOffset+3]=w0}static multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){const x0=src0[srcOffset0];const y0=src0[srcOffset0+1];const z0=src0[srcOffset0+2];const w0=src0[srcOffset0+3];const x1=src1[srcOffset1];const y1=src1[srcOffset1+1];const z1=src1[srcOffset1+2];const w1=src1[srcOffset1+3];dst[dstOffset]=x0*w1+w0*x1+y0*z1-z0*y1;dst[dstOffset+1]=y0*w1+w0*y1+z0*x1-x0*z1;dst[dstOffset+2]=z0*w1+w0*z1+x0*y1-y0*x1;dst[dstOffset+3]=w0*w1-x0*x1-y0*y1-z0*z1;return dst}get x(){return this._x}set x(value){this._x=value;this._onChangeCallback()}get y(){return this._y}set y(value){this._y=value;this._onChangeCallback()}get z(){return this._z}set z(value){this._z=value;this._onChangeCallback()}get w(){return this._w}set w(value){this._w=value;this._onChangeCallback()}set(x2,y2,z,w){this._x=x2;this._y=y2;this._z=z;this._w=w;this._onChangeCallback();return this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this}setFromEuler(euler,update){if(!(euler&&euler.isEuler)){throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.")}const x2=euler._x,y2=euler._y,z=euler._z,order=euler._order;const cos=Math.cos;const sin=Math.sin;const c1=cos(x2/2);const c2=cos(y2/2);const c3=cos(z/2);const s1=sin(x2/2);const s2=sin(y2/2);const s3=sin(z/2);switch(order){case"XYZ":this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case"YXZ":this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case"ZXY":this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case"ZYX":this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case"YZX":this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case"XZY":this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+order)}if(update!==false)this._onChangeCallback();return this}setFromAxisAngle(axis,angle){const halfAngle=angle/2,s=Math.sin(halfAngle);this._x=axis.x*s;this._y=axis.y*s;this._z=axis.z*s;this._w=Math.cos(halfAngle);this._onChangeCallback();return this}setFromRotationMatrix(m){const te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10],trace=m11+m22+m33;if(trace>0){const s=.5/Math.sqrt(trace+1);this._w=.25/s;this._x=(m32-m23)*s;this._y=(m13-m31)*s;this._z=(m21-m12)*s}else if(m11>m22&&m11>m33){const s=2*Math.sqrt(1+m11-m22-m33);this._w=(m32-m23)/s;this._x=.25*s;this._y=(m12+m21)/s;this._z=(m13+m31)/s}else if(m22>m33){const s=2*Math.sqrt(1+m22-m11-m33);this._w=(m13-m31)/s;this._x=(m12+m21)/s;this._y=.25*s;this._z=(m23+m32)/s}else{const s=2*Math.sqrt(1+m33-m11-m22);this._w=(m21-m12)/s;this._x=(m13+m31)/s;this._y=(m23+m32)/s;this._z=.25*s}this._onChangeCallback();return this}setFromUnitVectors(vFrom,vTo){let r=vFrom.dot(vTo)+1;if(rMath.abs(vFrom.z)){this._x=-vFrom.y;this._y=vFrom.x;this._z=0;this._w=r}else{this._x=0;this._y=-vFrom.z;this._z=vFrom.y;this._w=r}}else{this._x=vFrom.y*vTo.z-vFrom.z*vTo.y;this._y=vFrom.z*vTo.x-vFrom.x*vTo.z;this._z=vFrom.x*vTo.y-vFrom.y*vTo.x;this._w=r}return this.normalize()}angleTo(q){return 2*Math.acos(Math.abs(clamp(this.dot(q),-1,1)))}rotateTowards(q,step){const angle=this.angleTo(q);if(angle===0)return this;const t=Math.min(1,step/angle);this.slerp(q,t);return this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this}dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let l=this.length();if(l===0){this._x=0;this._y=0;this._z=0;this._w=1}else{l=1/l;this._x=this._x*l;this._y=this._y*l;this._z=this._z*l;this._w=this._w*l}this._onChangeCallback();return this}multiply(q){return this.multiplyQuaternions(this,q)}premultiply(q){return this.multiplyQuaternions(q,this)}multiplyQuaternions(a,b){const qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;const qbx=b._x,qby=b._y,qbz=b._z,qbw=b._w;this._x=qax*qbw+qaw*qbx+qay*qbz-qaz*qby;this._y=qay*qbw+qaw*qby+qaz*qbx-qax*qbz;this._z=qaz*qbw+qaw*qbz+qax*qby-qay*qbx;this._w=qaw*qbw-qax*qbx-qay*qby-qaz*qbz;this._onChangeCallback();return this}slerp(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);const x2=this._x,y2=this._y,z=this._z,w=this._w;let cosHalfTheta=w*qb._w+x2*qb._x+y2*qb._y+z*qb._z;if(cosHalfTheta<0){this._w=-qb._w;this._x=-qb._x;this._y=-qb._y;this._z=-qb._z;cosHalfTheta=-cosHalfTheta}else{this.copy(qb)}if(cosHalfTheta>=1){this._w=w;this._x=x2;this._y=y2;this._z=z;return this}const sqrSinHalfTheta=1-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){const s=1-t;this._w=s*w+t*this._w;this._x=s*x2+t*this._x;this._y=s*y2+t*this._y;this._z=s*z+t*this._z;this.normalize();this._onChangeCallback();return this}const sinHalfTheta=Math.sqrt(sqrSinHalfTheta);const halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);const ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;this._w=w*ratioA+this._w*ratioB;this._x=x2*ratioA+this._x*ratioB;this._y=y2*ratioA+this._y*ratioB;this._z=z*ratioA+this._z*ratioB;this._onChangeCallback();return this}slerpQuaternions(qa,qb,t){return this.copy(qa).slerp(qb,t)}random(){const u1=Math.random();const sqrt1u1=Math.sqrt(1-u1);const sqrtu1=Math.sqrt(u1);const u2=2*Math.PI*Math.random();const u3=2*Math.PI*Math.random();return this.set(sqrt1u1*Math.cos(u2),sqrtu1*Math.sin(u3),sqrtu1*Math.cos(u3),sqrt1u1*Math.sin(u2))}equals(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w}fromArray(array,offset=0){this._x=array[offset];this._y=array[offset+1];this._z=array[offset+2];this._w=array[offset+3];this._onChangeCallback();return this}toArray(array=[],offset=0){array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._w;return array}fromBufferAttribute(attribute,index){this._x=attribute.getX(index);this._y=attribute.getY(index);this._z=attribute.getZ(index);this._w=attribute.getW(index);return this}_onChange(callback){this._onChangeCallback=callback;return this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x;yield this._y;yield this._z;yield this._w}};var Vector3=class{constructor(x2=0,y2=0,z=0){Vector3.prototype.isVector3=true;this.x=x2;this.y=y2;this.z=z}set(x2,y2,z){if(z===void 0)z=this.z;this.x=x2;this.y=y2;this.z=z;return this}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this}setX(x2){this.x=x2;return this}setY(y2){this.y=y2;return this}setZ(z){this.z=z;return this}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;default:throw new Error("index is out of range: "+index)}return this}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+index)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this}add(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;return this}addScalar(s){this.x+=s;this.y+=s;this.z+=s;return this}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this}sub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;return this}subScalar(s){this.x-=s;this.y-=s;this.z-=s;return this}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this}multiply(v){this.x*=v.x;this.y*=v.y;this.z*=v.z;return this}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this}multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this}applyEuler(euler){return this.applyQuaternion(_quaternion$4.setFromEuler(euler))}applyAxisAngle(axis,angle){return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis,angle))}applyMatrix3(m){const x2=this.x,y2=this.y,z=this.z;const e=m.elements;this.x=e[0]*x2+e[3]*y2+e[6]*z;this.y=e[1]*x2+e[4]*y2+e[7]*z;this.z=e[2]*x2+e[5]*y2+e[8]*z;return this}applyNormalMatrix(m){return this.applyMatrix3(m).normalize()}applyMatrix4(m){const x2=this.x,y2=this.y,z=this.z;const e=m.elements;const w=1/(e[3]*x2+e[7]*y2+e[11]*z+e[15]);this.x=(e[0]*x2+e[4]*y2+e[8]*z+e[12])*w;this.y=(e[1]*x2+e[5]*y2+e[9]*z+e[13])*w;this.z=(e[2]*x2+e[6]*y2+e[10]*z+e[14])*w;return this}applyQuaternion(q){const x2=this.x,y2=this.y,z=this.z;const qx=q.x,qy=q.y,qz=q.z,qw=q.w;const ix=qw*x2+qy*z-qz*y2;const iy=qw*y2+qz*x2-qx*z;const iz=qw*z+qx*y2-qy*x2;const iw=-qx*x2-qy*y2-qz*z;this.x=ix*qw+iw*-qx+iy*-qz-iz*-qy;this.y=iy*qw+iw*-qy+iz*-qx-ix*-qz;this.z=iz*qw+iw*-qz+ix*-qy-iy*-qx;return this}project(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix)}unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld)}transformDirection(m){const x2=this.x,y2=this.y,z=this.z;const e=m.elements;this.x=e[0]*x2+e[4]*y2+e[8]*z;this.y=e[1]*x2+e[5]*y2+e[9]*z;this.z=e[2]*x2+e[6]*y2+e[10]*z;return this.normalize()}divide(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this}divideScalar(scalar){return this.multiplyScalar(1/scalar)}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);return this}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);return this}clamp(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));return this}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));this.z=Math.max(minVal,Math.min(maxVal,this.z));return this}clampLength(min,max){const length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);return this}negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this}dot(v){return this.x*v.x+this.y*v.y+this.z*v.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(length){return this.normalize().multiplyScalar(length)}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;return this}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;this.z=v1.z+(v2.z-v1.z)*alpha;return this}cross(v){return this.crossVectors(this,v)}crossVectors(a,b){const ax=a.x,ay=a.y,az=a.z;const bx=b.x,by=b.y,bz=b.z;this.x=ay*bz-az*by;this.y=az*bx-ax*bz;this.z=ax*by-ay*bx;return this}projectOnVector(v){const denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);const scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar)}projectOnPlane(planeNormal){_vector$c.copy(this).projectOnVector(planeNormal);return this.sub(_vector$c)}reflect(normal){return this.sub(_vector$c.copy(normal).multiplyScalar(2*this.dot(normal)))}angleTo(v){const denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;const theta=this.dot(v)/denominator;return Math.acos(clamp(theta,-1,1))}distanceTo(v){return Math.sqrt(this.distanceToSquared(v))}distanceToSquared(v){const dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z)}setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta)}setFromSphericalCoords(radius,phi,theta){const sinPhiRadius=Math.sin(phi)*radius;this.x=sinPhiRadius*Math.sin(theta);this.y=Math.cos(phi)*radius;this.z=sinPhiRadius*Math.cos(theta);return this}setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y)}setFromCylindricalCoords(radius,theta,y2){this.x=radius*Math.sin(theta);this.y=y2;this.z=radius*Math.cos(theta);return this}setFromMatrixPosition(m){const e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this}setFromMatrixScale(m){const sx=this.setFromMatrixColumn(m,0).length();const sy=this.setFromMatrixColumn(m,1).length();const sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this}setFromMatrixColumn(m,index){return this.fromArray(m.elements,index*4)}setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3)}setFromEuler(e){this.x=e._x;this.y=e._y;this.z=e._z;return this}equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z}fromArray(array,offset=0){this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];return this}toArray(array=[],offset=0){array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;return array}fromBufferAttribute(attribute,index){this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);return this}random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this}randomDirection(){const u=(Math.random()-.5)*2;const t=Math.random()*Math.PI*2;const f=Math.sqrt(1-u**2);this.x=f*Math.cos(t);this.y=f*Math.sin(t);this.z=u;return this}*[Symbol.iterator](){yield this.x;yield this.y;yield this.z}};var _vector$c=new Vector3;var _quaternion$4=new Quaternion;var Box3=class{constructor(min=new Vector3(Infinity,Infinity,Infinity),max=new Vector3(-Infinity,-Infinity,-Infinity)){this.isBox3=true;this.min=min;this.max=max}set(min,max){this.min.copy(min);this.max.copy(max);return this}setFromArray(array){let minX=Infinity;let minY=Infinity;let minZ=Infinity;let maxX=-Infinity;let maxY=-Infinity;let maxZ=-Infinity;for(let i=0,l=array.length;imaxX)maxX=x2;if(y2>maxY)maxY=y2;if(z>maxZ)maxZ=z}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this}setFromBufferAttribute(attribute){let minX=Infinity;let minY=Infinity;let minZ=Infinity;let maxX=-Infinity;let maxY=-Infinity;let maxZ=-Infinity;for(let i=0,l=attribute.count;imaxX)maxX=x2;if(y2>maxY)maxY=y2;if(z>maxZ)maxZ=z}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this}setFromPoints(points){this.makeEmpty();for(let i=0,il=points.length;ithis.max.x||point.ythis.max.y||point.zthis.max.z?false:true}containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y&&this.min.z<=box.min.z&&box.max.z<=this.max.z}getParameter(point,target){return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y),(point.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(box){return box.max.xthis.max.x||box.max.ythis.max.y||box.max.zthis.max.z?false:true}intersectsSphere(sphere){this.clampPoint(sphere.center,_vector$b);return _vector$b.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius}intersectsPlane(plane){let min,max;if(plane.normal.x>0){min=plane.normal.x*this.min.x;max=plane.normal.x*this.max.x}else{min=plane.normal.x*this.max.x;max=plane.normal.x*this.min.x}if(plane.normal.y>0){min+=plane.normal.y*this.min.y;max+=plane.normal.y*this.max.y}else{min+=plane.normal.y*this.max.y;max+=plane.normal.y*this.min.y}if(plane.normal.z>0){min+=plane.normal.z*this.min.z;max+=plane.normal.z*this.max.z}else{min+=plane.normal.z*this.max.z;max+=plane.normal.z*this.min.z}return min<=-plane.constant&&max>=-plane.constant}intersectsTriangle(triangle){if(this.isEmpty()){return false}this.getCenter(_center);_extents.subVectors(this.max,_center);_v0$2.subVectors(triangle.a,_center);_v1$7.subVectors(triangle.b,_center);_v2$3.subVectors(triangle.c,_center);_f0.subVectors(_v1$7,_v0$2);_f1.subVectors(_v2$3,_v1$7);_f2.subVectors(_v0$2,_v2$3);let axes=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];if(!satForAxes(axes,_v0$2,_v1$7,_v2$3,_extents)){return false}axes=[1,0,0,0,1,0,0,0,1];if(!satForAxes(axes,_v0$2,_v1$7,_v2$3,_extents)){return false}_triangleNormal.crossVectors(_f0,_f1);axes=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z];return satForAxes(axes,_v0$2,_v1$7,_v2$3,_extents)}clampPoint(point,target){return target.copy(point).clamp(this.min,this.max)}distanceToPoint(point){const clampedPoint=_vector$b.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length()}getBoundingSphere(target){this.getCenter(target.center);target.radius=this.getSize(_vector$b).length()*.5;return target}intersect(box){this.min.max(box.min);this.max.min(box.max);if(this.isEmpty())this.makeEmpty();return this}union(box){this.min.min(box.min);this.max.max(box.max);return this}applyMatrix4(matrix){if(this.isEmpty())return this;_points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);_points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);_points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);_points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);_points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);_points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);_points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);_points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);this.setFromPoints(_points);return this}translate(offset){this.min.add(offset);this.max.add(offset);return this}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max)}};var _points=[new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3];var _vector$b=new Vector3;var _box$3=new Box3;var _v0$2=new Vector3;var _v1$7=new Vector3;var _v2$3=new Vector3;var _f0=new Vector3;var _f1=new Vector3;var _f2=new Vector3;var _center=new Vector3;var _extents=new Vector3;var _triangleNormal=new Vector3;var _testAxis=new Vector3;function satForAxes(axes,v0,v1,v2,extents){for(let i=0,j=axes.length-3;i<=j;i+=3){_testAxis.fromArray(axes,i);const r=extents.x*Math.abs(_testAxis.x)+extents.y*Math.abs(_testAxis.y)+extents.z*Math.abs(_testAxis.z);const p0=v0.dot(_testAxis);const p1=v1.dot(_testAxis);const p2=v2.dot(_testAxis);if(Math.max(-Math.max(p0,p1,p2),Math.min(p0,p1,p2))>r){return false}}return true}var _box$2=new Box3;var _v1$6=new Vector3;var _toFarthestPoint=new Vector3;var _toPoint=new Vector3;var Sphere=class{constructor(center=new Vector3,radius=-1){this.center=center;this.radius=radius}set(center,radius){this.center.copy(center);this.radius=radius;return this}setFromPoints(points,optionalCenter){const center=this.center;if(optionalCenter!==void 0){center.copy(optionalCenter)}else{_box$2.setFromPoints(points).getCenter(center)}let maxRadiusSq=0;for(let i=0,il=points.length;ithis.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center)}return target}getBoundingBox(target){if(this.isEmpty()){target.makeEmpty();return target}target.set(this.center,this.center);target.expandByScalar(this.radius);return target}applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this}translate(offset){this.center.add(offset);return this}expandByPoint(point){_toPoint.subVectors(point,this.center);const lengthSq=_toPoint.lengthSq();if(lengthSq>this.radius*this.radius){const length=Math.sqrt(lengthSq);const missingRadiusHalf=(length-this.radius)*.5;this.center.add(_toPoint.multiplyScalar(missingRadiusHalf/length));this.radius+=missingRadiusHalf}return this}union(sphere){if(this.center.equals(sphere.center)===true){_toFarthestPoint.set(0,0,1).multiplyScalar(sphere.radius)}else{_toFarthestPoint.subVectors(sphere.center,this.center).normalize().multiplyScalar(sphere.radius)}this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));return this}equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius}clone(){return new this.constructor().copy(this)}};var _vector$a=new Vector3;var _segCenter=new Vector3;var _segDir=new Vector3;var _diff=new Vector3;var _edge1=new Vector3;var _edge2=new Vector3;var _normal$1=new Vector3;var Ray=class{constructor(origin=new Vector3,direction=new Vector3(0,0,-1)){this.origin=origin;this.direction=direction}set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this}copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this}at(t,target){return target.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this}recast(t){this.origin.copy(this.at(t,_vector$a));return this}closestPointToPoint(point,target){target.subVectors(point,this.origin);const directionDistance=target.dot(this.direction);if(directionDistance<0){return target.copy(this.origin)}return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin)}distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point))}distanceSqToPoint(point){const directionDistance=_vector$a.subVectors(point,this.origin).dot(this.direction);if(directionDistance<0){return this.origin.distanceToSquared(point)}_vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return _vector$a.distanceToSquared(point)}distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment){_segCenter.copy(v0).add(v1).multiplyScalar(.5);_segDir.copy(v1).sub(v0).normalize();_diff.copy(this.origin).sub(_segCenter);const segExtent=v0.distanceTo(v1)*.5;const a01=-this.direction.dot(_segDir);const b0=_diff.dot(this.direction);const b1=-_diff.dot(_segDir);const c=_diff.lengthSq();const det=Math.abs(1-a01*a01);let s0,s1,sqrDist,extDet;if(det>0){s0=a01*b1-b0;s1=a01*b0-b1;extDet=segExtent*det;if(s0>=0){if(s1>=-extDet){if(s1<=extDet){const invDet=1/det;s0*=invDet;s1*=invDet;sqrDist=s0*(s0+a01*s1+2*b0)+s1*(a01*s0+s1+2*b1)+c}else{s1=segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}}else{s1=-segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}}else{if(s1<=-extDet){s0=Math.max(0,-(-a01*segExtent+b0));s1=s0>0?-segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c}else if(s1<=extDet){s0=0;s1=Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=s1*(s1+2*b1)+c}else{s0=Math.max(0,-(a01*segExtent+b0));s1=s0>0?segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c}}}else{s1=a01>0?-segExtent:segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}if(optionalPointOnRay){optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin)}if(optionalPointOnSegment){optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter)}return sqrDist}intersectSphere(sphere,target){_vector$a.subVectors(sphere.center,this.origin);const tca=_vector$a.dot(this.direction);const d2=_vector$a.dot(_vector$a)-tca*tca;const radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;const thc=Math.sqrt(radius2-d2);const t0=tca-thc;const t1=tca+thc;if(t0<0&&t1<0)return null;if(t0<0)return this.at(t1,target);return this.at(t0,target)}intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius}distanceToPlane(plane){const denominator=plane.normal.dot(this.direction);if(denominator===0){if(plane.distanceToPoint(this.origin)===0){return 0}return null}const t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;return t>=0?t:null}intersectPlane(plane,target){const t=this.distanceToPlane(plane);if(t===null){return null}return this.at(t,target)}intersectsPlane(plane){const distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true}const denominator=plane.normal.dot(this.direction);if(denominator*distToPoint<0){return true}return false}intersectBox(box,target){let tmin,tmax,tymin,tymax,tzmin,tzmax;const invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;const origin=this.origin;if(invdirx>=0){tmin=(box.min.x-origin.x)*invdirx;tmax=(box.max.x-origin.x)*invdirx}else{tmin=(box.max.x-origin.x)*invdirx;tmax=(box.min.x-origin.x)*invdirx}if(invdiry>=0){tymin=(box.min.y-origin.y)*invdiry;tymax=(box.max.y-origin.y)*invdiry}else{tymin=(box.max.y-origin.y)*invdiry;tymax=(box.min.y-origin.y)*invdiry}if(tmin>tymax||tymin>tmax)return null;if(tymin>tmin||tmin!==tmin)tmin=tymin;if(tymax=0){tzmin=(box.min.z-origin.z)*invdirz;tzmax=(box.max.z-origin.z)*invdirz}else{tzmin=(box.max.z-origin.z)*invdirz;tzmax=(box.min.z-origin.z)*invdirz}if(tmin>tzmax||tzmin>tmax)return null;if(tzmin>tmin||tmin!==tmin)tmin=tzmin;if(tzmax=0?tmin:tmax,target)}intersectsBox(box){return this.intersectBox(box,_vector$a)!==null}intersectTriangle(a,b,c,backfaceCulling,target){_edge1.subVectors(b,a);_edge2.subVectors(c,a);_normal$1.crossVectors(_edge1,_edge2);let DdN=this.direction.dot(_normal$1);let sign2;if(DdN>0){if(backfaceCulling)return null;sign2=1}else if(DdN<0){sign2=-1;DdN=-DdN}else{return null}_diff.subVectors(this.origin,a);const DdQxE2=sign2*this.direction.dot(_edge2.crossVectors(_diff,_edge2));if(DdQxE2<0){return null}const DdE1xQ=sign2*this.direction.dot(_edge1.cross(_diff));if(DdE1xQ<0){return null}if(DdQxE2+DdE1xQ>DdN){return null}const QdN=-sign2*_diff.dot(_normal$1);if(QdN<0){return null}return this.at(QdN/DdN,target)}applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this}equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}};var Matrix4=class{constructor(){Matrix4.prototype.isMatrix4=true;this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){const te=this.elements;te[0]=n11;te[4]=n12;te[8]=n13;te[12]=n14;te[1]=n21;te[5]=n22;te[9]=n23;te[13]=n24;te[2]=n31;te[6]=n32;te[10]=n33;te[14]=n34;te[3]=n41;te[7]=n42;te[11]=n43;te[15]=n44;return this}identity(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this}clone(){return new Matrix4().fromArray(this.elements)}copy(m){const te=this.elements;const me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];te[9]=me[9];te[10]=me[10];te[11]=me[11];te[12]=me[12];te[13]=me[13];te[14]=me[14];te[15]=me[15];return this}copyPosition(m){const te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this}setFromMatrix3(m){const me=m.elements;this.set(me[0],me[3],me[6],0,me[1],me[4],me[7],0,me[2],me[5],me[8],0,0,0,0,1);return this}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this}makeBasis(xAxis,yAxis,zAxis){this.set(xAxis.x,yAxis.x,zAxis.x,0,xAxis.y,yAxis.y,zAxis.y,0,xAxis.z,yAxis.z,zAxis.z,0,0,0,0,1);return this}extractRotation(m){const te=this.elements;const me=m.elements;const scaleX=1/_v1$5.setFromMatrixColumn(m,0).length();const scaleY=1/_v1$5.setFromMatrixColumn(m,1).length();const scaleZ=1/_v1$5.setFromMatrixColumn(m,2).length();te[0]=me[0]*scaleX;te[1]=me[1]*scaleX;te[2]=me[2]*scaleX;te[3]=0;te[4]=me[4]*scaleY;te[5]=me[5]*scaleY;te[6]=me[6]*scaleY;te[7]=0;te[8]=me[8]*scaleZ;te[9]=me[9]*scaleZ;te[10]=me[10]*scaleZ;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this}makeRotationFromEuler(euler){const te=this.elements;const x2=euler.x,y2=euler.y,z=euler.z;const a=Math.cos(x2),b=Math.sin(x2);const c=Math.cos(y2),d=Math.sin(y2);const e=Math.cos(z),f=Math.sin(z);if(euler.order==="XYZ"){const ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=-c*f;te[8]=d;te[1]=af+be*d;te[5]=ae-bf*d;te[9]=-b*c;te[2]=bf-ae*d;te[6]=be+af*d;te[10]=a*c}else if(euler.order==="YXZ"){const ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce+df*b;te[4]=de*b-cf;te[8]=a*d;te[1]=a*f;te[5]=a*e;te[9]=-b;te[2]=cf*b-de;te[6]=df+ce*b;te[10]=a*c}else if(euler.order==="ZXY"){const ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce-df*b;te[4]=-a*f;te[8]=de+cf*b;te[1]=cf+de*b;te[5]=a*e;te[9]=df-ce*b;te[2]=-a*d;te[6]=b;te[10]=a*c}else if(euler.order==="ZYX"){const ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=be*d-af;te[8]=ae*d+bf;te[1]=c*f;te[5]=bf*d+ae;te[9]=af*d-be;te[2]=-d;te[6]=b*c;te[10]=a*c}else if(euler.order==="YZX"){const ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=bd-ac*f;te[8]=bc*f+ad;te[1]=f;te[5]=a*e;te[9]=-b*e;te[2]=-d*e;te[6]=ad*f+bc;te[10]=ac-bd*f}else if(euler.order==="XZY"){const ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=-f;te[8]=d*e;te[1]=ac*f+bd;te[5]=a*e;te[9]=ad*f-bc;te[2]=bc*f-ad;te[6]=b*e;te[10]=bd*f+ac}te[3]=0;te[7]=0;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this}makeRotationFromQuaternion(q){return this.compose(_zero,q,_one)}lookAt(eye,target,up){const te=this.elements;_z.subVectors(eye,target);if(_z.lengthSq()===0){_z.z=1}_z.normalize();_x.crossVectors(up,_z);if(_x.lengthSq()===0){if(Math.abs(up.z)===1){_z.x+=1e-4}else{_z.z+=1e-4}_z.normalize();_x.crossVectors(up,_z)}_x.normalize();_y.crossVectors(_z,_x);te[0]=_x.x;te[4]=_y.x;te[8]=_z.x;te[1]=_x.y;te[5]=_y.y;te[9]=_z.y;te[2]=_x.z;te[6]=_y.z;te[10]=_z.z;return this}multiply(m){return this.multiplyMatrices(this,m)}premultiply(m){return this.multiplyMatrices(m,this)}multiplyMatrices(a,b){const ae=a.elements;const be=b.elements;const te=this.elements;const a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];const a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];const a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];const a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];const b11=be[0],b12=be[4],b13=be[8],b14=be[12];const b21=be[1],b22=be[5],b23=be[9],b24=be[13];const b31=be[2],b32=be[6],b33=be[10],b34=be[14];const b41=be[3],b42=be[7],b43=be[11],b44=be[15];te[0]=a11*b11+a12*b21+a13*b31+a14*b41;te[4]=a11*b12+a12*b22+a13*b32+a14*b42;te[8]=a11*b13+a12*b23+a13*b33+a14*b43;te[12]=a11*b14+a12*b24+a13*b34+a14*b44;te[1]=a21*b11+a22*b21+a23*b31+a24*b41;te[5]=a21*b12+a22*b22+a23*b32+a24*b42;te[9]=a21*b13+a22*b23+a23*b33+a24*b43;te[13]=a21*b14+a22*b24+a23*b34+a24*b44;te[2]=a31*b11+a32*b21+a33*b31+a34*b41;te[6]=a31*b12+a32*b22+a33*b32+a34*b42;te[10]=a31*b13+a32*b23+a33*b33+a34*b43;te[14]=a31*b14+a32*b24+a33*b34+a34*b44;te[3]=a41*b11+a42*b21+a43*b31+a44*b41;te[7]=a41*b12+a42*b22+a43*b32+a44*b42;te[11]=a41*b13+a42*b23+a43*b33+a44*b43;te[15]=a41*b14+a42*b24+a43*b34+a44*b44;return this}multiplyScalar(s){const te=this.elements;te[0]*=s;te[4]*=s;te[8]*=s;te[12]*=s;te[1]*=s;te[5]*=s;te[9]*=s;te[13]*=s;te[2]*=s;te[6]*=s;te[10]*=s;te[14]*=s;te[3]*=s;te[7]*=s;te[11]*=s;te[15]*=s;return this}determinant(){const te=this.elements;const n11=te[0],n12=te[4],n13=te[8],n14=te[12];const n21=te[1],n22=te[5],n23=te[9],n24=te[13];const n31=te[2],n32=te[6],n33=te[10],n34=te[14];const n41=te[3],n42=te[7],n43=te[11],n44=te[15];return n41*(+n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34)+n42*(+n11*n23*n34-n11*n24*n33+n14*n21*n33-n13*n21*n34+n13*n24*n31-n14*n23*n31)+n43*(+n11*n24*n32-n11*n22*n34-n14*n21*n32+n12*n21*n34+n14*n22*n31-n12*n24*n31)+n44*(-n13*n22*n31-n11*n23*n32+n11*n22*n33+n13*n21*n32-n12*n21*n33+n12*n23*n31)}transpose(){const te=this.elements;let tmp2;tmp2=te[1];te[1]=te[4];te[4]=tmp2;tmp2=te[2];te[2]=te[8];te[8]=tmp2;tmp2=te[6];te[6]=te[9];te[9]=tmp2;tmp2=te[3];te[3]=te[12];te[12]=tmp2;tmp2=te[7];te[7]=te[13];te[13]=tmp2;tmp2=te[11];te[11]=te[14];te[14]=tmp2;return this}setPosition(x2,y2,z){const te=this.elements;if(x2.isVector3){te[12]=x2.x;te[13]=x2.y;te[14]=x2.z}else{te[12]=x2;te[13]=y2;te[14]=z}return this}invert(){const te=this.elements,n11=te[0],n21=te[1],n31=te[2],n41=te[3],n12=te[4],n22=te[5],n32=te[6],n42=te[7],n13=te[8],n23=te[9],n33=te[10],n43=te[11],n14=te[12],n24=te[13],n34=te[14],n44=te[15],t11=n23*n34*n42-n24*n33*n42+n24*n32*n43-n22*n34*n43-n23*n32*n44+n22*n33*n44,t12=n14*n33*n42-n13*n34*n42-n14*n32*n43+n12*n34*n43+n13*n32*n44-n12*n33*n44,t13=n13*n24*n42-n14*n23*n42+n14*n22*n43-n12*n24*n43-n13*n22*n44+n12*n23*n44,t14=n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34;const det=n11*t11+n21*t12+n31*t13+n41*t14;if(det===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const detInv=1/det;te[0]=t11*detInv;te[1]=(n24*n33*n41-n23*n34*n41-n24*n31*n43+n21*n34*n43+n23*n31*n44-n21*n33*n44)*detInv;te[2]=(n22*n34*n41-n24*n32*n41+n24*n31*n42-n21*n34*n42-n22*n31*n44+n21*n32*n44)*detInv;te[3]=(n23*n32*n41-n22*n33*n41-n23*n31*n42+n21*n33*n42+n22*n31*n43-n21*n32*n43)*detInv;te[4]=t12*detInv;te[5]=(n13*n34*n41-n14*n33*n41+n14*n31*n43-n11*n34*n43-n13*n31*n44+n11*n33*n44)*detInv;te[6]=(n14*n32*n41-n12*n34*n41-n14*n31*n42+n11*n34*n42+n12*n31*n44-n11*n32*n44)*detInv;te[7]=(n12*n33*n41-n13*n32*n41+n13*n31*n42-n11*n33*n42-n12*n31*n43+n11*n32*n43)*detInv;te[8]=t13*detInv;te[9]=(n14*n23*n41-n13*n24*n41-n14*n21*n43+n11*n24*n43+n13*n21*n44-n11*n23*n44)*detInv;te[10]=(n12*n24*n41-n14*n22*n41+n14*n21*n42-n11*n24*n42-n12*n21*n44+n11*n22*n44)*detInv;te[11]=(n13*n22*n41-n12*n23*n41-n13*n21*n42+n11*n23*n42+n12*n21*n43-n11*n22*n43)*detInv;te[12]=t14*detInv;te[13]=(n13*n24*n31-n14*n23*n31+n14*n21*n33-n11*n24*n33-n13*n21*n34+n11*n23*n34)*detInv;te[14]=(n14*n22*n31-n12*n24*n31-n14*n21*n32+n11*n24*n32+n12*n21*n34-n11*n22*n34)*detInv;te[15]=(n12*n23*n31-n13*n22*n31+n13*n21*n32-n11*n23*n32-n12*n21*n33+n11*n22*n33)*detInv;return this}scale(v){const te=this.elements;const x2=v.x,y2=v.y,z=v.z;te[0]*=x2;te[4]*=y2;te[8]*=z;te[1]*=x2;te[5]*=y2;te[9]*=z;te[2]*=x2;te[6]*=y2;te[10]*=z;te[3]*=x2;te[7]*=y2;te[11]*=z;return this}getMaxScaleOnAxis(){const te=this.elements;const scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];const scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];const scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq))}makeTranslation(x2,y2,z){this.set(1,0,0,x2,0,1,0,y2,0,0,1,z,0,0,0,1);return this}makeRotationX(theta){const c=Math.cos(theta),s=Math.sin(theta);this.set(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);return this}makeRotationY(theta){const c=Math.cos(theta),s=Math.sin(theta);this.set(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);return this}makeRotationZ(theta){const c=Math.cos(theta),s=Math.sin(theta);this.set(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return this}makeRotationAxis(axis,angle){const c=Math.cos(angle);const s=Math.sin(angle);const t=1-c;const x2=axis.x,y2=axis.y,z=axis.z;const tx=t*x2,ty=t*y2;this.set(tx*x2+c,tx*y2-s*z,tx*z+s*y2,0,tx*y2+s*z,ty*y2+c,ty*z-s*x2,0,tx*z-s*y2,ty*z+s*x2,t*z*z+c,0,0,0,0,1);return this}makeScale(x2,y2,z){this.set(x2,0,0,0,0,y2,0,0,0,0,z,0,0,0,0,1);return this}makeShear(xy,xz,yx,yz,zx,zy){this.set(1,yx,zx,0,xy,1,zy,0,xz,yz,1,0,0,0,0,1);return this}compose(position,quaternion,scale){const te=this.elements;const x2=quaternion._x,y2=quaternion._y,z=quaternion._z,w=quaternion._w;const x22=x2+x2,y22=y2+y2,z2=z+z;const xx=x2*x22,xy=x2*y22,xz=x2*z2;const yy=y2*y22,yz=y2*z2,zz=z*z2;const wx=w*x22,wy=w*y22,wz=w*z2;const sx=scale.x,sy=scale.y,sz=scale.z;te[0]=(1-(yy+zz))*sx;te[1]=(xy+wz)*sx;te[2]=(xz-wy)*sx;te[3]=0;te[4]=(xy-wz)*sy;te[5]=(1-(xx+zz))*sy;te[6]=(yz+wx)*sy;te[7]=0;te[8]=(xz+wy)*sz;te[9]=(yz-wx)*sz;te[10]=(1-(xx+yy))*sz;te[11]=0;te[12]=position.x;te[13]=position.y;te[14]=position.z;te[15]=1;return this}decompose(position,quaternion,scale){const te=this.elements;let sx=_v1$5.set(te[0],te[1],te[2]).length();const sy=_v1$5.set(te[4],te[5],te[6]).length();const sz=_v1$5.set(te[8],te[9],te[10]).length();const det=this.determinant();if(det<0)sx=-sx;position.x=te[12];position.y=te[13];position.z=te[14];_m1$2.copy(this);const invSX=1/sx;const invSY=1/sy;const invSZ=1/sz;_m1$2.elements[0]*=invSX;_m1$2.elements[1]*=invSX;_m1$2.elements[2]*=invSX;_m1$2.elements[4]*=invSY;_m1$2.elements[5]*=invSY;_m1$2.elements[6]*=invSY;_m1$2.elements[8]*=invSZ;_m1$2.elements[9]*=invSZ;_m1$2.elements[10]*=invSZ;quaternion.setFromRotationMatrix(_m1$2);scale.x=sx;scale.y=sy;scale.z=sz;return this}makePerspective(left,right,top,bottom,near,far){const te=this.elements;const x2=2*near/(right-left);const y2=2*near/(top-bottom);const a=(right+left)/(right-left);const b=(top+bottom)/(top-bottom);const c=-(far+near)/(far-near);const d=-2*far*near/(far-near);te[0]=x2;te[4]=0;te[8]=a;te[12]=0;te[1]=0;te[5]=y2;te[9]=b;te[13]=0;te[2]=0;te[6]=0;te[10]=c;te[14]=d;te[3]=0;te[7]=0;te[11]=-1;te[15]=0;return this}makeOrthographic(left,right,top,bottom,near,far){const te=this.elements;const w=1/(right-left);const h=1/(top-bottom);const p=1/(far-near);const x2=(right+left)*w;const y2=(top+bottom)*h;const z=(far+near)*p;te[0]=2*w;te[4]=0;te[8]=0;te[12]=-x2;te[1]=0;te[5]=2*h;te[9]=0;te[13]=-y2;te[2]=0;te[6]=0;te[10]=-2*p;te[14]=-z;te[3]=0;te[7]=0;te[11]=0;te[15]=1;return this}equals(matrix){const te=this.elements;const me=matrix.elements;for(let i=0;i<16;i++){if(te[i]!==me[i])return false}return true}fromArray(array,offset=0){for(let i=0;i<16;i++){this.elements[i]=array[i+offset]}return this}toArray(array=[],offset=0){const te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];array[offset+9]=te[9];array[offset+10]=te[10];array[offset+11]=te[11];array[offset+12]=te[12];array[offset+13]=te[13];array[offset+14]=te[14];array[offset+15]=te[15];return array}};var _v1$5=new Vector3;var _m1$2=new Matrix4;var _zero=new Vector3(0,0,0);var _one=new Vector3(1,1,1);var _x=new Vector3;var _y=new Vector3;var _z=new Vector3;var _matrix$1=new Matrix4;var _quaternion$3=new Quaternion;var Euler=class{constructor(x2=0,y2=0,z=0,order=Euler.DefaultOrder){this.isEuler=true;this._x=x2;this._y=y2;this._z=z;this._order=order}get x(){return this._x}set x(value){this._x=value;this._onChangeCallback()}get y(){return this._y}set y(value){this._y=value;this._onChangeCallback()}get z(){return this._z}set z(value){this._z=value;this._onChangeCallback()}get order(){return this._order}set order(value){this._order=value;this._onChangeCallback()}set(x2,y2,z,order=this._order){this._x=x2;this._y=y2;this._z=z;this._order=order;this._onChangeCallback();return this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this}setFromRotationMatrix(m,order=this._order,update=true){const te=m.elements;const m11=te[0],m12=te[4],m13=te[8];const m21=te[1],m22=te[5],m23=te[9];const m31=te[2],m32=te[6],m33=te[10];switch(order){case"XYZ":this._y=Math.asin(clamp(m13,-1,1));if(Math.abs(m13)<.9999999){this._x=Math.atan2(-m23,m33);this._z=Math.atan2(-m12,m11)}else{this._x=Math.atan2(m32,m22);this._z=0}break;case"YXZ":this._x=Math.asin(-clamp(m23,-1,1));if(Math.abs(m23)<.9999999){this._y=Math.atan2(m13,m33);this._z=Math.atan2(m21,m22)}else{this._y=Math.atan2(-m31,m11);this._z=0}break;case"ZXY":this._x=Math.asin(clamp(m32,-1,1));if(Math.abs(m32)<.9999999){this._y=Math.atan2(-m31,m33);this._z=Math.atan2(-m12,m22)}else{this._y=0;this._z=Math.atan2(m21,m11)}break;case"ZYX":this._y=Math.asin(-clamp(m31,-1,1));if(Math.abs(m31)<.9999999){this._x=Math.atan2(m32,m33);this._z=Math.atan2(m21,m11)}else{this._x=0;this._z=Math.atan2(-m12,m22)}break;case"YZX":this._z=Math.asin(clamp(m21,-1,1));if(Math.abs(m21)<.9999999){this._x=Math.atan2(-m23,m22);this._y=Math.atan2(-m31,m11)}else{this._x=0;this._y=Math.atan2(m13,m33)}break;case"XZY":this._z=Math.asin(-clamp(m12,-1,1));if(Math.abs(m12)<.9999999){this._x=Math.atan2(m32,m22);this._y=Math.atan2(m13,m11)}else{this._x=Math.atan2(-m23,m33);this._y=0}break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+order)}this._order=order;if(update===true)this._onChangeCallback();return this}setFromQuaternion(q,order,update){_matrix$1.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix$1,order,update)}setFromVector3(v,order=this._order){return this.set(v.x,v.y,v.z,order)}reorder(newOrder){_quaternion$3.setFromEuler(this);return this.setFromQuaternion(_quaternion$3,newOrder)}equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order}fromArray(array){this._x=array[0];this._y=array[1];this._z=array[2];if(array[3]!==void 0)this._order=array[3];this._onChangeCallback();return this}toArray(array=[],offset=0){array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._order;return array}_onChange(callback){this._onChangeCallback=callback;return this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x;yield this._y;yield this._z;yield this._order}toVector3(){console.error("THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead")}};Euler.DefaultOrder="XYZ";Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];var Layers=class{constructor(){this.mask=1|0}set(channel){this.mask=(1<>>0}enable(channel){this.mask|=1<1){for(let i=0;i1){for(let i=0;i0){object.children=[];for(let i=0;i0){object.animations=[];for(let i=0;i0)output.geometries=geometries;if(materials.length>0)output.materials=materials;if(textures.length>0)output.textures=textures;if(images.length>0)output.images=images;if(shapes.length>0)output.shapes=shapes;if(skeletons.length>0)output.skeletons=skeletons;if(animations.length>0)output.animations=animations;if(nodes.length>0)output.nodes=nodes}output.object=object;return output;function extractFromCache(cache){const values=[];for(const key in cache){const data=cache[key];delete data.metadata;values.push(data)}return values}}clone(recursive){return new this.constructor().copy(this,recursive)}copy(source,recursive=true){this.name=source.name;this.up.copy(source.up);this.position.copy(source.position);this.rotation.order=source.rotation.order;this.quaternion.copy(source.quaternion);this.scale.copy(source.scale);this.matrix.copy(source.matrix);this.matrixWorld.copy(source.matrixWorld);this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrixWorldNeedsUpdate=source.matrixWorldNeedsUpdate;this.layers.mask=source.layers.mask;this.visible=source.visible;this.castShadow=source.castShadow;this.receiveShadow=source.receiveShadow;this.frustumCulled=source.frustumCulled;this.renderOrder=source.renderOrder;this.userData=JSON.parse(JSON.stringify(source.userData));if(recursive===true){for(let i=0;i0){return target.multiplyScalar(1/Math.sqrt(targetLengthSq))}return target.set(0,0,0)}static getBarycoord(point,a,b,c,target){_v0$1.subVectors(c,a);_v1$3.subVectors(b,a);_v2$2.subVectors(point,a);const dot00=_v0$1.dot(_v0$1);const dot01=_v0$1.dot(_v1$3);const dot02=_v0$1.dot(_v2$2);const dot11=_v1$3.dot(_v1$3);const dot12=_v1$3.dot(_v2$2);const denom=dot00*dot11-dot01*dot01;if(denom===0){return target.set(-2,-1,-1)}const invDenom=1/denom;const u=(dot11*dot02-dot01*dot12)*invDenom;const v=(dot00*dot12-dot01*dot02)*invDenom;return target.set(1-u-v,v,u)}static containsPoint(point,a,b,c){this.getBarycoord(point,a,b,c,_v3$1);return _v3$1.x>=0&&_v3$1.y>=0&&_v3$1.x+_v3$1.y<=1}static getUV(point,p1,p2,p3,uv1,uv2,uv3,target){this.getBarycoord(point,p1,p2,p3,_v3$1);target.set(0,0);target.addScaledVector(uv1,_v3$1.x);target.addScaledVector(uv2,_v3$1.y);target.addScaledVector(uv3,_v3$1.z);return target}static isFrontFacing(a,b,c,direction){_v0$1.subVectors(c,b);_v1$3.subVectors(a,b);return _v0$1.cross(_v1$3).dot(direction)<0?true:false}set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this}setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this}setFromAttributeAndIndices(attribute,i0,i1,i2){this.a.fromBufferAttribute(attribute,i0);this.b.fromBufferAttribute(attribute,i1);this.c.fromBufferAttribute(attribute,i2);return this}clone(){return new this.constructor().copy(this)}copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this}getArea(){_v0$1.subVectors(this.c,this.b);_v1$3.subVectors(this.a,this.b);return _v0$1.cross(_v1$3).length()*.5}getMidpoint(target){return target.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(target){return Triangle.getNormal(this.a,this.b,this.c,target)}getPlane(target){return target.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(point,target){return Triangle.getBarycoord(point,this.a,this.b,this.c,target)}getUV(point,uv1,uv2,uv3,target){return Triangle.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target)}containsPoint(point){return Triangle.containsPoint(point,this.a,this.b,this.c)}isFrontFacing(direction){return Triangle.isFrontFacing(this.a,this.b,this.c,direction)}intersectsBox(box){return box.intersectsTriangle(this)}closestPointToPoint(p,target){const a=this.a,b=this.b,c=this.c;let v,w;_vab.subVectors(b,a);_vac.subVectors(c,a);_vap.subVectors(p,a);const d1=_vab.dot(_vap);const d2=_vac.dot(_vap);if(d1<=0&&d2<=0){return target.copy(a)}_vbp.subVectors(p,b);const d3=_vab.dot(_vbp);const d4=_vac.dot(_vbp);if(d3>=0&&d4<=d3){return target.copy(b)}const vc=d1*d4-d3*d2;if(vc<=0&&d1>=0&&d3<=0){v=d1/(d1-d3);return target.copy(a).addScaledVector(_vab,v)}_vcp.subVectors(p,c);const d5=_vab.dot(_vcp);const d6=_vac.dot(_vcp);if(d6>=0&&d5<=d6){return target.copy(c)}const vb=d5*d2-d1*d6;if(vb<=0&&d2>=0&&d6<=0){w=d2/(d2-d6);return target.copy(a).addScaledVector(_vac,w)}const va=d3*d6-d5*d4;if(va<=0&&d4-d3>=0&&d5-d6>=0){_vbc.subVectors(c,b);w=(d4-d3)/(d4-d3+(d5-d6));return target.copy(b).addScaledVector(_vbc,w)}const denom=1/(va+vb+vc);v=vb*denom;w=vc*denom;return target.copy(a).addScaledVector(_vab,v).addScaledVector(_vac,w)}equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c)}};var materialId=0;var Material=class extends EventDispatcher2{constructor(){super();this.isMaterial=true;Object.defineProperty(this,"id",{value:materialId++});this.uuid=generateUUID();this.name="";this.type="Material";this.blending=NormalBlending;this.side=FrontSide;this.vertexColors=false;this.opacity=1;this.transparent=false;this.blendSrc=SrcAlphaFactor;this.blendDst=OneMinusSrcAlphaFactor;this.blendEquation=AddEquation;this.blendSrcAlpha=null;this.blendDstAlpha=null;this.blendEquationAlpha=null;this.depthFunc=LessEqualDepth;this.depthTest=true;this.depthWrite=true;this.stencilWriteMask=255;this.stencilFunc=AlwaysStencilFunc;this.stencilRef=0;this.stencilFuncMask=255;this.stencilFail=KeepStencilOp;this.stencilZFail=KeepStencilOp;this.stencilZPass=KeepStencilOp;this.stencilWrite=false;this.clippingPlanes=null;this.clipIntersection=false;this.clipShadows=false;this.shadowSide=null;this.colorWrite=true;this.precision=null;this.polygonOffset=false;this.polygonOffsetFactor=0;this.polygonOffsetUnits=0;this.dithering=false;this.alphaToCoverage=false;this.premultipliedAlpha=false;this.visible=true;this.toneMapped=true;this.userData={};this.version=0;this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(value){if(this._alphaTest>0!==value>0){this.version++}this._alphaTest=value}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(values){if(values===void 0)return;for(const key in values){const newValue=values[key];if(newValue===void 0){console.warn("THREE.Material: \'"+key+"\' parameter is undefined.");continue}if(key==="shading"){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");this.flatShading=newValue===FlatShading?true:false;continue}const currentValue=this[key];if(currentValue===void 0){console.warn("THREE."+this.type+": \'"+key+"\' is not a property of this material.");continue}if(currentValue&¤tValue.isColor){currentValue.set(newValue)}else if(currentValue&¤tValue.isVector3&&(newValue&&newValue.isVector3)){currentValue.copy(newValue)}else{this[key]=newValue}}}toJSON(meta){const isRootObject=meta===void 0||typeof meta==="string";if(isRootObject){meta={textures:{},images:{}}}const data={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};data.uuid=this.uuid;data.type=this.type;if(this.name!=="")data.name=this.name;if(this.color&&this.color.isColor)data.color=this.color.getHex();if(this.roughness!==void 0)data.roughness=this.roughness;if(this.metalness!==void 0)data.metalness=this.metalness;if(this.sheen!==void 0)data.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)data.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)data.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)data.emissive=this.emissive.getHex();if(this.emissiveIntensity&&this.emissiveIntensity!==1)data.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)data.specular=this.specular.getHex();if(this.specularIntensity!==void 0)data.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)data.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)data.shininess=this.shininess;if(this.clearcoat!==void 0)data.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)data.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture){data.clearcoatMap=this.clearcoatMap.toJSON(meta).uuid}if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture){data.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(meta).uuid}if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture){data.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(meta).uuid;data.clearcoatNormalScale=this.clearcoatNormalScale.toArray()}if(this.iridescence!==void 0)data.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)data.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)data.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture){data.iridescenceMap=this.iridescenceMap.toJSON(meta).uuid}if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture){data.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(meta).uuid}if(this.map&&this.map.isTexture)data.map=this.map.toJSON(meta).uuid;if(this.matcap&&this.matcap.isTexture)data.matcap=this.matcap.toJSON(meta).uuid;if(this.alphaMap&&this.alphaMap.isTexture)data.alphaMap=this.alphaMap.toJSON(meta).uuid;if(this.lightMap&&this.lightMap.isTexture){data.lightMap=this.lightMap.toJSON(meta).uuid;data.lightMapIntensity=this.lightMapIntensity}if(this.aoMap&&this.aoMap.isTexture){data.aoMap=this.aoMap.toJSON(meta).uuid;data.aoMapIntensity=this.aoMapIntensity}if(this.bumpMap&&this.bumpMap.isTexture){data.bumpMap=this.bumpMap.toJSON(meta).uuid;data.bumpScale=this.bumpScale}if(this.normalMap&&this.normalMap.isTexture){data.normalMap=this.normalMap.toJSON(meta).uuid;data.normalMapType=this.normalMapType;data.normalScale=this.normalScale.toArray()}if(this.displacementMap&&this.displacementMap.isTexture){data.displacementMap=this.displacementMap.toJSON(meta).uuid;data.displacementScale=this.displacementScale;data.displacementBias=this.displacementBias}if(this.roughnessMap&&this.roughnessMap.isTexture)data.roughnessMap=this.roughnessMap.toJSON(meta).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)data.metalnessMap=this.metalnessMap.toJSON(meta).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)data.emissiveMap=this.emissiveMap.toJSON(meta).uuid;if(this.specularMap&&this.specularMap.isTexture)data.specularMap=this.specularMap.toJSON(meta).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)data.specularIntensityMap=this.specularIntensityMap.toJSON(meta).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)data.specularColorMap=this.specularColorMap.toJSON(meta).uuid;if(this.envMap&&this.envMap.isTexture){data.envMap=this.envMap.toJSON(meta).uuid;if(this.combine!==void 0)data.combine=this.combine}if(this.envMapIntensity!==void 0)data.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)data.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)data.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture){data.gradientMap=this.gradientMap.toJSON(meta).uuid}if(this.transmission!==void 0)data.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)data.transmissionMap=this.transmissionMap.toJSON(meta).uuid;if(this.thickness!==void 0)data.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)data.thicknessMap=this.thicknessMap.toJSON(meta).uuid;if(this.attenuationDistance!==void 0)data.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)data.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)data.size=this.size;if(this.shadowSide!==null)data.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)data.sizeAttenuation=this.sizeAttenuation;if(this.blending!==NormalBlending)data.blending=this.blending;if(this.side!==FrontSide)data.side=this.side;if(this.vertexColors)data.vertexColors=true;if(this.opacity<1)data.opacity=this.opacity;if(this.transparent===true)data.transparent=this.transparent;data.depthFunc=this.depthFunc;data.depthTest=this.depthTest;data.depthWrite=this.depthWrite;data.colorWrite=this.colorWrite;data.stencilWrite=this.stencilWrite;data.stencilWriteMask=this.stencilWriteMask;data.stencilFunc=this.stencilFunc;data.stencilRef=this.stencilRef;data.stencilFuncMask=this.stencilFuncMask;data.stencilFail=this.stencilFail;data.stencilZFail=this.stencilZFail;data.stencilZPass=this.stencilZPass;if(this.rotation!==void 0&&this.rotation!==0)data.rotation=this.rotation;if(this.polygonOffset===true)data.polygonOffset=true;if(this.polygonOffsetFactor!==0)data.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)data.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)data.linewidth=this.linewidth;if(this.dashSize!==void 0)data.dashSize=this.dashSize;if(this.gapSize!==void 0)data.gapSize=this.gapSize;if(this.scale!==void 0)data.scale=this.scale;if(this.dithering===true)data.dithering=true;if(this.alphaTest>0)data.alphaTest=this.alphaTest;if(this.alphaToCoverage===true)data.alphaToCoverage=this.alphaToCoverage;if(this.premultipliedAlpha===true)data.premultipliedAlpha=this.premultipliedAlpha;if(this.wireframe===true)data.wireframe=this.wireframe;if(this.wireframeLinewidth>1)data.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")data.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")data.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===true)data.flatShading=this.flatShading;if(this.visible===false)data.visible=false;if(this.toneMapped===false)data.toneMapped=false;if(this.fog===false)data.fog=false;if(JSON.stringify(this.userData)!=="{}")data.userData=this.userData;function extractFromCache(cache){const values=[];for(const key in cache){const data2=cache[key];delete data2.metadata;values.push(data2)}return values}if(isRootObject){const textures=extractFromCache(meta.textures);const images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images}return data}clone(){return new this.constructor().copy(this)}copy(source){this.name=source.name;this.blending=source.blending;this.side=source.side;this.vertexColors=source.vertexColors;this.opacity=source.opacity;this.transparent=source.transparent;this.blendSrc=source.blendSrc;this.blendDst=source.blendDst;this.blendEquation=source.blendEquation;this.blendSrcAlpha=source.blendSrcAlpha;this.blendDstAlpha=source.blendDstAlpha;this.blendEquationAlpha=source.blendEquationAlpha;this.depthFunc=source.depthFunc;this.depthTest=source.depthTest;this.depthWrite=source.depthWrite;this.stencilWriteMask=source.stencilWriteMask;this.stencilFunc=source.stencilFunc;this.stencilRef=source.stencilRef;this.stencilFuncMask=source.stencilFuncMask;this.stencilFail=source.stencilFail;this.stencilZFail=source.stencilZFail;this.stencilZPass=source.stencilZPass;this.stencilWrite=source.stencilWrite;const srcPlanes=source.clippingPlanes;let dstPlanes=null;if(srcPlanes!==null){const n=srcPlanes.length;dstPlanes=new Array(n);for(let i=0;i!==n;++i){dstPlanes[i]=srcPlanes[i].clone()}}this.clippingPlanes=dstPlanes;this.clipIntersection=source.clipIntersection;this.clipShadows=source.clipShadows;this.shadowSide=source.shadowSide;this.colorWrite=source.colorWrite;this.precision=source.precision;this.polygonOffset=source.polygonOffset;this.polygonOffsetFactor=source.polygonOffsetFactor;this.polygonOffsetUnits=source.polygonOffsetUnits;this.dithering=source.dithering;this.alphaTest=source.alphaTest;this.alphaToCoverage=source.alphaToCoverage;this.premultipliedAlpha=source.premultipliedAlpha;this.visible=source.visible;this.toneMapped=source.toneMapped;this.userData=JSON.parse(JSON.stringify(source.userData));return this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(value){if(value===true)this.version++}};var MeshBasicMaterial=class extends Material{constructor(parameters){super();this.isMeshBasicMaterial=true;this.type="MeshBasicMaterial";this.color=new Color(16777215);this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.fog=source.fog;return this}};var _vector$9=new Vector3;var _vector2$1=new Vector2;var BufferAttribute=class{constructor(array,itemSize,normalized){if(Array.isArray(array)){throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.")}this.isBufferAttribute=true;this.name="";this.array=array;this.itemSize=itemSize;this.count=array!==void 0?array.length/itemSize:0;this.normalized=normalized===true;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0}onUploadCallback(){}set needsUpdate(value){if(value===true)this.version++}setUsage(value){this.usage=value;return this}copy(source){this.name=source.name;this.array=new source.array.constructor(source.array);this.itemSize=source.itemSize;this.count=source.count;this.normalized=source.normalized;this.usage=source.usage;return this}copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(let i=0,l=this.itemSize;i0)data.userData=this.userData;if(this.parameters!==void 0){const parameters=this.parameters;for(const key in parameters){if(parameters[key]!==void 0)data[key]=parameters[key]}return data}data.data={attributes:{}};const index=this.index;if(index!==null){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)}}const attributes=this.attributes;for(const key in attributes){const attribute=attributes[key];data.data.attributes[key]=attribute.toJSON(data.data)}const morphAttributes={};let hasMorphAttributes=false;for(const key in this.morphAttributes){const attributeArray=this.morphAttributes[key];const array=[];for(let i=0,il=attributeArray.length;i0){morphAttributes[key]=array;hasMorphAttributes=true}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative}const groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups))}const boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius}}return data}clone(){return new this.constructor().copy(this)}copy(source){this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;const data={};this.name=source.name;const index=source.index;if(index!==null){this.setIndex(index.clone(data))}const attributes=source.attributes;for(const name in attributes){const attribute=attributes[name];this.setAttribute(name,attribute.clone(data))}const morphAttributes=source.morphAttributes;for(const name in morphAttributes){const array=[];const morphAttribute=morphAttributes[name];for(let i=0,l=morphAttribute.length;i0){const morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==void 0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(let m=0,ml=morphAttribute.length;mraycaster.far)return null;return{distance,point:_intersectionPointWorld.clone(),object}}function checkBufferGeometryIntersection(object,material,raycaster,ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c){_vA$1.fromBufferAttribute(position,a);_vB$1.fromBufferAttribute(position,b);_vC$1.fromBufferAttribute(position,c);const morphInfluences=object.morphTargetInfluences;if(morphPosition&&morphInfluences){_morphA.set(0,0,0);_morphB.set(0,0,0);_morphC.set(0,0,0);for(let i=0,il=morphPosition.length;i0?1:-1;normals.push(vector.x,vector.y,vector.z);uvs.push(ix/gridX);uvs.push(1-iy/gridY);vertexCounter+=1}}for(let iy=0;iy0)data.defines=this.defines;data.vertexShader=this.vertexShader;data.fragmentShader=this.fragmentShader;const extensions={};for(const key in this.extensions){if(this.extensions[key]===true)extensions[key]=true}if(Object.keys(extensions).length>0)data.extensions=extensions;return data}};var Camera=class extends Object3D{constructor(){super();this.isCamera=true;this.type="Camera";this.matrixWorldInverse=new Matrix4;this.projectionMatrix=new Matrix4;this.projectionMatrixInverse=new Matrix4}copy(source,recursive){super.copy(source,recursive);this.matrixWorldInverse.copy(source.matrixWorldInverse);this.projectionMatrix.copy(source.projectionMatrix);this.projectionMatrixInverse.copy(source.projectionMatrixInverse);return this}getWorldDirection(target){this.updateWorldMatrix(true,false);const e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(force){super.updateMatrixWorld(force);this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(updateParents,updateChildren){super.updateWorldMatrix(updateParents,updateChildren);this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}};var PerspectiveCamera=class extends Camera{constructor(fov2=50,aspect2=1,near=.1,far=2e3){super();this.isPerspectiveCamera=true;this.type="PerspectiveCamera";this.fov=fov2;this.zoom=1;this.near=near;this.far=far;this.focus=10;this.aspect=aspect2;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}copy(source,recursive){super.copy(source,recursive);this.fov=source.fov;this.zoom=source.zoom;this.near=source.near;this.far=source.far;this.focus=source.focus;this.aspect=source.aspect;this.view=source.view===null?null:Object.assign({},source.view);this.filmGauge=source.filmGauge;this.filmOffset=source.filmOffset;return this}setFocalLength(focalLength){const vExtentSlope=.5*this.getFilmHeight()/focalLength;this.fov=RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix()}getFocalLength(){const vExtentSlope=Math.tan(DEG2RAD*.5*this.fov);return .5*this.getFilmHeight()/vExtentSlope}getEffectiveFOV(){return RAD2DEG*2*Math.atan(Math.tan(DEG2RAD*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(fullWidth,fullHeight,x2,y2,width,height){this.aspect=fullWidth/fullHeight;if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x2;this.view.offsetY=y2;this.view.width=width;this.view.height=height;this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null){this.view.enabled=false}this.updateProjectionMatrix()}updateProjectionMatrix(){const near=this.near;let top=near*Math.tan(DEG2RAD*.5*this.fov)/this.zoom;let height=2*top;let width=this.aspect*height;let left=-.5*width;const view=this.view;if(this.view!==null&&this.view.enabled){const fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight}const skew=this.filmOffset;if(skew!==0)left+=near*skew/this.getFilmWidth();this.projectionMatrix.makePerspective(left,left+width,top,top-height,near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(meta){const data=super.toJSON(meta);data.object.fov=this.fov;data.object.zoom=this.zoom;data.object.near=this.near;data.object.far=this.far;data.object.focus=this.focus;data.object.aspect=this.aspect;if(this.view!==null)data.object.view=Object.assign({},this.view);data.object.filmGauge=this.filmGauge;data.object.filmOffset=this.filmOffset;return data}};var fov=90;var aspect=1;var CubeCamera=class extends Object3D{constructor(near,far,renderTarget){super();this.type="CubeCamera";if(renderTarget.isWebGLCubeRenderTarget!==true){console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");return}this.renderTarget=renderTarget;const cameraPX=new PerspectiveCamera(fov,aspect,near,far);cameraPX.layers=this.layers;cameraPX.up.set(0,-1,0);cameraPX.lookAt(new Vector3(1,0,0));this.add(cameraPX);const cameraNX=new PerspectiveCamera(fov,aspect,near,far);cameraNX.layers=this.layers;cameraNX.up.set(0,-1,0);cameraNX.lookAt(new Vector3(-1,0,0));this.add(cameraNX);const cameraPY=new PerspectiveCamera(fov,aspect,near,far);cameraPY.layers=this.layers;cameraPY.up.set(0,0,1);cameraPY.lookAt(new Vector3(0,1,0));this.add(cameraPY);const cameraNY=new PerspectiveCamera(fov,aspect,near,far);cameraNY.layers=this.layers;cameraNY.up.set(0,0,-1);cameraNY.lookAt(new Vector3(0,-1,0));this.add(cameraNY);const cameraPZ=new PerspectiveCamera(fov,aspect,near,far);cameraPZ.layers=this.layers;cameraPZ.up.set(0,-1,0);cameraPZ.lookAt(new Vector3(0,0,1));this.add(cameraPZ);const cameraNZ=new PerspectiveCamera(fov,aspect,near,far);cameraNZ.layers=this.layers;cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3(0,0,-1));this.add(cameraNZ)}update(renderer,scene){if(this.parent===null)this.updateMatrixWorld();const renderTarget=this.renderTarget;const[cameraPX,cameraNX,cameraPY,cameraNY,cameraPZ,cameraNZ]=this.children;const currentRenderTarget=renderer.getRenderTarget();const currentToneMapping=renderer.toneMapping;const currentXrEnabled=renderer.xr.enabled;renderer.toneMapping=NoToneMapping;renderer.xr.enabled=false;const generateMipmaps=renderTarget.texture.generateMipmaps;renderTarget.texture.generateMipmaps=false;renderer.setRenderTarget(renderTarget,0);renderer.render(scene,cameraPX);renderer.setRenderTarget(renderTarget,1);renderer.render(scene,cameraNX);renderer.setRenderTarget(renderTarget,2);renderer.render(scene,cameraPY);renderer.setRenderTarget(renderTarget,3);renderer.render(scene,cameraNY);renderer.setRenderTarget(renderTarget,4);renderer.render(scene,cameraPZ);renderTarget.texture.generateMipmaps=generateMipmaps;renderer.setRenderTarget(renderTarget,5);renderer.render(scene,cameraNZ);renderer.setRenderTarget(currentRenderTarget);renderer.toneMapping=currentToneMapping;renderer.xr.enabled=currentXrEnabled;renderTarget.texture.needsPMREMUpdate=true}};var CubeTexture=class extends Texture{constructor(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){images=images!==void 0?images:[];mapping=mapping!==void 0?mapping:CubeReflectionMapping;super(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.isCubeTexture=true;this.flipY=false}get images(){return this.image}set images(value){this.image=value}};var WebGLCubeRenderTarget=class extends WebGLRenderTarget{constructor(size,options={}){super(size,size,options);this.isWebGLCubeRenderTarget=true;const image={width:size,height:size,depth:1};const images=[image,image,image,image,image,image];this.texture=new CubeTexture(images,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture.isRenderTargetTexture=true;this.texture.generateMipmaps=options.generateMipmaps!==void 0?options.generateMipmaps:false;this.texture.minFilter=options.minFilter!==void 0?options.minFilter:LinearFilter}fromEquirectangularTexture(renderer,texture){this.texture.type=texture.type;this.texture.encoding=texture.encoding;this.texture.generateMipmaps=texture.generateMipmaps;this.texture.minFilter=texture.minFilter;this.texture.magFilter=texture.magFilter;const shader={uniforms:{tEquirect:{value:null}},vertexShader:`\n\n varying vec3 vWorldDirection;\n\n vec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n }\n\n void main() {\n\n vWorldDirection = transformDirection( position, modelMatrix );\n\n #include \n #include \n\n }\n `,fragmentShader:`\n\n uniform sampler2D tEquirect;\n\n varying vec3 vWorldDirection;\n\n #include \n\n void main() {\n\n vec3 direction = normalize( vWorldDirection );\n\n vec2 sampleUV = equirectUv( direction );\n\n gl_FragColor = texture2D( tEquirect, sampleUV );\n\n }\n `};const geometry=new BoxGeometry(5,5,5);const material=new ShaderMaterial({name:"CubemapFromEquirect",uniforms:cloneUniforms(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide,blending:NoBlending});material.uniforms.tEquirect.value=texture;const mesh=new Mesh(geometry,material);const currentMinFilter=texture.minFilter;if(texture.minFilter===LinearMipmapLinearFilter)texture.minFilter=LinearFilter;const camera=new CubeCamera(1,10,this);camera.update(renderer,mesh);texture.minFilter=currentMinFilter;mesh.geometry.dispose();mesh.material.dispose();return this}clear(renderer,color,depth,stencil){const currentRenderTarget=renderer.getRenderTarget();for(let i=0;i<6;i++){renderer.setRenderTarget(this,i);renderer.clear(color,depth,stencil)}renderer.setRenderTarget(currentRenderTarget)}};var _vector1=new Vector3;var _vector2=new Vector3;var _normalMatrix=new Matrix3;var Plane=class{constructor(normal=new Vector3(1,0,0),constant=0){this.isPlane=true;this.normal=normal;this.constant=constant}set(normal,constant){this.normal.copy(normal);this.constant=constant;return this}setComponents(x2,y2,z,w){this.normal.set(x2,y2,z);this.constant=w;return this}setFromNormalAndCoplanarPoint(normal,point){this.normal.copy(normal);this.constant=-point.dot(this.normal);return this}setFromCoplanarPoints(a,b,c){const normal=_vector1.subVectors(c,b).cross(_vector2.subVectors(a,b)).normalize();this.setFromNormalAndCoplanarPoint(normal,a);return this}copy(plane){this.normal.copy(plane.normal);this.constant=plane.constant;return this}normalize(){const inverseNormalLength=1/this.normal.length();this.normal.multiplyScalar(inverseNormalLength);this.constant*=inverseNormalLength;return this}negate(){this.constant*=-1;this.normal.negate();return this}distanceToPoint(point){return this.normal.dot(point)+this.constant}distanceToSphere(sphere){return this.distanceToPoint(sphere.center)-sphere.radius}projectPoint(point,target){return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point)}intersectLine(line,target){const direction=line.delta(_vector1);const denominator=this.normal.dot(direction);if(denominator===0){if(this.distanceToPoint(line.start)===0){return target.copy(line.start)}return null}const t=-(line.start.dot(this.normal)+this.constant)/denominator;if(t<0||t>1){return null}return target.copy(direction).multiplyScalar(t).add(line.start)}intersectsLine(line){const startSign=this.distanceToPoint(line.start);const endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0}intersectsBox(box){return box.intersectsPlane(this)}intersectsSphere(sphere){return sphere.intersectsPlane(this)}coplanarPoint(target){return target.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(matrix,optionalNormalMatrix){const normalMatrix=optionalNormalMatrix||_normalMatrix.getNormalMatrix(matrix);const referencePoint=this.coplanarPoint(_vector1).applyMatrix4(matrix);const normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this}translate(offset){this.constant-=offset.dot(this.normal);return this}equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant}clone(){return new this.constructor().copy(this)}};var _sphere$2=new Sphere;var _vector$7=new Vector3;var Frustum=class{constructor(p0=new Plane,p1=new Plane,p2=new Plane,p3=new Plane,p4=new Plane,p5=new Plane){this.planes=[p0,p1,p2,p3,p4,p5]}set(p0,p1,p2,p3,p4,p5){const planes=this.planes;planes[0].copy(p0);planes[1].copy(p1);planes[2].copy(p2);planes[3].copy(p3);planes[4].copy(p4);planes[5].copy(p5);return this}copy(frustum){const planes=this.planes;for(let i=0;i<6;i++){planes[i].copy(frustum.planes[i])}return this}setFromProjectionMatrix(m){const planes=this.planes;const me=m.elements;const me0=me[0],me1=me[1],me2=me[2],me3=me[3];const me4=me[4],me5=me[5],me6=me[6],me7=me[7];const me8=me[8],me9=me[9],me10=me[10],me11=me[11];const me12=me[12],me13=me[13],me14=me[14],me15=me[15];planes[0].setComponents(me3-me0,me7-me4,me11-me8,me15-me12).normalize();planes[1].setComponents(me3+me0,me7+me4,me11+me8,me15+me12).normalize();planes[2].setComponents(me3+me1,me7+me5,me11+me9,me15+me13).normalize();planes[3].setComponents(me3-me1,me7-me5,me11-me9,me15-me13).normalize();planes[4].setComponents(me3-me2,me7-me6,me11-me10,me15-me14).normalize();planes[5].setComponents(me3+me2,me7+me6,me11+me10,me15+me14).normalize();return this}intersectsObject(object){const geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$2)}intersectsSprite(sprite){_sphere$2.center.set(0,0,0);_sphere$2.radius=.7071067811865476;_sphere$2.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(_sphere$2)}intersectsSphere(sphere){const planes=this.planes;const center=sphere.center;const negRadius=-sphere.radius;for(let i=0;i<6;i++){const distance=planes[i].distanceToPoint(center);if(distance0?box.max.x:box.min.x;_vector$7.y=plane.normal.y>0?box.max.y:box.min.y;_vector$7.z=plane.normal.z>0?box.max.z:box.min.z;if(plane.distanceToPoint(_vector$7)<0){return false}}return true}containsPoint(point){const planes=this.planes;for(let i=0;i<6;i++){if(planes[i].distanceToPoint(point)<0){return false}}return true}clone(){return new this.constructor().copy(this)}};function WebGLAnimation(){let context=null;let isAnimating=false;let animationLoop=null;let requestId=null;function onAnimationFrame(time,frame){animationLoop(time,frame);requestId=context.requestAnimationFrame(onAnimationFrame)}return{start:function(){if(isAnimating===true)return;if(animationLoop===null)return;requestId=context.requestAnimationFrame(onAnimationFrame);isAnimating=true},stop:function(){context.cancelAnimationFrame(requestId);isAnimating=false},setAnimationLoop:function(callback){animationLoop=callback},setContext:function(value){context=value}}}function WebGLAttributes(gl,capabilities){const isWebGL2=capabilities.isWebGL2;const buffers=new WeakMap;function createBuffer(attribute,bufferType){const array=attribute.array;const usage=attribute.usage;const buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();let type;if(array instanceof Float32Array){type=5126}else if(array instanceof Uint16Array){if(attribute.isFloat16BufferAttribute){if(isWebGL2){type=5131}else{throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.")}}else{type=5123}}else if(array instanceof Int16Array){type=5122}else if(array instanceof Uint32Array){type=5125}else if(array instanceof Int32Array){type=5124}else if(array instanceof Int8Array){type=5120}else if(array instanceof Uint8Array){type=5121}else if(array instanceof Uint8ClampedArray){type=5121}else{throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+array)}return{buffer,type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version}}function updateBuffer(buffer,attribute,bufferType){const array=attribute.array;const updateRange=attribute.updateRange;gl.bindBuffer(bufferType,buffer);if(updateRange.count===-1){gl.bufferSubData(bufferType,0,array)}else{if(isWebGL2){gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array,updateRange.offset,updateRange.count)}else{gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array.subarray(updateRange.offset,updateRange.offset+updateRange.count))}updateRange.count=-1}}function get3(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;return buffers.get(attribute)}function remove(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;const data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute)}}function update(attribute,bufferType){if(attribute.isGLBufferAttribute){const cached=buffers.get(attribute);if(!cached||cached.version=0){const cachedAttribute=cachedAttributes[name];let geometryAttribute=geometryAttributes[name];if(geometryAttribute===void 0){if(name==="instanceMatrix"&&object.instanceMatrix)geometryAttribute=object.instanceMatrix;if(name==="instanceColor"&&object.instanceColor)geometryAttribute=object.instanceColor}if(cachedAttribute===void 0)return true;if(cachedAttribute.attribute!==geometryAttribute)return true;if(geometryAttribute&&cachedAttribute.data!==geometryAttribute.data)return true;attributesNum++}}if(currentState.attributesNum!==attributesNum)return true;if(currentState.index!==index)return true;return false}function saveCache(object,geometry,program,index){const cache={};const attributes2=geometry.attributes;let attributesNum=0;const programAttributes=program.getAttributes();for(const name in programAttributes){const programAttribute=programAttributes[name];if(programAttribute.location>=0){let attribute=attributes2[name];if(attribute===void 0){if(name==="instanceMatrix"&&object.instanceMatrix)attribute=object.instanceMatrix;if(name==="instanceColor"&&object.instanceColor)attribute=object.instanceColor}const data={};data.attribute=attribute;if(attribute&&attribute.data){data.data=attribute.data}cache[name]=data;attributesNum++}}currentState.attributes=cache;currentState.attributesNum=attributesNum;currentState.index=index}function initAttributes(){const newAttributes=currentState.newAttributes;for(let i=0,il=newAttributes.length;i=0){let geometryAttribute=geometryAttributes[name];if(geometryAttribute===void 0){if(name==="instanceMatrix"&&object.instanceMatrix)geometryAttribute=object.instanceMatrix;if(name==="instanceColor"&&object.instanceColor)geometryAttribute=object.instanceColor}if(geometryAttribute!==void 0){const normalized=geometryAttribute.normalized;const size=geometryAttribute.itemSize;const attribute=attributes.get(geometryAttribute);if(attribute===void 0)continue;const buffer=attribute.buffer;const type=attribute.type;const bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){const data=geometryAttribute.data;const stride=data.stride;const offset=geometryAttribute.offset;if(data.isInstancedInterleavedBuffer){for(let i=0;i0&&gl.getShaderPrecisionFormat(35632,36338).precision>0){return"highp"}precision2="mediump"}if(precision2==="mediump"){if(gl.getShaderPrecisionFormat(35633,36337).precision>0&&gl.getShaderPrecisionFormat(35632,36337).precision>0){return"mediump"}}return"lowp"}const isWebGL2=typeof WebGL2RenderingContext!=="undefined"&&gl instanceof WebGL2RenderingContext||typeof WebGL2ComputeRenderingContext!=="undefined"&&gl instanceof WebGL2ComputeRenderingContext;let precision=parameters.precision!==void 0?parameters.precision:"highp";const maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn("THREE.WebGLRenderer:",precision,"not supported, using",maxPrecision,"instead.");precision=maxPrecision}const drawBuffers=isWebGL2||extensions.has("WEBGL_draw_buffers");const logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true;const maxTextures=gl.getParameter(34930);const maxVertexTextures=gl.getParameter(35660);const maxTextureSize=gl.getParameter(3379);const maxCubemapSize=gl.getParameter(34076);const maxAttributes=gl.getParameter(34921);const maxVertexUniforms=gl.getParameter(36347);const maxVaryings=gl.getParameter(36348);const maxFragmentUniforms=gl.getParameter(36349);const vertexTextures=maxVertexTextures>0;const floatFragmentTextures=isWebGL2||extensions.has("OES_texture_float");const floatVertexTextures=vertexTextures&&floatFragmentTextures;const maxSamples=isWebGL2?gl.getParameter(36183):0;return{isWebGL2,drawBuffers,getMaxAnisotropy,getMaxPrecision,precision,logarithmicDepthBuffer,maxTextures,maxVertexTextures,maxTextureSize,maxCubemapSize,maxAttributes,maxVertexUniforms,maxVaryings,maxFragmentUniforms,vertexTextures,floatFragmentTextures,floatVertexTextures,maxSamples}}function WebGLClipping(properties){const scope=this;let globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false;const plane=new Plane,viewNormalMatrix=new Matrix3,uniform={value:null,needsUpdate:false};this.uniform=uniform;this.numPlanes=0;this.numIntersection=0;this.init=function(planes,enableLocalClipping,camera){const enabled=planes.length!==0||enableLocalClipping||numGlobalPlanes!==0||localClippingEnabled;localClippingEnabled=enableLocalClipping;globalState=projectPlanes(planes,camera,0);numGlobalPlanes=planes.length;return enabled};this.beginShadows=function(){renderingShadows=true;projectPlanes(null)};this.endShadows=function(){renderingShadows=false;resetGlobalState()};this.setState=function(material,camera,useCache){const planes=material.clippingPlanes,clipIntersection=material.clipIntersection,clipShadows=material.clipShadows;const materialProperties=properties.get(material);if(!localClippingEnabled||planes===null||planes.length===0||renderingShadows&&!clipShadows){if(renderingShadows){projectPlanes(null)}else{resetGlobalState()}}else{const nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4;let dstArray=materialProperties.clippingState||null;uniform.value=dstArray;dstArray=projectPlanes(planes,camera,lGlobal,useCache);for(let i=0;i!==lGlobal;++i){dstArray[i]=globalState[i]}materialProperties.clippingState=dstArray;this.numIntersection=clipIntersection?this.numPlanes:0;this.numPlanes+=nGlobal}};function resetGlobalState(){if(uniform.value!==globalState){uniform.value=globalState;uniform.needsUpdate=numGlobalPlanes>0}scope.numPlanes=numGlobalPlanes;scope.numIntersection=0}function projectPlanes(planes,camera,dstOffset,skipTransform){const nPlanes=planes!==null?planes.length:0;let dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){const flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length0){const renderTarget=new WebGLCubeRenderTarget(image.height/2);renderTarget.fromEquirectangularTexture(renderer,texture);cubemaps.set(texture,renderTarget);texture.addEventListener("dispose",onTextureDispose);return mapTextureMapping(renderTarget.texture,texture.mapping)}else{return null}}}}return texture}function onTextureDispose(event){const texture=event.target;texture.removeEventListener("dispose",onTextureDispose);const cubemap=cubemaps.get(texture);if(cubemap!==void 0){cubemaps.delete(texture);cubemap.dispose()}}function dispose(){cubemaps=new WeakMap}return{get:get3,dispose}}var OrthographicCamera=class extends Camera{constructor(left=-1,right=1,top=1,bottom=-1,near=.1,far=2e3){super();this.isOrthographicCamera=true;this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=left;this.right=right;this.top=top;this.bottom=bottom;this.near=near;this.far=far;this.updateProjectionMatrix()}copy(source,recursive){super.copy(source,recursive);this.left=source.left;this.right=source.right;this.top=source.top;this.bottom=source.bottom;this.near=source.near;this.far=source.far;this.zoom=source.zoom;this.view=source.view===null?null:Object.assign({},source.view);return this}setViewOffset(fullWidth,fullHeight,x2,y2,width,height){if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x2;this.view.offsetY=y2;this.view.width=width;this.view.height=height;this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null){this.view.enabled=false}this.updateProjectionMatrix()}updateProjectionMatrix(){const dx=(this.right-this.left)/(2*this.zoom);const dy=(this.top-this.bottom)/(2*this.zoom);const cx=(this.right+this.left)/2;const cy=(this.top+this.bottom)/2;let left=cx-dx;let right=cx+dx;let top=cy+dy;let bottom=cy-dy;if(this.view!==null&&this.view.enabled){const scaleW=(this.right-this.left)/this.view.fullWidth/this.zoom;const scaleH=(this.top-this.bottom)/this.view.fullHeight/this.zoom;left+=scaleW*this.view.offsetX;right=left+scaleW*this.view.width;top-=scaleH*this.view.offsetY;bottom=top-scaleH*this.view.height}this.projectionMatrix.makeOrthographic(left,right,top,bottom,this.near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(meta){const data=super.toJSON(meta);data.object.zoom=this.zoom;data.object.left=this.left;data.object.right=this.right;data.object.top=this.top;data.object.bottom=this.bottom;data.object.near=this.near;data.object.far=this.far;if(this.view!==null)data.object.view=Object.assign({},this.view);return data}};var LOD_MIN=4;var EXTRA_LOD_SIGMA=[.125,.215,.35,.446,.526,.582];var MAX_SAMPLES=20;var _flatCamera=new OrthographicCamera;var _clearColor=new Color;var _oldTarget=null;var PHI=(1+Math.sqrt(5))/2;var INV_PHI=1/PHI;var _axisDirections=[new Vector3(1,1,1),new Vector3(-1,1,1),new Vector3(1,1,-1),new Vector3(-1,1,-1),new Vector3(0,PHI,INV_PHI),new Vector3(0,PHI,-INV_PHI),new Vector3(INV_PHI,0,PHI),new Vector3(-INV_PHI,0,PHI),new Vector3(PHI,INV_PHI,0),new Vector3(-PHI,INV_PHI,0)];var PMREMGenerator=class{constructor(renderer){this._renderer=renderer;this._pingPongRenderTarget=null;this._lodMax=0;this._cubeSize=0;this._lodPlanes=[];this._sizeLods=[];this._sigmas=[];this._blurMaterial=null;this._cubemapMaterial=null;this._equirectMaterial=null;this._compileMaterial(this._blurMaterial)}fromScene(scene,sigma=0,near=.1,far=100){_oldTarget=this._renderer.getRenderTarget();this._setSize(256);const cubeUVRenderTarget=this._allocateTargets();cubeUVRenderTarget.depthBuffer=true;this._sceneToCubeUV(scene,near,far,cubeUVRenderTarget);if(sigma>0){this._blur(cubeUVRenderTarget,0,0,sigma)}this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget}fromEquirectangular(equirectangular,renderTarget=null){return this._fromTexture(equirectangular,renderTarget)}fromCubemap(cubemap,renderTarget=null){return this._fromTexture(cubemap,renderTarget)}compileCubemapShader(){if(this._cubemapMaterial===null){this._cubemapMaterial=_getCubemapMaterial();this._compileMaterial(this._cubemapMaterial)}}compileEquirectangularShader(){if(this._equirectMaterial===null){this._equirectMaterial=_getEquirectMaterial();this._compileMaterial(this._equirectMaterial)}}dispose(){this._dispose();if(this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose()}_setSize(cubeSize){this._lodMax=Math.floor(Math.log2(cubeSize));this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._pingPongRenderTarget!==null)this._pingPongRenderTarget.dispose();for(let i=0;i2?size:0,size,size);renderer.setRenderTarget(cubeUVRenderTarget);if(useSolidColor){renderer.render(backgroundBox,cubeCamera)}renderer.render(scene,cubeCamera)}backgroundBox.geometry.dispose();backgroundBox.material.dispose();renderer.toneMapping=toneMapping;renderer.autoClear=originalAutoClear;scene.background=background}_textureToCubeUV(texture,cubeUVRenderTarget){const renderer=this._renderer;const isCubeTexture=texture.mapping===CubeReflectionMapping||texture.mapping===CubeRefractionMapping;if(isCubeTexture){if(this._cubemapMaterial===null){this._cubemapMaterial=_getCubemapMaterial()}this._cubemapMaterial.uniforms.flipEnvMap.value=texture.isRenderTargetTexture===false?-1:1}else{if(this._equirectMaterial===null){this._equirectMaterial=_getEquirectMaterial()}}const material=isCubeTexture?this._cubemapMaterial:this._equirectMaterial;const mesh=new Mesh(this._lodPlanes[0],material);const uniforms=material.uniforms;uniforms["envMap"].value=texture;const size=this._cubeSize;_setViewport(cubeUVRenderTarget,0,0,3*size,2*size);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(mesh,_flatCamera)}_applyPMREM(cubeUVRenderTarget){const renderer=this._renderer;const autoClear=renderer.autoClear;renderer.autoClear=false;for(let i=1;iMAX_SAMPLES){console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`)}const weights=[];let sum=0;for(let i=0;i_lodMax-LOD_MIN?lodOut-_lodMax+LOD_MIN:0);const y2=4*(this._cubeSize-outputSize);_setViewport(targetOut,x2,y2,3*outputSize,2*outputSize);renderer.setRenderTarget(targetOut);renderer.render(blurMesh,_flatCamera)}};function _createPlanes(lodMax){const lodPlanes=[];const sizeLods=[];const sigmas=[];let lod=lodMax;const totalLods=lodMax-LOD_MIN+1+EXTRA_LOD_SIGMA.length;for(let i=0;ilodMax-LOD_MIN){sigma=EXTRA_LOD_SIGMA[i-lodMax+LOD_MIN-1]}else if(i===0){sigma=0}sigmas.push(sigma);const texelSize=1/(sizeLod-2);const min=-texelSize;const max=1+texelSize;const uv1=[min,min,max,min,max,max,min,min,max,max,min,max];const cubeFaces=6;const vertices=6;const positionSize=3;const uvSize=2;const faceIndexSize=1;const position=new Float32Array(positionSize*vertices*cubeFaces);const uv=new Float32Array(uvSize*vertices*cubeFaces);const faceIndex=new Float32Array(faceIndexSize*vertices*cubeFaces);for(let face=0;face2?0:-1;const coordinates=[x2,y2,0,x2+2/3,y2,0,x2+2/3,y2+1,0,x2,y2,0,x2+2/3,y2+1,0,x2,y2+1,0];position.set(coordinates,positionSize*vertices*face);uv.set(uv1,uvSize*vertices*face);const fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*vertices*face)}const planes=new BufferGeometry;planes.setAttribute("position",new BufferAttribute(position,positionSize));planes.setAttribute("uv",new BufferAttribute(uv,uvSize));planes.setAttribute("faceIndex",new BufferAttribute(faceIndex,faceIndexSize));lodPlanes.push(planes);if(lod>LOD_MIN){lod--}}return{lodPlanes,sizeLods,sigmas}}function _createRenderTarget(width,height,params){const cubeUVRenderTarget=new WebGLRenderTarget(width,height,params);cubeUVRenderTarget.texture.mapping=CubeUVReflectionMapping;cubeUVRenderTarget.texture.name="PMREM.cubeUv";cubeUVRenderTarget.scissorTest=true;return cubeUVRenderTarget}function _setViewport(target,x2,y2,width,height){target.viewport.set(x2,y2,width,height);target.scissor.set(x2,y2,width,height)}function _getBlurShader(lodMax,width,height){const weights=new Float32Array(MAX_SAMPLES);const poleAxis=new Vector3(0,1,0);const shaderMaterial=new ShaderMaterial({name:"SphericalGaussianBlur",defines:{"n":MAX_SAMPLES,"CUBEUV_TEXEL_WIDTH":1/width,"CUBEUV_TEXEL_HEIGHT":1/height,"CUBEUV_MAX_MIP":`${lodMax}.0`},uniforms:{"envMap":{value:null},"samples":{value:1},"weights":{value:weights},"latitudinal":{value:false},"dTheta":{value:0},"mipInt":{value:0},"poleAxis":{value:poleAxis}},vertexShader:_getCommonVertexShader(),fragmentShader:`\n\n precision mediump float;\n precision mediump int;\n\n varying vec3 vOutputDirection;\n\n uniform sampler2D envMap;\n uniform int samples;\n uniform float weights[ n ];\n uniform bool latitudinal;\n uniform float dTheta;\n uniform float mipInt;\n uniform vec3 poleAxis;\n\n #define ENVMAP_TYPE_CUBE_UV\n #include \n\n vec3 getSample( float theta, vec3 axis ) {\n\n float cosTheta = cos( theta );\n // Rodrigues\' axis-angle rotation\n vec3 sampleDirection = vOutputDirection * cosTheta\n + cross( axis, vOutputDirection ) * sin( theta )\n + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n return bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n }\n\n void main() {\n\n vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n if ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n }\n\n axis = normalize( axis );\n\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n for ( int i = 1; i < n; i++ ) {\n\n if ( i >= samples ) {\n\n break;\n\n }\n\n float theta = dTheta * float( i );\n gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n }\n\n }\n `,blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial}function _getEquirectMaterial(){return new ShaderMaterial({name:"EquirectangularToCubeUV",uniforms:{"envMap":{value:null}},vertexShader:_getCommonVertexShader(),fragmentShader:`\n\n precision mediump float;\n precision mediump int;\n\n varying vec3 vOutputDirection;\n\n uniform sampler2D envMap;\n\n #include \n\n void main() {\n\n vec3 outputDirection = normalize( vOutputDirection );\n vec2 uv = equirectUv( outputDirection );\n\n gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n }\n `,blending:NoBlending,depthTest:false,depthWrite:false})}function _getCubemapMaterial(){return new ShaderMaterial({name:"CubemapToCubeUV",uniforms:{"envMap":{value:null},"flipEnvMap":{value:-1}},vertexShader:_getCommonVertexShader(),fragmentShader:`\n\n precision mediump float;\n precision mediump int;\n\n uniform float flipEnvMap;\n\n varying vec3 vOutputDirection;\n\n uniform samplerCube envMap;\n\n void main() {\n\n gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n }\n `,blending:NoBlending,depthTest:false,depthWrite:false})}function _getCommonVertexShader(){return`\n\n precision mediump float;\n precision mediump int;\n\n attribute float faceIndex;\n\n varying vec3 vOutputDirection;\n\n // RH coordinate system; PMREM face-indexing convention\n vec3 getDirection( vec2 uv, float face ) {\n\n uv = 2.0 * uv - 1.0;\n\n vec3 direction = vec3( uv, 1.0 );\n\n if ( face == 0.0 ) {\n\n direction = direction.zyx; // ( 1, v, u ) pos x\n\n } else if ( face == 1.0 ) {\n\n direction = direction.xzy;\n direction.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n } else if ( face == 2.0 ) {\n\n direction.x *= -1.0; // ( -u, v, 1 ) pos z\n\n } else if ( face == 3.0 ) {\n\n direction = direction.zyx;\n direction.xz *= -1.0; // ( -1, v, -u ) neg x\n\n } else if ( face == 4.0 ) {\n\n direction = direction.xzy;\n direction.xy *= -1.0; // ( -u, -1, v ) neg y\n\n } else if ( face == 5.0 ) {\n\n direction.z *= -1.0; // ( u, v, -1 ) neg z\n\n }\n\n return direction;\n\n }\n\n void main() {\n\n vOutputDirection = getDirection( uv, faceIndex );\n gl_Position = vec4( position, 1.0 );\n\n }\n `}function WebGLCubeUVMaps(renderer){let cubeUVmaps=new WeakMap;let pmremGenerator=null;function get3(texture){if(texture&&texture.isTexture){const mapping=texture.mapping;const isEquirectMap=mapping===EquirectangularReflectionMapping||mapping===EquirectangularRefractionMapping;const isCubeMap=mapping===CubeReflectionMapping||mapping===CubeRefractionMapping;if(isEquirectMap||isCubeMap){if(texture.isRenderTargetTexture&&texture.needsPMREMUpdate===true){texture.needsPMREMUpdate=false;let renderTarget=cubeUVmaps.get(texture);if(pmremGenerator===null)pmremGenerator=new PMREMGenerator(renderer);renderTarget=isEquirectMap?pmremGenerator.fromEquirectangular(texture,renderTarget):pmremGenerator.fromCubemap(texture,renderTarget);cubeUVmaps.set(texture,renderTarget);return renderTarget.texture}else{if(cubeUVmaps.has(texture)){return cubeUVmaps.get(texture).texture}else{const image=texture.image;if(isEquirectMap&&image&&image.height>0||isCubeMap&&image&&isCubeTextureComplete(image)){if(pmremGenerator===null)pmremGenerator=new PMREMGenerator(renderer);const renderTarget=isEquirectMap?pmremGenerator.fromEquirectangular(texture):pmremGenerator.fromCubemap(texture);cubeUVmaps.set(texture,renderTarget);texture.addEventListener("dispose",onTextureDispose);return renderTarget.texture}else{return null}}}}}return texture}function isCubeTextureComplete(image){let count=0;const length=6;for(let i=0;icapabilities.maxTextureSize){height=Math.ceil(width/capabilities.maxTextureSize);width=capabilities.maxTextureSize}const buffer=new Float32Array(width*height*4*morphTargetsCount);const texture=new DataArrayTexture(buffer,width,height,morphTargetsCount);texture.type=FloatType;texture.needsUpdate=true;const vertexDataStride=vertexDataCount*4;for(let i=0;i0)return array;const n=nBlocks*blockSize;let r=arrayCacheF32[n];if(r===void 0){r=new Float32Array(n);arrayCacheF32[n]=r}if(nBlocks!==0){firstElem.toArray(r,0);for(let i=1,offset=0;i!==nBlocks;++i){offset+=blockSize;array[i].toArray(r,offset)}}return r}function arraysEqual(a,b){if(a.length!==b.length)return false;for(let i=0,l=a.length;i":" "} ${line}: ${lines[i]}`)}return lines2.join("\\n")}function getEncodingComponents(encoding){switch(encoding){case LinearEncoding:return["Linear","( value )"];case sRGBEncoding:return["sRGB","( value )"];default:console.warn("THREE.WebGLProgram: Unsupported encoding:",encoding);return["Linear","( value )"]}}function getShaderErrors(gl,shader,type){const status=gl.getShaderParameter(shader,35713);const errors=gl.getShaderInfoLog(shader).trim();if(status&&errors==="")return"";const errorMatches=/ERROR: 0:(\\d+)/.exec(errors);if(errorMatches){const errorLine=parseInt(errorMatches[1]);return type.toUpperCase()+"\\n\\n"+errors+"\\n\\n"+handleSource(gl.getShaderSource(shader),errorLine)}else{return errors}}function getTexelEncodingFunction(functionName,encoding){const components=getEncodingComponents(encoding);return"vec4 "+functionName+"( vec4 value ) { return LinearTo"+components[0]+components[1]+"; }"}function getToneMappingFunction(functionName,toneMapping){let toneMappingName;switch(toneMapping){case LinearToneMapping:toneMappingName="Linear";break;case ReinhardToneMapping:toneMappingName="Reinhard";break;case CineonToneMapping:toneMappingName="OptimizedCineon";break;case ACESFilmicToneMapping:toneMappingName="ACESFilmic";break;case CustomToneMapping:toneMappingName="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",toneMapping);toneMappingName="Linear"}return"vec3 "+functionName+"( vec3 color ) { return "+toneMappingName+"ToneMapping( color ); }"}function generateExtensions(parameters){const chunks=[parameters.extensionDerivatives||!!parameters.envMapCubeUVHeight||parameters.bumpMap||parameters.tangentSpaceNormalMap||parameters.clearcoatNormalMap||parameters.flatShading||parameters.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(parameters.extensionFragDepth||parameters.logarithmicDepthBuffer)&¶meters.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",parameters.extensionDrawBuffers&¶meters.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(parameters.extensionShaderTextureLOD||parameters.envMap||parameters.transmission)&¶meters.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""];return chunks.filter(filterEmptyLine).join("\\n")}function generateDefines(defines){const chunks=[];for(const name in defines){const value=defines[name];if(value===false)continue;chunks.push("#define "+name+" "+value)}return chunks.join("\\n")}function fetchAttributeLocations(gl,program){const attributes={};const n=gl.getProgramParameter(program,35721);for(let i=0;i/gm;function resolveIncludes(string){return string.replace(includePattern,includeReplacer)}function includeReplacer(match,include){const string=ShaderChunk[include];if(string===void 0){throw new Error("Can not resolve #include <"+include+">")}return resolveIncludes(string)}var deprecatedUnrollLoopPattern=/#pragma unroll_loop[\\s]+?for \\( int i \\= (\\d+)\\; i < (\\d+)\\; i \\+\\+ \\) \\{([\\s\\S]+?)(?=\\})\\}/g;var unrollLoopPattern=/#pragma unroll_loop_start\\s+for\\s*\\(\\s*int\\s+i\\s*=\\s*(\\d+)\\s*;\\s*i\\s*<\\s*(\\d+)\\s*;\\s*i\\s*\\+\\+\\s*\\)\\s*{([\\s\\S]+?)}\\s+#pragma unroll_loop_end/g;function unrollLoops(string){return string.replace(unrollLoopPattern,loopReplacer).replace(deprecatedUnrollLoopPattern,deprecatedLoopReplacer)}function deprecatedLoopReplacer(match,start,end,snippet){console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.");return loopReplacer(match,start,end,snippet)}function loopReplacer(match,start,end,snippet){let string="";for(let i=parseInt(start);i0){prefixVertex+="\\n"}prefixFragment=[customExtensions,customDefines].filter(filterEmptyLine).join("\\n");if(prefixFragment.length>0){prefixFragment+="\\n"}}else{prefixVertex=[generatePrecision(parameters),"#define SHADER_NAME "+parameters.shaderName,customDefines,parameters.instancing?"#define USE_INSTANCING":"",parameters.instancingColor?"#define USE_INSTANCING_COLOR":"",parameters.supportsVertexTextures?"#define VERTEX_TEXTURES":"",parameters.useFog&¶meters.fog?"#define USE_FOG":"",parameters.useFog&¶meters.fogExp2?"#define FOG_EXP2":"",parameters.map?"#define USE_MAP":"",parameters.envMap?"#define USE_ENVMAP":"",parameters.envMap?"#define "+envMapModeDefine:"",parameters.lightMap?"#define USE_LIGHTMAP":"",parameters.aoMap?"#define USE_AOMAP":"",parameters.emissiveMap?"#define USE_EMISSIVEMAP":"",parameters.bumpMap?"#define USE_BUMPMAP":"",parameters.normalMap?"#define USE_NORMALMAP":"",parameters.normalMap&¶meters.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",parameters.normalMap&¶meters.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",parameters.clearcoatMap?"#define USE_CLEARCOATMAP":"",parameters.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",parameters.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",parameters.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",parameters.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",parameters.displacementMap&¶meters.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",parameters.specularMap?"#define USE_SPECULARMAP":"",parameters.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",parameters.specularColorMap?"#define USE_SPECULARCOLORMAP":"",parameters.roughnessMap?"#define USE_ROUGHNESSMAP":"",parameters.metalnessMap?"#define USE_METALNESSMAP":"",parameters.alphaMap?"#define USE_ALPHAMAP":"",parameters.transmission?"#define USE_TRANSMISSION":"",parameters.transmissionMap?"#define USE_TRANSMISSIONMAP":"",parameters.thicknessMap?"#define USE_THICKNESSMAP":"",parameters.sheenColorMap?"#define USE_SHEENCOLORMAP":"",parameters.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",parameters.vertexTangents?"#define USE_TANGENT":"",parameters.vertexColors?"#define USE_COLOR":"",parameters.vertexAlphas?"#define USE_COLOR_ALPHA":"",parameters.vertexUvs?"#define USE_UV":"",parameters.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",parameters.flatShading?"#define FLAT_SHADED":"",parameters.skinning?"#define USE_SKINNING":"",parameters.morphTargets?"#define USE_MORPHTARGETS":"",parameters.morphNormals&¶meters.flatShading===false?"#define USE_MORPHNORMALS":"",parameters.morphColors&¶meters.isWebGL2?"#define USE_MORPHCOLORS":"",parameters.morphTargetsCount>0&¶meters.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",parameters.morphTargetsCount>0&¶meters.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+parameters.morphTextureStride:"",parameters.morphTargetsCount>0&¶meters.isWebGL2?"#define MORPHTARGETS_COUNT "+parameters.morphTargetsCount:"",parameters.doubleSided?"#define DOUBLE_SIDED":"",parameters.flipSided?"#define FLIP_SIDED":"",parameters.shadowMapEnabled?"#define USE_SHADOWMAP":"",parameters.shadowMapEnabled?"#define "+shadowMapTypeDefine:"",parameters.sizeAttenuation?"#define USE_SIZEATTENUATION":"",parameters.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif","\\n"].filter(filterEmptyLine).join("\\n");prefixFragment=[customExtensions,generatePrecision(parameters),"#define SHADER_NAME "+parameters.shaderName,customDefines,parameters.useFog&¶meters.fog?"#define USE_FOG":"",parameters.useFog&¶meters.fogExp2?"#define FOG_EXP2":"",parameters.map?"#define USE_MAP":"",parameters.matcap?"#define USE_MATCAP":"",parameters.envMap?"#define USE_ENVMAP":"",parameters.envMap?"#define "+envMapTypeDefine:"",parameters.envMap?"#define "+envMapModeDefine:"",parameters.envMap?"#define "+envMapBlendingDefine:"",envMapCubeUVSize?"#define CUBEUV_TEXEL_WIDTH "+envMapCubeUVSize.texelWidth:"",envMapCubeUVSize?"#define CUBEUV_TEXEL_HEIGHT "+envMapCubeUVSize.texelHeight:"",envMapCubeUVSize?"#define CUBEUV_MAX_MIP "+envMapCubeUVSize.maxMip+".0":"",parameters.lightMap?"#define USE_LIGHTMAP":"",parameters.aoMap?"#define USE_AOMAP":"",parameters.emissiveMap?"#define USE_EMISSIVEMAP":"",parameters.bumpMap?"#define USE_BUMPMAP":"",parameters.normalMap?"#define USE_NORMALMAP":"",parameters.normalMap&¶meters.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",parameters.normalMap&¶meters.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",parameters.clearcoat?"#define USE_CLEARCOAT":"",parameters.clearcoatMap?"#define USE_CLEARCOATMAP":"",parameters.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",parameters.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",parameters.iridescence?"#define USE_IRIDESCENCE":"",parameters.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",parameters.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",parameters.specularMap?"#define USE_SPECULARMAP":"",parameters.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",parameters.specularColorMap?"#define USE_SPECULARCOLORMAP":"",parameters.roughnessMap?"#define USE_ROUGHNESSMAP":"",parameters.metalnessMap?"#define USE_METALNESSMAP":"",parameters.alphaMap?"#define USE_ALPHAMAP":"",parameters.alphaTest?"#define USE_ALPHATEST":"",parameters.sheen?"#define USE_SHEEN":"",parameters.sheenColorMap?"#define USE_SHEENCOLORMAP":"",parameters.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",parameters.transmission?"#define USE_TRANSMISSION":"",parameters.transmissionMap?"#define USE_TRANSMISSIONMAP":"",parameters.thicknessMap?"#define USE_THICKNESSMAP":"",parameters.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",parameters.vertexTangents?"#define USE_TANGENT":"",parameters.vertexColors||parameters.instancingColor?"#define USE_COLOR":"",parameters.vertexAlphas?"#define USE_COLOR_ALPHA":"",parameters.vertexUvs?"#define USE_UV":"",parameters.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",parameters.gradientMap?"#define USE_GRADIENTMAP":"",parameters.flatShading?"#define FLAT_SHADED":"",parameters.doubleSided?"#define DOUBLE_SIDED":"",parameters.flipSided?"#define FLIP_SIDED":"",parameters.shadowMapEnabled?"#define USE_SHADOWMAP":"",parameters.shadowMapEnabled?"#define "+shadowMapTypeDefine:"",parameters.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",parameters.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",parameters.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",parameters.toneMapping!==NoToneMapping?"#define TONE_MAPPING":"",parameters.toneMapping!==NoToneMapping?ShaderChunk["tonemapping_pars_fragment"]:"",parameters.toneMapping!==NoToneMapping?getToneMappingFunction("toneMapping",parameters.toneMapping):"",parameters.dithering?"#define DITHERING":"",parameters.opaque?"#define OPAQUE":"",ShaderChunk["encodings_pars_fragment"],getTexelEncodingFunction("linearToOutputTexel",parameters.outputEncoding),parameters.useDepthPacking?"#define DEPTH_PACKING "+parameters.depthPacking:"","\\n"].filter(filterEmptyLine).join("\\n")}vertexShader=resolveIncludes(vertexShader);vertexShader=replaceLightNums(vertexShader,parameters);vertexShader=replaceClippingPlaneNums(vertexShader,parameters);fragmentShader=resolveIncludes(fragmentShader);fragmentShader=replaceLightNums(fragmentShader,parameters);fragmentShader=replaceClippingPlaneNums(fragmentShader,parameters);vertexShader=unrollLoops(vertexShader);fragmentShader=unrollLoops(fragmentShader);if(parameters.isWebGL2&¶meters.isRawShaderMaterial!==true){versionString="#version 300 es\\n";prefixVertex=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\\n")+"\\n"+prefixVertex;prefixFragment=["#define varying in",parameters.glslVersion===GLSL3?"":"layout(location = 0) out highp vec4 pc_fragColor;",parameters.glslVersion===GLSL3?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\\n")+"\\n"+prefixFragment}const vertexGlsl=versionString+prefixVertex+vertexShader;const fragmentGlsl=versionString+prefixFragment+fragmentShader;const glVertexShader=WebGLShader(gl,35633,vertexGlsl);const glFragmentShader=WebGLShader(gl,35632,fragmentGlsl);gl.attachShader(program,glVertexShader);gl.attachShader(program,glFragmentShader);if(parameters.index0AttributeName!==void 0){gl.bindAttribLocation(program,0,parameters.index0AttributeName)}else if(parameters.morphTargets===true){gl.bindAttribLocation(program,0,"position")}gl.linkProgram(program);if(renderer.debug.checkShaderErrors){const programLog=gl.getProgramInfoLog(program).trim();const vertexLog=gl.getShaderInfoLog(glVertexShader).trim();const fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();let runnable=true;let haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;const vertexErrors=getShaderErrors(gl,glVertexShader,"vertex");const fragmentErrors=getShaderErrors(gl,glFragmentShader,"fragment");console.error("THREE.WebGLProgram: Shader Error "+gl.getError()+" - VALIDATE_STATUS "+gl.getProgramParameter(program,35715)+"\\n\\nProgram Info Log: "+programLog+"\\n"+vertexErrors+"\\n"+fragmentErrors)}else if(programLog!==""){console.warn("THREE.WebGLProgram: Program Info Log:",programLog)}else if(vertexLog===""||fragmentLog===""){haveDiagnostics=false}if(haveDiagnostics){this.diagnostics={runnable,programLog,vertexShader:{log:vertexLog,prefix:prefixVertex},fragmentShader:{log:fragmentLog,prefix:prefixFragment}}}}gl.deleteShader(glVertexShader);gl.deleteShader(glFragmentShader);let cachedUniforms;this.getUniforms=function(){if(cachedUniforms===void 0){cachedUniforms=new WebGLUniforms(gl,program)}return cachedUniforms};let cachedAttributes;this.getAttributes=function(){if(cachedAttributes===void 0){cachedAttributes=fetchAttributeLocations(gl,program)}return cachedAttributes};this.destroy=function(){bindingStates.releaseStatesOfProgram(this);gl.deleteProgram(program);this.program=void 0};this.name=parameters.shaderName;this.id=programIdCount++;this.cacheKey=cacheKey;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this}var _id=0;var WebGLShaderCache=class{constructor(){this.shaderCache=new Map;this.materialCache=new Map}update(material){const vertexShader=material.vertexShader;const fragmentShader=material.fragmentShader;const vertexShaderStage=this._getShaderStage(vertexShader);const fragmentShaderStage=this._getShaderStage(fragmentShader);const materialShaders=this._getShaderCacheForMaterial(material);if(materialShaders.has(vertexShaderStage)===false){materialShaders.add(vertexShaderStage);vertexShaderStage.usedTimes++}if(materialShaders.has(fragmentShaderStage)===false){materialShaders.add(fragmentShaderStage);fragmentShaderStage.usedTimes++}return this}remove(material){const materialShaders=this.materialCache.get(material);for(const shaderStage of materialShaders){shaderStage.usedTimes--;if(shaderStage.usedTimes===0)this.shaderCache.delete(shaderStage.code)}this.materialCache.delete(material);return this}getVertexShaderID(material){return this._getShaderStage(material.vertexShader).id}getFragmentShaderID(material){return this._getShaderStage(material.fragmentShader).id}dispose(){this.shaderCache.clear();this.materialCache.clear()}_getShaderCacheForMaterial(material){const cache=this.materialCache;if(cache.has(material)===false){cache.set(material,new Set)}return cache.get(material)}_getShaderStage(code){const cache=this.shaderCache;if(cache.has(code)===false){const stage=new WebGLShaderStage(code);cache.set(code,stage)}return cache.get(code)}};var WebGLShaderStage=class{constructor(code){this.id=_id++;this.code=code;this.usedTimes=0}};function WebGLPrograms(renderer,cubemaps,cubeuvmaps,extensions,capabilities,bindingStates,clipping){const _programLayers=new Layers;const _customShaders=new WebGLShaderCache;const programs=[];const isWebGL2=capabilities.isWebGL2;const logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;const vertexTextures=capabilities.vertexTextures;let precision=capabilities.precision;const shaderIDs={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function getParameters(material,lights,shadows,scene,object){const fog=scene.fog;const geometry=object.geometry;const environment=material.isMeshStandardMaterial?scene.environment:null;const envMap=(material.isMeshStandardMaterial?cubeuvmaps:cubemaps).get(material.envMap||environment);const envMapCubeUVHeight=!!envMap&&envMap.mapping===CubeUVReflectionMapping?envMap.image.height:null;const shaderID=shaderIDs[material.type];if(material.precision!==null){precision=capabilities.getMaxPrecision(material.precision);if(precision!==material.precision){console.warn("THREE.WebGLProgram.getParameters:",material.precision,"not supported, using",precision,"instead.")}}const morphAttribute=geometry.morphAttributes.position||geometry.morphAttributes.normal||geometry.morphAttributes.color;const morphTargetsCount=morphAttribute!==void 0?morphAttribute.length:0;let morphTextureStride=0;if(geometry.morphAttributes.position!==void 0)morphTextureStride=1;if(geometry.morphAttributes.normal!==void 0)morphTextureStride=2;if(geometry.morphAttributes.color!==void 0)morphTextureStride=3;let vertexShader,fragmentShader;let customVertexShaderID,customFragmentShaderID;if(shaderID){const shader=ShaderLib[shaderID];vertexShader=shader.vertexShader;fragmentShader=shader.fragmentShader}else{vertexShader=material.vertexShader;fragmentShader=material.fragmentShader;_customShaders.update(material);customVertexShaderID=_customShaders.getVertexShaderID(material);customFragmentShaderID=_customShaders.getFragmentShaderID(material)}const currentRenderTarget=renderer.getRenderTarget();const useAlphaTest=material.alphaTest>0;const useClearcoat=material.clearcoat>0;const useIridescence=material.iridescence>0;const parameters={isWebGL2,shaderID,shaderName:material.type,vertexShader,fragmentShader,defines:material.defines,customVertexShaderID,customFragmentShaderID,isRawShaderMaterial:material.isRawShaderMaterial===true,glslVersion:material.glslVersion,precision,instancing:object.isInstancedMesh===true,instancingColor:object.isInstancedMesh===true&&object.instanceColor!==null,supportsVertexTextures:vertexTextures,outputEncoding:currentRenderTarget===null?renderer.outputEncoding:currentRenderTarget.isXRRenderTarget===true?currentRenderTarget.texture.encoding:LinearEncoding,map:!!material.map,matcap:!!material.matcap,envMap:!!envMap,envMapMode:envMap&&envMap.mapping,envMapCubeUVHeight,lightMap:!!material.lightMap,aoMap:!!material.aoMap,emissiveMap:!!material.emissiveMap,bumpMap:!!material.bumpMap,normalMap:!!material.normalMap,objectSpaceNormalMap:material.normalMapType===ObjectSpaceNormalMap,tangentSpaceNormalMap:material.normalMapType===TangentSpaceNormalMap,decodeVideoTexture:!!material.map&&material.map.isVideoTexture===true&&material.map.encoding===sRGBEncoding,clearcoat:useClearcoat,clearcoatMap:useClearcoat&&!!material.clearcoatMap,clearcoatRoughnessMap:useClearcoat&&!!material.clearcoatRoughnessMap,clearcoatNormalMap:useClearcoat&&!!material.clearcoatNormalMap,iridescence:useIridescence,iridescenceMap:useIridescence&&!!material.iridescenceMap,iridescenceThicknessMap:useIridescence&&!!material.iridescenceThicknessMap,displacementMap:!!material.displacementMap,roughnessMap:!!material.roughnessMap,metalnessMap:!!material.metalnessMap,specularMap:!!material.specularMap,specularIntensityMap:!!material.specularIntensityMap,specularColorMap:!!material.specularColorMap,opaque:material.transparent===false&&material.blending===NormalBlending,alphaMap:!!material.alphaMap,alphaTest:useAlphaTest,gradientMap:!!material.gradientMap,sheen:material.sheen>0,sheenColorMap:!!material.sheenColorMap,sheenRoughnessMap:!!material.sheenRoughnessMap,transmission:material.transmission>0,transmissionMap:!!material.transmissionMap,thicknessMap:!!material.thicknessMap,combine:material.combine,vertexTangents:!!material.normalMap&&!!geometry.attributes.tangent,vertexColors:material.vertexColors,vertexAlphas:material.vertexColors===true&&!!geometry.attributes.color&&geometry.attributes.color.itemSize===4,vertexUvs:!!material.map||!!material.bumpMap||!!material.normalMap||!!material.specularMap||!!material.alphaMap||!!material.emissiveMap||!!material.roughnessMap||!!material.metalnessMap||!!material.clearcoatMap||!!material.clearcoatRoughnessMap||!!material.clearcoatNormalMap||!!material.iridescenceMap||!!material.iridescenceThicknessMap||!!material.displacementMap||!!material.transmissionMap||!!material.thicknessMap||!!material.specularIntensityMap||!!material.specularColorMap||!!material.sheenColorMap||!!material.sheenRoughnessMap,uvsVertexOnly:!(!!material.map||!!material.bumpMap||!!material.normalMap||!!material.specularMap||!!material.alphaMap||!!material.emissiveMap||!!material.roughnessMap||!!material.metalnessMap||!!material.clearcoatNormalMap||!!material.iridescenceMap||!!material.iridescenceThicknessMap||material.transmission>0||!!material.transmissionMap||!!material.thicknessMap||!!material.specularIntensityMap||!!material.specularColorMap||material.sheen>0||!!material.sheenColorMap||!!material.sheenRoughnessMap)&&!!material.displacementMap,fog:!!fog,useFog:material.fog===true,fogExp2:fog&&fog.isFogExp2,flatShading:!!material.flatShading,sizeAttenuation:material.sizeAttenuation,logarithmicDepthBuffer,skinning:object.isSkinnedMesh===true,morphTargets:geometry.morphAttributes.position!==void 0,morphNormals:geometry.morphAttributes.normal!==void 0,morphColors:geometry.morphAttributes.color!==void 0,morphTargetsCount,morphTextureStride,numDirLights:lights.directional.length,numPointLights:lights.point.length,numSpotLights:lights.spot.length,numRectAreaLights:lights.rectArea.length,numHemiLights:lights.hemi.length,numDirLightShadows:lights.directionalShadowMap.length,numPointLightShadows:lights.pointShadowMap.length,numSpotLightShadows:lights.spotShadowMap.length,numClippingPlanes:clipping.numPlanes,numClipIntersection:clipping.numIntersection,dithering:material.dithering,shadowMapEnabled:renderer.shadowMap.enabled&&shadows.length>0,shadowMapType:renderer.shadowMap.type,toneMapping:material.toneMapped?renderer.toneMapping:NoToneMapping,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,doubleSided:material.side===DoubleSide,flipSided:material.side===BackSide,useDepthPacking:!!material.depthPacking,depthPacking:material.depthPacking||0,index0AttributeName:material.index0AttributeName,extensionDerivatives:material.extensions&&material.extensions.derivatives,extensionFragDepth:material.extensions&&material.extensions.fragDepth,extensionDrawBuffers:material.extensions&&material.extensions.drawBuffers,extensionShaderTextureLOD:material.extensions&&material.extensions.shaderTextureLOD,rendererExtensionFragDepth:isWebGL2||extensions.has("EXT_frag_depth"),rendererExtensionDrawBuffers:isWebGL2||extensions.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:isWebGL2||extensions.has("EXT_shader_texture_lod"),customProgramCacheKey:material.customProgramCacheKey()};return parameters}function getProgramCacheKey(parameters){const array=[];if(parameters.shaderID){array.push(parameters.shaderID)}else{array.push(parameters.customVertexShaderID);array.push(parameters.customFragmentShaderID)}if(parameters.defines!==void 0){for(const name in parameters.defines){array.push(name);array.push(parameters.defines[name])}}if(parameters.isRawShaderMaterial===false){getProgramCacheKeyParameters(array,parameters);getProgramCacheKeyBooleans(array,parameters);array.push(renderer.outputEncoding)}array.push(parameters.customProgramCacheKey);return array.join()}function getProgramCacheKeyParameters(array,parameters){array.push(parameters.precision);array.push(parameters.outputEncoding);array.push(parameters.envMapMode);array.push(parameters.envMapCubeUVHeight);array.push(parameters.combine);array.push(parameters.vertexUvs);array.push(parameters.fogExp2);array.push(parameters.sizeAttenuation);array.push(parameters.morphTargetsCount);array.push(parameters.morphAttributeCount);array.push(parameters.numDirLights);array.push(parameters.numPointLights);array.push(parameters.numSpotLights);array.push(parameters.numHemiLights);array.push(parameters.numRectAreaLights);array.push(parameters.numDirLightShadows);array.push(parameters.numPointLightShadows);array.push(parameters.numSpotLightShadows);array.push(parameters.shadowMapType);array.push(parameters.toneMapping);array.push(parameters.numClippingPlanes);array.push(parameters.numClipIntersection);array.push(parameters.depthPacking)}function getProgramCacheKeyBooleans(array,parameters){_programLayers.disableAll();if(parameters.isWebGL2)_programLayers.enable(0);if(parameters.supportsVertexTextures)_programLayers.enable(1);if(parameters.instancing)_programLayers.enable(2);if(parameters.instancingColor)_programLayers.enable(3);if(parameters.map)_programLayers.enable(4);if(parameters.matcap)_programLayers.enable(5);if(parameters.envMap)_programLayers.enable(6);if(parameters.lightMap)_programLayers.enable(7);if(parameters.aoMap)_programLayers.enable(8);if(parameters.emissiveMap)_programLayers.enable(9);if(parameters.bumpMap)_programLayers.enable(10);if(parameters.normalMap)_programLayers.enable(11);if(parameters.objectSpaceNormalMap)_programLayers.enable(12);if(parameters.tangentSpaceNormalMap)_programLayers.enable(13);if(parameters.clearcoat)_programLayers.enable(14);if(parameters.clearcoatMap)_programLayers.enable(15);if(parameters.clearcoatRoughnessMap)_programLayers.enable(16);if(parameters.clearcoatNormalMap)_programLayers.enable(17);if(parameters.iridescence)_programLayers.enable(18);if(parameters.iridescenceMap)_programLayers.enable(19);if(parameters.iridescenceThicknessMap)_programLayers.enable(20);if(parameters.displacementMap)_programLayers.enable(21);if(parameters.specularMap)_programLayers.enable(22);if(parameters.roughnessMap)_programLayers.enable(23);if(parameters.metalnessMap)_programLayers.enable(24);if(parameters.gradientMap)_programLayers.enable(25);if(parameters.alphaMap)_programLayers.enable(26);if(parameters.alphaTest)_programLayers.enable(27);if(parameters.vertexColors)_programLayers.enable(28);if(parameters.vertexAlphas)_programLayers.enable(29);if(parameters.vertexUvs)_programLayers.enable(30);if(parameters.vertexTangents)_programLayers.enable(31);if(parameters.uvsVertexOnly)_programLayers.enable(32);if(parameters.fog)_programLayers.enable(33);array.push(_programLayers.mask);_programLayers.disableAll();if(parameters.useFog)_programLayers.enable(0);if(parameters.flatShading)_programLayers.enable(1);if(parameters.logarithmicDepthBuffer)_programLayers.enable(2);if(parameters.skinning)_programLayers.enable(3);if(parameters.morphTargets)_programLayers.enable(4);if(parameters.morphNormals)_programLayers.enable(5);if(parameters.morphColors)_programLayers.enable(6);if(parameters.premultipliedAlpha)_programLayers.enable(7);if(parameters.shadowMapEnabled)_programLayers.enable(8);if(parameters.physicallyCorrectLights)_programLayers.enable(9);if(parameters.doubleSided)_programLayers.enable(10);if(parameters.flipSided)_programLayers.enable(11);if(parameters.useDepthPacking)_programLayers.enable(12);if(parameters.dithering)_programLayers.enable(13);if(parameters.specularIntensityMap)_programLayers.enable(14);if(parameters.specularColorMap)_programLayers.enable(15);if(parameters.transmission)_programLayers.enable(16);if(parameters.transmissionMap)_programLayers.enable(17);if(parameters.thicknessMap)_programLayers.enable(18);if(parameters.sheen)_programLayers.enable(19);if(parameters.sheenColorMap)_programLayers.enable(20);if(parameters.sheenRoughnessMap)_programLayers.enable(21);if(parameters.decodeVideoTexture)_programLayers.enable(22);if(parameters.opaque)_programLayers.enable(23);array.push(_programLayers.mask)}function getUniforms(material){const shaderID=shaderIDs[material.type];let uniforms;if(shaderID){const shader=ShaderLib[shaderID];uniforms=UniformsUtils.clone(shader.uniforms)}else{uniforms=material.uniforms}return uniforms}function acquireProgram(parameters,cacheKey){let program;for(let p=0,pl=programs.length;p0){transmissive.push(renderItem)}else if(material.transparent===true){transparent.push(renderItem)}else{opaque.push(renderItem)}}function unshift(object,geometry,material,groupOrder,z,group){const renderItem=getNextRenderItem(object,geometry,material,groupOrder,z,group);if(material.transmission>0){transmissive.unshift(renderItem)}else if(material.transparent===true){transparent.unshift(renderItem)}else{opaque.unshift(renderItem)}}function sort(customOpaqueSort,customTransparentSort){if(opaque.length>1)opaque.sort(customOpaqueSort||painterSortStable);if(transmissive.length>1)transmissive.sort(customTransparentSort||reversePainterSortStable);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable)}function finish(){for(let i=renderItemsIndex,il=renderItems.length;i=lists.get(scene).length){list=new WebGLRenderList;lists.get(scene).push(list)}else{list=lists.get(scene)[renderCallDepth]}}return list}function dispose(){lists=new WeakMap}return{get:get3,dispose}}function UniformsCache(){const lights={};return{get:function(light){if(lights[light.id]!==void 0){return lights[light.id]}let uniforms;switch(light.type){case"DirectionalLight":uniforms={direction:new Vector3,color:new Color};break;case"SpotLight":uniforms={position:new Vector3,direction:new Vector3,color:new Color,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":uniforms={position:new Vector3,color:new Color,distance:0,decay:0};break;case"HemisphereLight":uniforms={direction:new Vector3,skyColor:new Color,groundColor:new Color};break;case"RectAreaLight":uniforms={color:new Color,position:new Vector3,halfWidth:new Vector3,halfHeight:new Vector3};break}lights[light.id]=uniforms;return uniforms}}}function ShadowUniformsCache(){const lights={};return{get:function(light){if(lights[light.id]!==void 0){return lights[light.id]}let uniforms;switch(light.type){case"DirectionalLight":uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"SpotLight":uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"PointLight":uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2,shadowCameraNear:1,shadowCameraFar:1e3};break}lights[light.id]=uniforms;return uniforms}}}var nextVersion=0;function shadowCastingLightsFirst(lightA,lightB){return(lightB.castShadow?1:0)-(lightA.castShadow?1:0)}function WebGLLights(extensions,capabilities){const cache=new UniformsCache;const shadowCache=ShadowUniformsCache();const state={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let i=0;i<9;i++)state.probe.push(new Vector3);const vector3=new Vector3;const matrix4=new Matrix4;const matrix42=new Matrix4;function setup(lights,physicallyCorrectLights){let r=0,g=0,b=0;for(let i=0;i<9;i++)state.probe[i].set(0,0,0);let directionalLength=0;let pointLength=0;let spotLength=0;let rectAreaLength=0;let hemiLength=0;let numDirectionalShadows=0;let numPointShadows=0;let numSpotShadows=0;lights.sort(shadowCastingLightsFirst);const scaleFactor=physicallyCorrectLights!==true?Math.PI:1;for(let i=0,l=lights.length;i0){if(capabilities.isWebGL2){state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2}else{if(extensions.has("OES_texture_float_linear")===true){state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2}else if(extensions.has("OES_texture_half_float_linear")===true){state.rectAreaLTC1=UniformsLib.LTC_HALF_1;state.rectAreaLTC2=UniformsLib.LTC_HALF_2}else{console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")}}}state.ambient[0]=r;state.ambient[1]=g;state.ambient[2]=b;const hash=state.hash;if(hash.directionalLength!==directionalLength||hash.pointLength!==pointLength||hash.spotLength!==spotLength||hash.rectAreaLength!==rectAreaLength||hash.hemiLength!==hemiLength||hash.numDirectionalShadows!==numDirectionalShadows||hash.numPointShadows!==numPointShadows||hash.numSpotShadows!==numSpotShadows){state.directional.length=directionalLength;state.spot.length=spotLength;state.rectArea.length=rectAreaLength;state.point.length=pointLength;state.hemi.length=hemiLength;state.directionalShadow.length=numDirectionalShadows;state.directionalShadowMap.length=numDirectionalShadows;state.pointShadow.length=numPointShadows;state.pointShadowMap.length=numPointShadows;state.spotShadow.length=numSpotShadows;state.spotShadowMap.length=numSpotShadows;state.directionalShadowMatrix.length=numDirectionalShadows;state.pointShadowMatrix.length=numPointShadows;state.spotShadowMatrix.length=numSpotShadows;hash.directionalLength=directionalLength;hash.pointLength=pointLength;hash.spotLength=spotLength;hash.rectAreaLength=rectAreaLength;hash.hemiLength=hemiLength;hash.numDirectionalShadows=numDirectionalShadows;hash.numPointShadows=numPointShadows;hash.numSpotShadows=numSpotShadows;state.version=nextVersion++}}function setupView(lights,camera){let directionalLength=0;let pointLength=0;let spotLength=0;let rectAreaLength=0;let hemiLength=0;const viewMatrix=camera.matrixWorldInverse;for(let i=0,l=lights.length;i=renderStates.get(scene).length){renderState=new WebGLRenderState(extensions,capabilities);renderStates.get(scene).push(renderState)}else{renderState=renderStates.get(scene)[renderCallDepth]}}return renderState}function dispose(){renderStates=new WeakMap}return{get:get3,dispose}}var MeshDepthMaterial=class extends Material{constructor(parameters){super();this.isMeshDepthMaterial=true;this.type="MeshDepthMaterial";this.depthPacking=BasicDepthPacking;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.setValues(parameters)}copy(source){super.copy(source);this.depthPacking=source.depthPacking;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;return this}};var MeshDistanceMaterial=class extends Material{constructor(parameters){super();this.isMeshDistanceMaterial=true;this.type="MeshDistanceMaterial";this.referencePosition=new Vector3;this.nearDistance=1;this.farDistance=1e3;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.setValues(parameters)}copy(source){super.copy(source);this.referencePosition.copy(source.referencePosition);this.nearDistance=source.nearDistance;this.farDistance=source.farDistance;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;return this}};var vertex="void main() {\\n gl_Position = vec4( position, 1.0 );\\n}";var fragment="uniform sampler2D shadow_pass;\\nuniform vec2 resolution;\\nuniform float radius;\\n#include \\nvoid main() {\\n const float samples = float( VSM_SAMPLES );\\n float mean = 0.0;\\n float squared_mean = 0.0;\\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\\n for ( float i = 0.0; i < samples; i ++ ) {\\n float uvOffset = uvStart + i * uvStride;\\n #ifdef HORIZONTAL_PASS\\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\\n mean += distribution.x;\\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\\n #else\\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\\n mean += depth;\\n squared_mean += depth * depth;\\n #endif\\n }\\n mean = mean / samples;\\n squared_mean = squared_mean / samples;\\n float std_dev = sqrt( squared_mean - mean * mean );\\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\\n}";function WebGLShadowMap(_renderer,_objects,_capabilities){let _frustum=new Frustum;const _shadowMapSize=new Vector2,_viewportSize=new Vector2,_viewport=new Vector4,_depthMaterial=new MeshDepthMaterial({depthPacking:RGBADepthPacking}),_distanceMaterial=new MeshDistanceMaterial,_materialCache={},_maxTextureSize=_capabilities.maxTextureSize;const shadowSide={0:BackSide,1:FrontSide,2:DoubleSide};const shadowMaterialVertical=new ShaderMaterial({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2},radius:{value:4}},vertexShader:vertex,fragmentShader:fragment});const shadowMaterialHorizontal=shadowMaterialVertical.clone();shadowMaterialHorizontal.defines.HORIZONTAL_PASS=1;const fullScreenTri=new BufferGeometry;fullScreenTri.setAttribute("position",new BufferAttribute(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const fullScreenMesh=new Mesh(fullScreenTri,shadowMaterialVertical);const scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap;this.render=function(lights,scene,camera){if(scope.enabled===false)return;if(scope.autoUpdate===false&&scope.needsUpdate===false)return;if(lights.length===0)return;const currentRenderTarget=_renderer.getRenderTarget();const activeCubeFace=_renderer.getActiveCubeFace();const activeMipmapLevel=_renderer.getActiveMipmapLevel();const _state=_renderer.state;_state.setBlending(NoBlending);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);for(let i=0,il=lights.length;i_maxTextureSize||_shadowMapSize.y>_maxTextureSize){if(_shadowMapSize.x>_maxTextureSize){_viewportSize.x=Math.floor(_maxTextureSize/shadowFrameExtents.x);_shadowMapSize.x=_viewportSize.x*shadowFrameExtents.x;shadow.mapSize.x=_viewportSize.x}if(_shadowMapSize.y>_maxTextureSize){_viewportSize.y=Math.floor(_maxTextureSize/shadowFrameExtents.y);_shadowMapSize.y=_viewportSize.y*shadowFrameExtents.y;shadow.mapSize.y=_viewportSize.y}}if(shadow.map===null){const pars=this.type!==VSMShadowMap?{minFilter:NearestFilter,magFilter:NearestFilter}:{};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+".shadowMap";shadow.camera.updateProjectionMatrix()}_renderer.setRenderTarget(shadow.map);_renderer.clear();const viewportCount=shadow.getViewportCount();for(let vp=0;vp0){const keyA=result.uuid,keyB=material.uuid;let materialsForVariant=_materialCache[keyA];if(materialsForVariant===void 0){materialsForVariant={};_materialCache[keyA]=materialsForVariant}let cachedMaterial=materialsForVariant[keyB];if(cachedMaterial===void 0){cachedMaterial=result.clone();materialsForVariant[keyB]=cachedMaterial}result=cachedMaterial}result.visible=material.visible;result.wireframe=material.wireframe;if(type===VSMShadowMap){result.side=material.shadowSide!==null?material.shadowSide:material.side}else{result.side=material.shadowSide!==null?material.shadowSide:shadowSide[material.side]}result.alphaMap=material.alphaMap;result.alphaTest=material.alphaTest;result.clipShadows=material.clipShadows;result.clippingPlanes=material.clippingPlanes;result.clipIntersection=material.clipIntersection;result.displacementMap=material.displacementMap;result.displacementScale=material.displacementScale;result.displacementBias=material.displacementBias;result.wireframeLinewidth=material.wireframeLinewidth;result.linewidth=material.linewidth;if(light.isPointLight===true&&result.isMeshDistanceMaterial===true){result.referencePosition.setFromMatrixPosition(light.matrixWorld);result.nearDistance=shadowCameraNear;result.farDistance=shadowCameraFar}return result}function renderObject(object,camera,shadowCamera,light,type){if(object.visible===false)return;const visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if((object.castShadow||object.receiveShadow&&type===VSMShadowMap)&&(!object.frustumCulled||_frustum.intersectsObject(object))){object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse,object.matrixWorld);const geometry=_objects.update(object);const material=object.material;if(Array.isArray(material)){const groups=geometry.groups;for(let k=0,kl=groups.length;k=1}else if(glVersion.indexOf("OpenGL ES")!==-1){version=parseFloat(/^OpenGL ES (\\d)/.exec(glVersion)[1]);lineWidthAvailable=version>=2}let currentTextureSlot=null;let currentBoundTextures={};const scissorParam=gl.getParameter(3088);const viewportParam=gl.getParameter(2978);const currentScissor=new Vector4().fromArray(scissorParam);const currentViewport=new Vector4().fromArray(viewportParam);function createTexture(type,target,count){const data=new Uint8Array(4);const texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(let i=0;imaxSize||image.height>maxSize){scale=maxSize/Math.max(image.width,image.height)}if(scale<1||needsPowerOfTwo===true){if(typeof HTMLImageElement!=="undefined"&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&image instanceof ImageBitmap){const floor=needsPowerOfTwo?floorPowerOfTwo:Math.floor;const width=floor(scale*image.width);const height=floor(scale*image.height);if(_canvas2===void 0)_canvas2=createCanvas(width,height);const canvas=needsNewCanvas?createCanvas(width,height):_canvas2;canvas.width=width;canvas.height=height;const context=canvas.getContext("2d");context.drawImage(image,0,0,width,height);console.warn("THREE.WebGLRenderer: Texture has been resized from ("+image.width+"x"+image.height+") to ("+width+"x"+height+").");return canvas}else{if("data"in image){console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+image.width+"x"+image.height+").")}return image}}return image}function isPowerOfTwo$1(image){return isPowerOfTwo(image.width)&&isPowerOfTwo(image.height)}function textureNeedsPowerOfTwo(texture){if(isWebGL2)return false;return texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping||texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter}function textureNeedsGenerateMipmaps(texture,supportsMips){return texture.generateMipmaps&&supportsMips&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter}function generateMipmap(target){_gl.generateMipmap(target)}function getInternalFormat(internalFormatName,glFormat,glType,encoding,isVideoTexture=false){if(isWebGL2===false)return glFormat;if(internalFormatName!==null){if(_gl[internalFormatName]!==void 0)return _gl[internalFormatName];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'"+internalFormatName+"\'")}let internalFormat=glFormat;if(glFormat===6403){if(glType===5126)internalFormat=33326;if(glType===5131)internalFormat=33325;if(glType===5121)internalFormat=33321}if(glFormat===33319){if(glType===5126)internalFormat=33328;if(glType===5131)internalFormat=33327;if(glType===5121)internalFormat=33323}if(glFormat===6408){if(glType===5126)internalFormat=34836;if(glType===5131)internalFormat=34842;if(glType===5121)internalFormat=encoding===sRGBEncoding&&isVideoTexture===false?35907:32856;if(glType===32819)internalFormat=32854;if(glType===32820)internalFormat=32855}if(internalFormat===33325||internalFormat===33326||internalFormat===33327||internalFormat===33328||internalFormat===34842||internalFormat===34836){extensions.get("EXT_color_buffer_float")}return internalFormat}function getMipLevels(texture,image,supportsMips){if(textureNeedsGenerateMipmaps(texture,supportsMips)===true||texture.isFramebufferTexture&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){return Math.log2(Math.max(image.width,image.height))+1}else if(texture.mipmaps!==void 0&&texture.mipmaps.length>0){return texture.mipmaps.length}else if(texture.isCompressedTexture&&Array.isArray(texture.image)){return image.mipmaps.length}else{return 1}}function filterFallback(f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return 9728}return 9729}function onTextureDispose(event){const texture=event.target;texture.removeEventListener("dispose",onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture)}}function onRenderTargetDispose(event){const renderTarget=event.target;renderTarget.removeEventListener("dispose",onRenderTargetDispose);deallocateRenderTarget(renderTarget)}function deallocateTexture(texture){const textureProperties=properties.get(texture);if(textureProperties.__webglInit===void 0)return;const source=texture.source;const webglTextures=_sources.get(source);if(webglTextures){const webglTexture=webglTextures[textureProperties.__cacheKey];webglTexture.usedTimes--;if(webglTexture.usedTimes===0){deleteTexture(texture)}if(Object.keys(webglTextures).length===0){_sources.delete(source)}}properties.remove(texture)}function deleteTexture(texture){const textureProperties=properties.get(texture);_gl.deleteTexture(textureProperties.__webglTexture);const source=texture.source;const webglTextures=_sources.get(source);delete webglTextures[textureProperties.__cacheKey];info2.memory.textures--}function deallocateRenderTarget(renderTarget){const texture=renderTarget.texture;const renderTargetProperties=properties.get(renderTarget);const textureProperties=properties.get(texture);if(textureProperties.__webglTexture!==void 0){_gl.deleteTexture(textureProperties.__webglTexture);info2.memory.textures--}if(renderTarget.depthTexture){renderTarget.depthTexture.dispose()}if(renderTarget.isWebGLCubeRenderTarget){for(let i=0;i<6;i++){_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i])}}else{_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);if(renderTargetProperties.__webglMultisampledFramebuffer)_gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);if(renderTargetProperties.__webglColorRenderbuffer){for(let i=0;i=maxTextures){console.warn("THREE.WebGLTextures: Trying to use "+textureUnit+" texture units while this GPU supports only "+maxTextures)}textureUnits+=1;return textureUnit}function getTextureCacheKey(texture){const array=[];array.push(texture.wrapS);array.push(texture.wrapT);array.push(texture.magFilter);array.push(texture.minFilter);array.push(texture.anisotropy);array.push(texture.internalFormat);array.push(texture.format);array.push(texture.type);array.push(texture.generateMipmaps);array.push(texture.premultiplyAlpha);array.push(texture.flipY);array.push(texture.unpackAlignment);array.push(texture.encoding);return array.join()}function setTexture2D(texture,slot){const textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(texture);if(texture.isRenderTargetTexture===false&&texture.version>0&&textureProperties.__version!==texture.version){const image=texture.image;if(image===null){console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.")}else if(image.complete===false){console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}else{uploadTexture(textureProperties,texture,slot);return}}state.activeTexture(33984+slot);state.bindTexture(3553,textureProperties.__webglTexture)}function setTexture2DArray(texture,slot){const textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return}state.activeTexture(33984+slot);state.bindTexture(35866,textureProperties.__webglTexture)}function setTexture3D(texture,slot){const textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return}state.activeTexture(33984+slot);state.bindTexture(32879,textureProperties.__webglTexture)}function setTextureCube(texture,slot){const textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadCubeTexture(textureProperties,texture,slot);return}state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture)}const wrappingToGL={[RepeatWrapping]:10497,[ClampToEdgeWrapping]:33071,[MirroredRepeatWrapping]:33648};const filterToGL={[NearestFilter]:9728,[NearestMipmapNearestFilter]:9984,[NearestMipmapLinearFilter]:9986,[LinearFilter]:9729,[LinearMipmapNearestFilter]:9985,[LinearMipmapLinearFilter]:9987};function setTextureParameters(textureType,texture,supportsMips){if(supportsMips){_gl.texParameteri(textureType,10242,wrappingToGL[texture.wrapS]);_gl.texParameteri(textureType,10243,wrappingToGL[texture.wrapT]);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,wrappingToGL[texture.wrapR])}_gl.texParameteri(textureType,10240,filterToGL[texture.magFilter]);_gl.texParameteri(textureType,10241,filterToGL[texture.minFilter])}else{_gl.texParameteri(textureType,10242,33071);_gl.texParameteri(textureType,10243,33071);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,33071)}if(texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping){console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.")}_gl.texParameteri(textureType,10240,filterFallback(texture.magFilter));_gl.texParameteri(textureType,10241,filterFallback(texture.minFilter));if(texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")}}if(extensions.has("EXT_texture_filter_anisotropic")===true){const extension=extensions.get("EXT_texture_filter_anisotropic");if(texture.type===FloatType&&extensions.has("OES_texture_float_linear")===false)return;if(isWebGL2===false&&(texture.type===HalfFloatType&&extensions.has("OES_texture_half_float_linear")===false))return;if(texture.anisotropy>1||properties.get(texture).__currentAnisotropy){_gl.texParameterf(textureType,extension.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(texture.anisotropy,capabilities.getMaxAnisotropy()));properties.get(texture).__currentAnisotropy=texture.anisotropy}}}function initTexture(textureProperties,texture){let forceUpload=false;if(textureProperties.__webglInit===void 0){textureProperties.__webglInit=true;texture.addEventListener("dispose",onTextureDispose)}const source=texture.source;let webglTextures=_sources.get(source);if(webglTextures===void 0){webglTextures={};_sources.set(source,webglTextures)}const textureCacheKey=getTextureCacheKey(texture);if(textureCacheKey!==textureProperties.__cacheKey){if(webglTextures[textureCacheKey]===void 0){webglTextures[textureCacheKey]={texture:_gl.createTexture(),usedTimes:0};info2.memory.textures++;forceUpload=true}webglTextures[textureCacheKey].usedTimes++;const webglTexture=webglTextures[textureProperties.__cacheKey];if(webglTexture!==void 0){webglTextures[textureProperties.__cacheKey].usedTimes--;if(webglTexture.usedTimes===0){deleteTexture(texture)}}textureProperties.__cacheKey=textureCacheKey;textureProperties.__webglTexture=webglTextures[textureCacheKey].texture}return forceUpload}function uploadTexture(textureProperties,texture,slot){let textureType=3553;if(texture.isDataArrayTexture)textureType=35866;if(texture.isData3DTexture)textureType=32879;const forceUpload=initTexture(textureProperties,texture);const source=texture.source;state.activeTexture(33984+slot);state.bindTexture(textureType,textureProperties.__webglTexture);if(source.version!==source.__currentVersion||forceUpload===true){_gl.pixelStorei(37440,texture.flipY);_gl.pixelStorei(37441,texture.premultiplyAlpha);_gl.pixelStorei(3317,texture.unpackAlignment);_gl.pixelStorei(37443,0);const needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo$1(texture.image)===false;let image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);image=verifyColorSpace(texture,image);const supportsMips=isPowerOfTwo$1(image)||isWebGL2,glFormat=utils.convert(texture.format,texture.encoding);let glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType,texture.encoding,texture.isVideoTexture);setTextureParameters(textureType,texture,supportsMips);let mipmap;const mipmaps=texture.mipmaps;const useTexStorage=isWebGL2&&texture.isVideoTexture!==true;const allocateMemory=source.__currentVersion===void 0||forceUpload===true;const levels=getMipLevels(texture,image,supportsMips);if(texture.isDepthTexture){glInternalFormat=6402;if(isWebGL2){if(texture.type===FloatType){glInternalFormat=36012}else if(texture.type===UnsignedIntType){glInternalFormat=33190}else if(texture.type===UnsignedInt248Type){glInternalFormat=35056}else{glInternalFormat=33189}}else{if(texture.type===FloatType){console.error("WebGLRenderer: Floating point depth texture requires WebGL2.")}}if(texture.format===DepthFormat&&glInternalFormat===6402){if(texture.type!==UnsignedShortType&&texture.type!==UnsignedIntType){console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.");texture.type=UnsignedIntType;glType=utils.convert(texture.type)}}if(texture.format===DepthStencilFormat&&glInternalFormat===6402){glInternalFormat=34041;if(texture.type!==UnsignedInt248Type){console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.");texture.type=UnsignedInt248Type;glType=utils.convert(texture.type)}}if(allocateMemory){if(useTexStorage){state.texStorage2D(3553,1,glInternalFormat,image.width,image.height)}else{state.texImage2D(3553,0,glInternalFormat,image.width,image.height,0,glFormat,glType,null)}}}else if(texture.isDataTexture){if(mipmaps.length>0&&supportsMips){if(useTexStorage&&allocateMemory){state.texStorage2D(3553,levels,glInternalFormat,mipmaps[0].width,mipmaps[0].height)}for(let i=0,il=mipmaps.length;i>=1;height>>=1}}}}else{if(mipmaps.length>0&&supportsMips){if(useTexStorage&&allocateMemory){state.texStorage2D(3553,levels,glInternalFormat,mipmaps[0].width,mipmaps[0].height)}for(let i=0,il=mipmaps.length;i0)levels++;state.texStorage2D(34067,levels,glInternalFormat,cubeImage[0].width,cubeImage[0].height)}for(let i=0;i<6;i++){if(isDataTexture){if(useTexStorage){state.texSubImage2D(34069+i,0,0,0,cubeImage[i].width,cubeImage[i].height,glFormat,glType,cubeImage[i].data)}else{state.texImage2D(34069+i,0,glInternalFormat,cubeImage[i].width,cubeImage[i].height,0,glFormat,glType,cubeImage[i].data)}for(let j=0;j0&&useMultisampledRTT(renderTarget)===false){const textures=isMultipleRenderTargets?texture:[texture];renderTargetProperties.__webglMultisampledFramebuffer=_gl.createFramebuffer();renderTargetProperties.__webglColorRenderbuffer=[];state.bindFramebuffer(36160,renderTargetProperties.__webglMultisampledFramebuffer);for(let i=0;i0&&useMultisampledRTT(renderTarget)===false){const textures=renderTarget.isWebGLMultipleRenderTargets?renderTarget.texture:[renderTarget.texture];const width=renderTarget.width;const height=renderTarget.height;let mask=16384;const invalidationArray=[];const depthStyle=renderTarget.stencilBuffer?33306:36096;const renderTargetProperties=properties.get(renderTarget);const isMultipleRenderTargets=renderTarget.isWebGLMultipleRenderTargets===true;if(isMultipleRenderTargets){for(let i=0;i0&&extensions.has("WEBGL_multisampled_render_to_texture")===true&&renderTargetProperties.__useRenderToTexture!==false}function updateVideoTexture(texture){const frame=info2.render.frame;if(_videoTextures.get(texture)!==frame){_videoTextures.set(texture,frame);texture.update()}}function verifyColorSpace(texture,image){const encoding=texture.encoding;const format=texture.format;const type=texture.type;if(texture.isCompressedTexture===true||texture.isVideoTexture===true||texture.format===_SRGBAFormat)return image;if(encoding!==LinearEncoding){if(encoding===sRGBEncoding){if(isWebGL2===false){if(extensions.has("EXT_sRGB")===true&&format===RGBAFormat){texture.format=_SRGBAFormat;texture.minFilter=LinearFilter;texture.generateMipmaps=false}else{image=ImageUtils.sRGBToLinear(image)}}else{if(format!==RGBAFormat||type!==UnsignedByteType){console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}}}else{console.error("THREE.WebGLTextures: Unsupported texture encoding:",encoding)}}return image}this.allocateTextureUnit=allocateTextureUnit;this.resetTextureUnits=resetTextureUnits;this.setTexture2D=setTexture2D;this.setTexture2DArray=setTexture2DArray;this.setTexture3D=setTexture3D;this.setTextureCube=setTextureCube;this.rebindTextures=rebindTextures;this.setupRenderTarget=setupRenderTarget;this.updateRenderTargetMipmap=updateRenderTargetMipmap;this.updateMultisampleRenderTarget=updateMultisampleRenderTarget;this.setupDepthRenderbuffer=setupDepthRenderbuffer;this.setupFrameBufferTexture=setupFrameBufferTexture;this.useMultisampledRTT=useMultisampledRTT}function WebGLUtils(gl,extensions,capabilities){const isWebGL2=capabilities.isWebGL2;function convert(p,encoding=null){let extension;if(p===UnsignedByteType)return 5121;if(p===UnsignedShort4444Type)return 32819;if(p===UnsignedShort5551Type)return 32820;if(p===ByteType)return 5120;if(p===ShortType)return 5122;if(p===UnsignedShortType)return 5123;if(p===IntType)return 5124;if(p===UnsignedIntType)return 5125;if(p===FloatType)return 5126;if(p===HalfFloatType){if(isWebGL2)return 5131;extension=extensions.get("OES_texture_half_float");if(extension!==null){return extension.HALF_FLOAT_OES}else{return null}}if(p===AlphaFormat)return 6406;if(p===RGBAFormat)return 6408;if(p===LuminanceFormat)return 6409;if(p===LuminanceAlphaFormat)return 6410;if(p===DepthFormat)return 6402;if(p===DepthStencilFormat)return 34041;if(p===RedFormat)return 6403;if(p===RGBFormat){console.warn("THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228");return 6408}if(p===_SRGBAFormat){extension=extensions.get("EXT_sRGB");if(extension!==null){return extension.SRGB_ALPHA_EXT}else{return null}}if(p===RedIntegerFormat)return 36244;if(p===RGFormat)return 33319;if(p===RGIntegerFormat)return 33320;if(p===RGBAIntegerFormat)return 36249;if(p===RGB_S3TC_DXT1_Format||p===RGBA_S3TC_DXT1_Format||p===RGBA_S3TC_DXT3_Format||p===RGBA_S3TC_DXT5_Format){if(encoding===sRGBEncoding){extension=extensions.get("WEBGL_compressed_texture_s3tc_srgb");if(extension!==null){if(p===RGB_S3TC_DXT1_Format)return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT1_Format)return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT3_Format)return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(p===RGBA_S3TC_DXT5_Format)return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{return null}}else{extension=extensions.get("WEBGL_compressed_texture_s3tc");if(extension!==null){if(p===RGB_S3TC_DXT1_Format)return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT1_Format)return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT3_Format)return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(p===RGBA_S3TC_DXT5_Format)return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT}else{return null}}}if(p===RGB_PVRTC_4BPPV1_Format||p===RGB_PVRTC_2BPPV1_Format||p===RGBA_PVRTC_4BPPV1_Format||p===RGBA_PVRTC_2BPPV1_Format){extension=extensions.get("WEBGL_compressed_texture_pvrtc");if(extension!==null){if(p===RGB_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(p===RGB_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(p===RGBA_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(p===RGBA_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else{return null}}if(p===RGB_ETC1_Format){extension=extensions.get("WEBGL_compressed_texture_etc1");if(extension!==null){return extension.COMPRESSED_RGB_ETC1_WEBGL}else{return null}}if(p===RGB_ETC2_Format||p===RGBA_ETC2_EAC_Format){extension=extensions.get("WEBGL_compressed_texture_etc");if(extension!==null){if(p===RGB_ETC2_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ETC2:extension.COMPRESSED_RGB8_ETC2;if(p===RGBA_ETC2_EAC_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:extension.COMPRESSED_RGBA8_ETC2_EAC}else{return null}}if(p===RGBA_ASTC_4x4_Format||p===RGBA_ASTC_5x4_Format||p===RGBA_ASTC_5x5_Format||p===RGBA_ASTC_6x5_Format||p===RGBA_ASTC_6x6_Format||p===RGBA_ASTC_8x5_Format||p===RGBA_ASTC_8x6_Format||p===RGBA_ASTC_8x8_Format||p===RGBA_ASTC_10x5_Format||p===RGBA_ASTC_10x6_Format||p===RGBA_ASTC_10x8_Format||p===RGBA_ASTC_10x10_Format||p===RGBA_ASTC_12x10_Format||p===RGBA_ASTC_12x12_Format){extension=extensions.get("WEBGL_compressed_texture_astc");if(extension!==null){if(p===RGBA_ASTC_4x4_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:extension.COMPRESSED_RGBA_ASTC_4x4_KHR;if(p===RGBA_ASTC_5x4_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:extension.COMPRESSED_RGBA_ASTC_5x4_KHR;if(p===RGBA_ASTC_5x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:extension.COMPRESSED_RGBA_ASTC_5x5_KHR;if(p===RGBA_ASTC_6x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:extension.COMPRESSED_RGBA_ASTC_6x5_KHR;if(p===RGBA_ASTC_6x6_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:extension.COMPRESSED_RGBA_ASTC_6x6_KHR;if(p===RGBA_ASTC_8x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:extension.COMPRESSED_RGBA_ASTC_8x5_KHR;if(p===RGBA_ASTC_8x6_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:extension.COMPRESSED_RGBA_ASTC_8x6_KHR;if(p===RGBA_ASTC_8x8_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:extension.COMPRESSED_RGBA_ASTC_8x8_KHR;if(p===RGBA_ASTC_10x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:extension.COMPRESSED_RGBA_ASTC_10x5_KHR;if(p===RGBA_ASTC_10x6_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:extension.COMPRESSED_RGBA_ASTC_10x6_KHR;if(p===RGBA_ASTC_10x8_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:extension.COMPRESSED_RGBA_ASTC_10x8_KHR;if(p===RGBA_ASTC_10x10_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:extension.COMPRESSED_RGBA_ASTC_10x10_KHR;if(p===RGBA_ASTC_12x10_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:extension.COMPRESSED_RGBA_ASTC_12x10_KHR;if(p===RGBA_ASTC_12x12_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:extension.COMPRESSED_RGBA_ASTC_12x12_KHR}else{return null}}if(p===RGBA_BPTC_Format){extension=extensions.get("EXT_texture_compression_bptc");if(extension!==null){if(p===RGBA_BPTC_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:extension.COMPRESSED_RGBA_BPTC_UNORM_EXT}else{return null}}if(p===UnsignedInt248Type){if(isWebGL2)return 34042;extension=extensions.get("WEBGL_depth_texture");if(extension!==null){return extension.UNSIGNED_INT_24_8_WEBGL}else{return null}}return gl[p]!==void 0?gl[p]:null}return{convert}}var ArrayCamera=class extends PerspectiveCamera{constructor(array=[]){super();this.isArrayCamera=true;this.cameras=array}};var Group=class extends Object3D{constructor(){super();this.isGroup=true;this.type="Group"}};var _moveEvent={type:"move"};var WebXRController=class{constructor(){this._targetRay=null;this._grip=null;this._hand=null}getHandSpace(){if(this._hand===null){this._hand=new Group;this._hand.matrixAutoUpdate=false;this._hand.visible=false;this._hand.joints={};this._hand.inputState={pinching:false}}return this._hand}getTargetRaySpace(){if(this._targetRay===null){this._targetRay=new Group;this._targetRay.matrixAutoUpdate=false;this._targetRay.visible=false;this._targetRay.hasLinearVelocity=false;this._targetRay.linearVelocity=new Vector3;this._targetRay.hasAngularVelocity=false;this._targetRay.angularVelocity=new Vector3}return this._targetRay}getGripSpace(){if(this._grip===null){this._grip=new Group;this._grip.matrixAutoUpdate=false;this._grip.visible=false;this._grip.hasLinearVelocity=false;this._grip.linearVelocity=new Vector3;this._grip.hasAngularVelocity=false;this._grip.angularVelocity=new Vector3}return this._grip}dispatchEvent(event){if(this._targetRay!==null){this._targetRay.dispatchEvent(event)}if(this._grip!==null){this._grip.dispatchEvent(event)}if(this._hand!==null){this._hand.dispatchEvent(event)}return this}disconnect(inputSource){this.dispatchEvent({type:"disconnected",data:inputSource});if(this._targetRay!==null){this._targetRay.visible=false}if(this._grip!==null){this._grip.visible=false}if(this._hand!==null){this._hand.visible=false}return this}update(inputSource,frame,referenceSpace){let inputPose=null;let gripPose=null;let handPose=null;const targetRay=this._targetRay;const grip=this._grip;const hand=this._hand;if(inputSource&&frame.session.visibilityState!=="visible-blurred"){if(hand&&inputSource.hand){handPose=true;for(const inputjoint of inputSource.hand.values()){const jointPose=frame.getJointPose(inputjoint,referenceSpace);if(hand.joints[inputjoint.jointName]===void 0){const joint2=new Group;joint2.matrixAutoUpdate=false;joint2.visible=false;hand.joints[inputjoint.jointName]=joint2;hand.add(joint2)}const joint=hand.joints[inputjoint.jointName];if(jointPose!==null){joint.matrix.fromArray(jointPose.transform.matrix);joint.matrix.decompose(joint.position,joint.rotation,joint.scale);joint.jointRadius=jointPose.radius}joint.visible=jointPose!==null}const indexTip=hand.joints["index-finger-tip"];const thumbTip=hand.joints["thumb-tip"];const distance=indexTip.position.distanceTo(thumbTip.position);const distanceToPinch=.02;const threshold=.005;if(hand.inputState.pinching&&distance>distanceToPinch+threshold){hand.inputState.pinching=false;this.dispatchEvent({type:"pinchend",handedness:inputSource.handedness,target:this})}else if(!hand.inputState.pinching&&distance<=distanceToPinch-threshold){hand.inputState.pinching=true;this.dispatchEvent({type:"pinchstart",handedness:inputSource.handedness,target:this})}}else{if(grip!==null&&inputSource.gripSpace){gripPose=frame.getPose(inputSource.gripSpace,referenceSpace);if(gripPose!==null){grip.matrix.fromArray(gripPose.transform.matrix);grip.matrix.decompose(grip.position,grip.rotation,grip.scale);if(gripPose.linearVelocity){grip.hasLinearVelocity=true;grip.linearVelocity.copy(gripPose.linearVelocity)}else{grip.hasLinearVelocity=false}if(gripPose.angularVelocity){grip.hasAngularVelocity=true;grip.angularVelocity.copy(gripPose.angularVelocity)}else{grip.hasAngularVelocity=false}}}}if(targetRay!==null){inputPose=frame.getPose(inputSource.targetRaySpace,referenceSpace);if(inputPose===null&&gripPose!==null){inputPose=gripPose}if(inputPose!==null){targetRay.matrix.fromArray(inputPose.transform.matrix);targetRay.matrix.decompose(targetRay.position,targetRay.rotation,targetRay.scale);if(inputPose.linearVelocity){targetRay.hasLinearVelocity=true;targetRay.linearVelocity.copy(inputPose.linearVelocity)}else{targetRay.hasLinearVelocity=false}if(inputPose.angularVelocity){targetRay.hasAngularVelocity=true;targetRay.angularVelocity.copy(inputPose.angularVelocity)}else{targetRay.hasAngularVelocity=false}this.dispatchEvent(_moveEvent)}}}if(targetRay!==null){targetRay.visible=inputPose!==null}if(grip!==null){grip.visible=gripPose!==null}if(hand!==null){hand.visible=handPose!==null}return this}};var DepthTexture=class extends Texture{constructor(width,height,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,format){format=format!==void 0?format:DepthFormat;if(format!==DepthFormat&&format!==DepthStencilFormat){throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat")}if(type===void 0&&format===DepthFormat)type=UnsignedIntType;if(type===void 0&&format===DepthStencilFormat)type=UnsignedInt248Type;super(null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.isDepthTexture=true;this.image={width,height};this.magFilter=magFilter!==void 0?magFilter:NearestFilter;this.minFilter=minFilter!==void 0?minFilter:NearestFilter;this.flipY=false;this.generateMipmaps=false}};var WebXRManager=class extends EventDispatcher2{constructor(renderer,gl){super();const scope=this;let session=null;let framebufferScaleFactor=1;let referenceSpace=null;let referenceSpaceType="local-floor";let customReferenceSpace=null;let pose=null;let glBinding=null;let glProjLayer=null;let glBaseLayer=null;let xrFrame=null;const attributes=gl.getContextAttributes();let initialRenderTarget=null;let newRenderTarget=null;const controllers=[];const controllerInputSources=[];const cameraL=new PerspectiveCamera;cameraL.layers.enable(1);cameraL.viewport=new Vector4;const cameraR=new PerspectiveCamera;cameraR.layers.enable(2);cameraR.viewport=new Vector4;const cameras=[cameraL,cameraR];const cameraVR=new ArrayCamera;cameraVR.layers.enable(1);cameraVR.layers.enable(2);let _currentDepthNear=null;let _currentDepthFar=null;this.cameraAutoUpdate=true;this.enabled=false;this.isPresenting=false;this.getController=function(index){let controller=controllers[index];if(controller===void 0){controller=new WebXRController;controllers[index]=controller}return controller.getTargetRaySpace()};this.getControllerGrip=function(index){let controller=controllers[index];if(controller===void 0){controller=new WebXRController;controllers[index]=controller}return controller.getGripSpace()};this.getHand=function(index){let controller=controllers[index];if(controller===void 0){controller=new WebXRController;controllers[index]=controller}return controller.getHandSpace()};function onSessionEvent(event){const controllerIndex=controllerInputSources.indexOf(event.inputSource);if(controllerIndex===-1){return}const controller=controllers[controllerIndex];if(controller!==void 0){controller.dispatchEvent({type:event.type,data:event.inputSource})}}function onSessionEnd(){session.removeEventListener("select",onSessionEvent);session.removeEventListener("selectstart",onSessionEvent);session.removeEventListener("selectend",onSessionEvent);session.removeEventListener("squeeze",onSessionEvent);session.removeEventListener("squeezestart",onSessionEvent);session.removeEventListener("squeezeend",onSessionEvent);session.removeEventListener("end",onSessionEnd);session.removeEventListener("inputsourceschange",onInputSourcesChange);for(let i=0;i=0){controllerInputSources[index]=null;controllers[index].dispatchEvent({type:"disconnected",data:inputSource})}}for(let i=0;i=controllerInputSources.length){controllerInputSources.push(inputSource);controllerIndex=i2;break}else if(controllerInputSources[i2]===null){controllerInputSources[i2]=inputSource;controllerIndex=i2;break}}if(controllerIndex===-1)break}const controller=controllers[controllerIndex];if(controller){controller.dispatchEvent({type:"connected",data:inputSource})}}}const cameraLPos=new Vector3;const cameraRPos=new Vector3;function setProjectionFromUnion(camera,cameraL2,cameraR2){cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld);cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld);const ipd=cameraLPos.distanceTo(cameraRPos);const projL=cameraL2.projectionMatrix.elements;const projR=cameraR2.projectionMatrix.elements;const near=projL[14]/(projL[10]-1);const far=projL[14]/(projL[10]+1);const topFov=(projL[9]+1)/projL[5];const bottomFov=(projL[9]-1)/projL[5];const leftFov=(projL[8]-1)/projL[0];const rightFov=(projR[8]+1)/projR[0];const left=near*leftFov;const right=near*rightFov;const zOffset=ipd/(-leftFov+rightFov);const xOffset=zOffset*-leftFov;cameraL2.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);camera.translateX(xOffset);camera.translateZ(zOffset);camera.matrixWorld.compose(camera.position,camera.quaternion,camera.scale);camera.matrixWorldInverse.copy(camera.matrixWorld).invert();const near2=near+zOffset;const far2=far+zOffset;const left2=left-xOffset;const right2=right+(ipd-xOffset);const top2=topFov*far/far2*near2;const bottom2=bottomFov*far/far2*near2;camera.projectionMatrix.makePerspective(left2,right2,top2,bottom2,near2,far2)}function updateCamera(camera,parent){if(parent===null){camera.matrixWorld.copy(camera.matrix)}else{camera.matrixWorld.multiplyMatrices(parent.matrixWorld,camera.matrix)}camera.matrixWorldInverse.copy(camera.matrixWorld).invert()}this.updateCamera=function(camera){if(session===null)return;cameraVR.near=cameraR.near=cameraL.near=camera.near;cameraVR.far=cameraR.far=cameraL.far=camera.far;if(_currentDepthNear!==cameraVR.near||_currentDepthFar!==cameraVR.far){session.updateRenderState({depthNear:cameraVR.near,depthFar:cameraVR.far});_currentDepthNear=cameraVR.near;_currentDepthFar=cameraVR.far}const parent=camera.parent;const cameras2=cameraVR.cameras;updateCamera(cameraVR,parent);for(let i=0;i0){uniforms.alphaTest.value=material.alphaTest}const envMap=properties.get(material).envMap;if(envMap){uniforms.envMap.value=envMap;uniforms.flipEnvMap.value=envMap.isCubeTexture&&envMap.isRenderTargetTexture===false?-1:1;uniforms.reflectivity.value=material.reflectivity;uniforms.ior.value=material.ior;uniforms.refractionRatio.value=material.refractionRatio}if(material.lightMap){uniforms.lightMap.value=material.lightMap;const scaleFactor=renderer.physicallyCorrectLights!==true?Math.PI:1;uniforms.lightMapIntensity.value=material.lightMapIntensity*scaleFactor}if(material.aoMap){uniforms.aoMap.value=material.aoMap;uniforms.aoMapIntensity.value=material.aoMapIntensity}let uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.specularMap){uvScaleMap=material.specularMap}else if(material.displacementMap){uvScaleMap=material.displacementMap}else if(material.normalMap){uvScaleMap=material.normalMap}else if(material.bumpMap){uvScaleMap=material.bumpMap}else if(material.roughnessMap){uvScaleMap=material.roughnessMap}else if(material.metalnessMap){uvScaleMap=material.metalnessMap}else if(material.alphaMap){uvScaleMap=material.alphaMap}else if(material.emissiveMap){uvScaleMap=material.emissiveMap}else if(material.clearcoatMap){uvScaleMap=material.clearcoatMap}else if(material.clearcoatNormalMap){uvScaleMap=material.clearcoatNormalMap}else if(material.clearcoatRoughnessMap){uvScaleMap=material.clearcoatRoughnessMap}else if(material.iridescenceMap){uvScaleMap=material.iridescenceMap}else if(material.iridescenceThicknessMap){uvScaleMap=material.iridescenceThicknessMap}else if(material.specularIntensityMap){uvScaleMap=material.specularIntensityMap}else if(material.specularColorMap){uvScaleMap=material.specularColorMap}else if(material.transmissionMap){uvScaleMap=material.transmissionMap}else if(material.thicknessMap){uvScaleMap=material.thicknessMap}else if(material.sheenColorMap){uvScaleMap=material.sheenColorMap}else if(material.sheenRoughnessMap){uvScaleMap=material.sheenRoughnessMap}if(uvScaleMap!==void 0){if(uvScaleMap.isWebGLRenderTarget){uvScaleMap=uvScaleMap.texture}if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix()}uniforms.uvTransform.value.copy(uvScaleMap.matrix)}let uv2ScaleMap;if(material.aoMap){uv2ScaleMap=material.aoMap}else if(material.lightMap){uv2ScaleMap=material.lightMap}if(uv2ScaleMap!==void 0){if(uv2ScaleMap.isWebGLRenderTarget){uv2ScaleMap=uv2ScaleMap.texture}if(uv2ScaleMap.matrixAutoUpdate===true){uv2ScaleMap.updateMatrix()}uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix)}}function refreshUniformsLine(uniforms,material){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity}function refreshUniformsDash(uniforms,material){uniforms.dashSize.value=material.dashSize;uniforms.totalSize.value=material.dashSize+material.gapSize;uniforms.scale.value=material.scale}function refreshUniformsPoints(uniforms,material,pixelRatio,height){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;uniforms.size.value=material.size*pixelRatio;uniforms.scale.value=height*.5;if(material.map){uniforms.map.value=material.map}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap}if(material.alphaTest>0){uniforms.alphaTest.value=material.alphaTest}let uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.alphaMap){uvScaleMap=material.alphaMap}if(uvScaleMap!==void 0){if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix()}uniforms.uvTransform.value.copy(uvScaleMap.matrix)}}function refreshUniformsSprites(uniforms,material){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;uniforms.rotation.value=material.rotation;if(material.map){uniforms.map.value=material.map}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap}if(material.alphaTest>0){uniforms.alphaTest.value=material.alphaTest}let uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.alphaMap){uvScaleMap=material.alphaMap}if(uvScaleMap!==void 0){if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix()}uniforms.uvTransform.value.copy(uvScaleMap.matrix)}}function refreshUniformsPhong(uniforms,material){uniforms.specular.value.copy(material.specular);uniforms.shininess.value=Math.max(material.shininess,1e-4)}function refreshUniformsToon(uniforms,material){if(material.gradientMap){uniforms.gradientMap.value=material.gradientMap}}function refreshUniformsStandard(uniforms,material){uniforms.roughness.value=material.roughness;uniforms.metalness.value=material.metalness;if(material.roughnessMap){uniforms.roughnessMap.value=material.roughnessMap}if(material.metalnessMap){uniforms.metalnessMap.value=material.metalnessMap}const envMap=properties.get(material).envMap;if(envMap){uniforms.envMapIntensity.value=material.envMapIntensity}}function refreshUniformsPhysical(uniforms,material,transmissionRenderTarget){uniforms.ior.value=material.ior;if(material.sheen>0){uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);uniforms.sheenRoughness.value=material.sheenRoughness;if(material.sheenColorMap){uniforms.sheenColorMap.value=material.sheenColorMap}if(material.sheenRoughnessMap){uniforms.sheenRoughnessMap.value=material.sheenRoughnessMap}}if(material.clearcoat>0){uniforms.clearcoat.value=material.clearcoat;uniforms.clearcoatRoughness.value=material.clearcoatRoughness;if(material.clearcoatMap){uniforms.clearcoatMap.value=material.clearcoatMap}if(material.clearcoatRoughnessMap){uniforms.clearcoatRoughnessMap.value=material.clearcoatRoughnessMap}if(material.clearcoatNormalMap){uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);uniforms.clearcoatNormalMap.value=material.clearcoatNormalMap;if(material.side===BackSide){uniforms.clearcoatNormalScale.value.negate()}}}if(material.iridescence>0){uniforms.iridescence.value=material.iridescence;uniforms.iridescenceIOR.value=material.iridescenceIOR;uniforms.iridescenceThicknessMinimum.value=material.iridescenceThicknessRange[0];uniforms.iridescenceThicknessMaximum.value=material.iridescenceThicknessRange[1];if(material.iridescenceMap){uniforms.iridescenceMap.value=material.iridescenceMap}if(material.iridescenceThicknessMap){uniforms.iridescenceThicknessMap.value=material.iridescenceThicknessMap}}if(material.transmission>0){uniforms.transmission.value=material.transmission;uniforms.transmissionSamplerMap.value=transmissionRenderTarget.texture;uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width,transmissionRenderTarget.height);if(material.transmissionMap){uniforms.transmissionMap.value=material.transmissionMap}uniforms.thickness.value=material.thickness;if(material.thicknessMap){uniforms.thicknessMap.value=material.thicknessMap}uniforms.attenuationDistance.value=material.attenuationDistance;uniforms.attenuationColor.value.copy(material.attenuationColor)}uniforms.specularIntensity.value=material.specularIntensity;uniforms.specularColor.value.copy(material.specularColor);if(material.specularIntensityMap){uniforms.specularIntensityMap.value=material.specularIntensityMap}if(material.specularColorMap){uniforms.specularColorMap.value=material.specularColorMap}}function refreshUniformsMatcap(uniforms,material){if(material.matcap){uniforms.matcap.value=material.matcap}}function refreshUniformsDistance(uniforms,material){uniforms.referencePosition.value.copy(material.referencePosition);uniforms.nearDistance.value=material.nearDistance;uniforms.farDistance.value=material.farDistance}return{refreshFogUniforms,refreshMaterialUniforms}}function WebGLUniformsGroups(gl,info2,capabilities,state){let buffers={};let updateList={};let allocatedBindingPoints=[];const maxBindingPoints=capabilities.isWebGL2?gl.getParameter(35375):0;function bind(uniformsGroup,program){const webglProgram=program.program;state.uniformBlockBinding(uniformsGroup,webglProgram)}function update(uniformsGroup,program){let buffer=buffers[uniformsGroup.id];if(buffer===void 0){prepareUniformsGroup(uniformsGroup);buffer=createBuffer(uniformsGroup);buffers[uniformsGroup.id]=buffer;uniformsGroup.addEventListener("dispose",onUniformsGroupsDispose)}const webglProgram=program.program;state.updateUBOMapping(uniformsGroup,webglProgram);const frame=info2.render.frame;if(updateList[uniformsGroup.id]!==frame){updateBufferData(uniformsGroup);updateList[uniformsGroup.id]=frame}}function createBuffer(uniformsGroup){const bindingPointIndex=allocateBindingPointIndex();uniformsGroup.__bindingPointIndex=bindingPointIndex;const buffer=gl.createBuffer();const size=uniformsGroup.__size;const usage=uniformsGroup.usage;gl.bindBuffer(35345,buffer);gl.bufferData(35345,size,usage);gl.bindBuffer(35345,null);gl.bindBufferBase(35345,bindingPointIndex,buffer);return buffer}function allocateBindingPointIndex(){for(let i=0;i0){chunkOffset=offset%chunkSize;const remainingSizeInChunk=chunkSize-chunkOffset;if(chunkOffset!==0&&remainingSizeInChunk-info3.boundary<0){offset+=chunkSize-chunkOffset;uniform.__offset=offset}}offset+=info3.storage}chunkOffset=offset%chunkSize;if(chunkOffset>0)offset+=chunkSize-chunkOffset;uniformsGroup.__size=offset;uniformsGroup.__cache={};return this}function getUniformSize(uniform){const value=uniform.value;const info3={boundary:0,storage:0};if(typeof value==="number"){info3.boundary=4;info3.storage=4}else if(value.isVector2){info3.boundary=8;info3.storage=8}else if(value.isVector3||value.isColor){info3.boundary=16;info3.storage=12}else if(value.isVector4){info3.boundary=16;info3.storage=16}else if(value.isMatrix3){info3.boundary=48;info3.storage=48}else if(value.isMatrix4){info3.boundary=64;info3.storage=64}else if(value.isTexture){console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.")}else{console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",value)}return info3}function onUniformsGroupsDispose(event){const uniformsGroup=event.target;uniformsGroup.removeEventListener("dispose",onUniformsGroupsDispose);const index=allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);allocatedBindingPoints.splice(index,1);gl.deleteBuffer(buffers[uniformsGroup.id]);delete buffers[uniformsGroup.id];delete updateList[uniformsGroup.id]}function dispose(){for(const id2 in buffers){gl.deleteBuffer(buffers[id2])}allocatedBindingPoints=[];buffers={};updateList={}}return{bind,update,dispose}}function createCanvasElement(){const canvas=createElementNS("canvas");canvas.style.display="block";return canvas}function WebGLRenderer(parameters={}){this.isWebGLRenderer=true;const _canvas2=parameters.canvas!==void 0?parameters.canvas:createCanvasElement(),_context2=parameters.context!==void 0?parameters.context:null,_depth=parameters.depth!==void 0?parameters.depth:true,_stencil=parameters.stencil!==void 0?parameters.stencil:true,_antialias=parameters.antialias!==void 0?parameters.antialias:false,_premultipliedAlpha=parameters.premultipliedAlpha!==void 0?parameters.premultipliedAlpha:true,_preserveDrawingBuffer=parameters.preserveDrawingBuffer!==void 0?parameters.preserveDrawingBuffer:false,_powerPreference=parameters.powerPreference!==void 0?parameters.powerPreference:"default",_failIfMajorPerformanceCaveat=parameters.failIfMajorPerformanceCaveat!==void 0?parameters.failIfMajorPerformanceCaveat:false;let _alpha;if(_context2!==null){_alpha=_context2.getContextAttributes().alpha}else{_alpha=parameters.alpha!==void 0?parameters.alpha:false}let currentRenderList=null;let currentRenderState=null;const renderListStack=[];const renderStateStack=[];this.domElement=_canvas2;this.debug={checkShaderErrors:true};this.autoClear=true;this.autoClearColor=true;this.autoClearDepth=true;this.autoClearStencil=true;this.sortObjects=true;this.clippingPlanes=[];this.localClippingEnabled=false;this.outputEncoding=LinearEncoding;this.physicallyCorrectLights=false;this.toneMapping=NoToneMapping;this.toneMappingExposure=1;Object.defineProperties(this,{gammaFactor:{get:function(){console.warn("THREE.WebGLRenderer: .gammaFactor has been removed.");return 2},set:function(){console.warn("THREE.WebGLRenderer: .gammaFactor has been removed.")}}});const _this=this;let _isContextLost=false;let _currentActiveCubeFace=0;let _currentActiveMipmapLevel=0;let _currentRenderTarget=null;let _currentMaterialId=-1;let _currentCamera=null;const _currentViewport=new Vector4;const _currentScissor=new Vector4;let _currentScissorTest=null;let _width=_canvas2.width;let _height=_canvas2.height;let _pixelRatio=1;let _opaqueSort=null;let _transparentSort=null;const _viewport=new Vector4(0,0,_width,_height);const _scissor=new Vector4(0,0,_width,_height);let _scissorTest=false;const _frustum=new Frustum;let _clippingEnabled=false;let _localClippingEnabled=false;let _transmissionRenderTarget=null;const _projScreenMatrix2=new Matrix4;const _vector22=new Vector2;const _vector3=new Vector3;const _emptyScene={background:null,fog:null,environment:null,overrideMaterial:null,isScene:true};function getTargetPixelRatio(){return _currentRenderTarget===null?_pixelRatio:1}let _gl=_context2;function getContext(contextNames,contextAttributes){for(let i=0;i0){currentRenderState=renderStateStack[renderStateStack.length-1]}else{currentRenderState=null}renderListStack.pop();if(renderListStack.length>0){currentRenderList=renderListStack[renderListStack.length-1]}else{currentRenderList=null}};function projectObject(object,camera,groupOrder,sortObjects){if(object.visible===false)return;const visible=object.layers.test(camera.layers);if(visible){if(object.isGroup){groupOrder=object.renderOrder}else if(object.isLOD){if(object.autoUpdate===true)object.update(camera)}else if(object.isLight){currentRenderState.pushLight(object);if(object.castShadow){currentRenderState.pushShadow(object)}}else if(object.isSprite){if(!object.frustumCulled||_frustum.intersectsSprite(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2)}const geometry=objects2.update(object);const material=object.material;if(material.visible){currentRenderList.push(object,geometry,material,groupOrder,_vector3.z,null)}}}else if(object.isMesh||object.isLine||object.isPoints){if(object.isSkinnedMesh){if(object.skeleton.frame!==info2.render.frame){object.skeleton.update();object.skeleton.frame=info2.render.frame}}if(!object.frustumCulled||_frustum.intersectsObject(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2)}const geometry=objects2.update(object);const material=object.material;if(Array.isArray(material)){const groups=geometry.groups;for(let i=0,l=groups.length;i0)renderTransmissionPass(opaqueObjects,scene,camera);if(viewport)state.viewport(_currentViewport.copy(viewport));if(opaqueObjects.length>0)renderObjects(opaqueObjects,scene,camera);if(transmissiveObjects.length>0)renderObjects(transmissiveObjects,scene,camera);if(transparentObjects.length>0)renderObjects(transparentObjects,scene,camera);state.buffers.depth.setTest(true);state.buffers.depth.setMask(true);state.buffers.color.setMask(true);state.setPolygonOffset(false)}function renderTransmissionPass(opaqueObjects,scene,camera){const isWebGL2=capabilities.isWebGL2;if(_transmissionRenderTarget===null){_transmissionRenderTarget=new WebGLRenderTarget(1,1,{generateMipmaps:true,type:extensions.has("EXT_color_buffer_half_float")?HalfFloatType:UnsignedByteType,minFilter:LinearMipmapLinearFilter,samples:isWebGL2&&_antialias===true?4:0})}_this.getDrawingBufferSize(_vector22);if(isWebGL2){_transmissionRenderTarget.setSize(_vector22.x,_vector22.y)}else{_transmissionRenderTarget.setSize(floorPowerOfTwo(_vector22.x),floorPowerOfTwo(_vector22.y))}const currentRenderTarget=_this.getRenderTarget();_this.setRenderTarget(_transmissionRenderTarget);_this.clear();const currentToneMapping=_this.toneMapping;_this.toneMapping=NoToneMapping;renderObjects(opaqueObjects,scene,camera);_this.toneMapping=currentToneMapping;textures.updateMultisampleRenderTarget(_transmissionRenderTarget);textures.updateRenderTargetMipmap(_transmissionRenderTarget);_this.setRenderTarget(currentRenderTarget)}function renderObjects(renderList,scene,camera){const overrideMaterial=scene.isScene===true?scene.overrideMaterial:null;for(let i=0,l=renderList.length;i0&&textures.useMultisampledRTT(renderTarget)===false){framebuffer=properties.get(renderTarget).__webglMultisampledFramebuffer}else{framebuffer=__webglFramebuffer}_currentViewport.copy(renderTarget.viewport);_currentScissor.copy(renderTarget.scissor);_currentScissorTest=renderTarget.scissorTest}else{_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();_currentScissorTest=_scissorTest}const framebufferBound=state.bindFramebuffer(36160,framebuffer);if(framebufferBound&&capabilities.drawBuffers&&useDefaultFramebuffer){state.drawBuffers(renderTarget,framebuffer)}state.viewport(_currentViewport);state.scissor(_currentScissor);state.setScissorTest(_currentScissorTest);if(isCube){const textureProperties=properties.get(renderTarget.texture);_gl.framebufferTexture2D(36160,36064,34069+activeCubeFace,textureProperties.__webglTexture,activeMipmapLevel)}else if(isRenderTarget3D){const textureProperties=properties.get(renderTarget.texture);const layer=activeCubeFace||0;_gl.framebufferTextureLayer(36160,36064,textureProperties.__webglTexture,activeMipmapLevel||0,layer)}_currentMaterialId=-1};this.readRenderTargetPixels=function(renderTarget,x2,y2,width,height,buffer,activeCubeFaceIndex){if(!(renderTarget&&renderTarget.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==void 0){framebuffer=framebuffer[activeCubeFaceIndex]}if(framebuffer){state.bindFramebuffer(36160,framebuffer);try{const texture=renderTarget.texture;const textureFormat=texture.format;const textureType=texture.type;if(textureFormat!==RGBAFormat&&utils.convert(textureFormat)!==_gl.getParameter(35739)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const halfFloatSupportedByExt=textureType===HalfFloatType&&(extensions.has("EXT_color_buffer_half_float")||capabilities.isWebGL2&&extensions.has("EXT_color_buffer_float"));if(textureType!==UnsignedByteType&&utils.convert(textureType)!==_gl.getParameter(35738)&&!(textureType===FloatType&&(capabilities.isWebGL2||extensions.has("OES_texture_float")||extensions.has("WEBGL_color_buffer_float")))&&!halfFloatSupportedByExt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(x2>=0&&x2<=renderTarget.width-width&&(y2>=0&&y2<=renderTarget.height-height)){_gl.readPixels(x2,y2,width,height,utils.convert(textureFormat),utils.convert(textureType),buffer)}}finally{const framebuffer2=_currentRenderTarget!==null?properties.get(_currentRenderTarget).__webglFramebuffer:null;state.bindFramebuffer(36160,framebuffer2)}}};this.copyFramebufferToTexture=function(position,texture,level=0){const levelScale=Math.pow(2,-level);const width=Math.floor(texture.image.width*levelScale);const height=Math.floor(texture.image.height*levelScale);textures.setTexture2D(texture,0);_gl.copyTexSubImage2D(3553,level,0,0,position.x,position.y,width,height);state.unbindTexture()};this.copyTextureToTexture=function(position,srcTexture,dstTexture,level=0){const width=srcTexture.image.width;const height=srcTexture.image.height;const glFormat=utils.convert(dstTexture.format);const glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);_gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);if(srcTexture.isDataTexture){_gl.texSubImage2D(3553,level,position.x,position.y,width,height,glFormat,glType,srcTexture.image.data)}else{if(srcTexture.isCompressedTexture){_gl.compressedTexSubImage2D(3553,level,position.x,position.y,srcTexture.mipmaps[0].width,srcTexture.mipmaps[0].height,glFormat,srcTexture.mipmaps[0].data)}else{_gl.texSubImage2D(3553,level,position.x,position.y,glFormat,glType,srcTexture.image)}}if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(3553);state.unbindTexture()};this.copyTextureToTexture3D=function(sourceBox,position,srcTexture,dstTexture,level=0){if(_this.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const width=sourceBox.max.x-sourceBox.min.x+1;const height=sourceBox.max.y-sourceBox.min.y+1;const depth=sourceBox.max.z-sourceBox.min.z+1;const glFormat=utils.convert(dstTexture.format);const glType=utils.convert(dstTexture.type);let glTarget;if(dstTexture.isData3DTexture){textures.setTexture3D(dstTexture,0);glTarget=32879}else if(dstTexture.isDataArrayTexture){textures.setTexture2DArray(dstTexture,0);glTarget=35866}else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}_gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);const unpackRowLen=_gl.getParameter(3314);const unpackImageHeight=_gl.getParameter(32878);const unpackSkipPixels=_gl.getParameter(3316);const unpackSkipRows=_gl.getParameter(3315);const unpackSkipImages=_gl.getParameter(32877);const image=srcTexture.isCompressedTexture?srcTexture.mipmaps[0]:srcTexture.image;_gl.pixelStorei(3314,image.width);_gl.pixelStorei(32878,image.height);_gl.pixelStorei(3316,sourceBox.min.x);_gl.pixelStorei(3315,sourceBox.min.y);_gl.pixelStorei(32877,sourceBox.min.z);if(srcTexture.isDataTexture||srcTexture.isData3DTexture){_gl.texSubImage3D(glTarget,level,position.x,position.y,position.z,width,height,depth,glFormat,glType,image.data)}else{if(srcTexture.isCompressedTexture){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.");_gl.compressedTexSubImage3D(glTarget,level,position.x,position.y,position.z,width,height,depth,glFormat,image.data)}else{_gl.texSubImage3D(glTarget,level,position.x,position.y,position.z,width,height,depth,glFormat,glType,image)}}_gl.pixelStorei(3314,unpackRowLen);_gl.pixelStorei(32878,unpackImageHeight);_gl.pixelStorei(3316,unpackSkipPixels);_gl.pixelStorei(3315,unpackSkipRows);_gl.pixelStorei(32877,unpackSkipImages);if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(glTarget);state.unbindTexture()};this.initTexture=function(texture){if(texture.isCubeTexture){textures.setTextureCube(texture,0)}else if(texture.isData3DTexture){textures.setTexture3D(texture,0)}else if(texture.isDataArrayTexture){textures.setTexture2DArray(texture,0)}else{textures.setTexture2D(texture,0)}state.unbindTexture()};this.resetState=function(){_currentActiveCubeFace=0;_currentActiveMipmapLevel=0;_currentRenderTarget=null;state.reset();bindingStates.reset()};if(typeof __THREE_DEVTOOLS__!=="undefined"){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}var WebGL1Renderer=class extends WebGLRenderer{};WebGL1Renderer.prototype.isWebGL1Renderer=true;var FogExp2=class{constructor(color,density=25e-5){this.isFogExp2=true;this.name="";this.color=new Color(color);this.density=density}clone(){return new FogExp2(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}};var Fog=class{constructor(color,near=1,far=1e3){this.isFog=true;this.name="";this.color=new Color(color);this.near=near;this.far=far}clone(){return new Fog(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}};var Scene=class extends Object3D{constructor(){super();this.isScene=true;this.type="Scene";this.background=null;this.environment=null;this.fog=null;this.overrideMaterial=null;this.autoUpdate=true;if(typeof __THREE_DEVTOOLS__!=="undefined"){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}copy(source,recursive){super.copy(source,recursive);if(source.background!==null)this.background=source.background.clone();if(source.environment!==null)this.environment=source.environment.clone();if(source.fog!==null)this.fog=source.fog.clone();if(source.overrideMaterial!==null)this.overrideMaterial=source.overrideMaterial.clone();this.autoUpdate=source.autoUpdate;this.matrixAutoUpdate=source.matrixAutoUpdate;return this}toJSON(meta){const data=super.toJSON(meta);if(this.fog!==null)data.object.fog=this.fog.toJSON();return data}};var InterleavedBuffer=class{constructor(array,stride){this.isInterleavedBuffer=true;this.array=array;this.stride=stride;this.count=array!==void 0?array.length/stride:0;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;this.uuid=generateUUID()}onUploadCallback(){}set needsUpdate(value){if(value===true)this.version++}setUsage(value){this.usage=value;return this}copy(source){this.array=new source.array.constructor(source.array);this.count=source.count;this.stride=source.stride;this.usage=source.usage;return this}copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(let i=0,l=this.stride;iraycaster.far)return;intersects2.push({distance,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA,_vB,_vC,_uvA,_uvB,_uvC,new Vector2),face:null,object:this})}copy(source,recursive){super.copy(source,recursive);if(source.center!==void 0)this.center.copy(source.center);this.material=source.material;return this}};function transformVertex(vertexPosition,mvPosition,center,scale,sin,cos){_alignedPosition.subVectors(vertexPosition,center).addScalar(.5).multiply(scale);if(sin!==void 0){_rotatedPosition.x=cos*_alignedPosition.x-sin*_alignedPosition.y;_rotatedPosition.y=sin*_alignedPosition.x+cos*_alignedPosition.y}else{_rotatedPosition.copy(_alignedPosition)}vertexPosition.copy(mvPosition);vertexPosition.x+=_rotatedPosition.x;vertexPosition.y+=_rotatedPosition.y;vertexPosition.applyMatrix4(_viewWorldMatrix)}var _v1$2=new Vector3;var _v2$1=new Vector3;var LOD=class extends Object3D{constructor(){super();this._currentLevel=0;this.type="LOD";Object.defineProperties(this,{levels:{enumerable:true,value:[]},isLOD:{value:true}});this.autoUpdate=true}copy(source){super.copy(source,false);const levels=source.levels;for(let i=0,l=levels.length;i0){let i,l;for(i=1,l=levels.length;i0){_v1$2.setFromMatrixPosition(this.matrixWorld);const distance=raycaster.ray.origin.distanceTo(_v1$2);this.getObjectForDistance(distance).raycast(raycaster,intersects2)}}update(camera){const levels=this.levels;if(levels.length>1){_v1$2.setFromMatrixPosition(camera.matrixWorld);_v2$1.setFromMatrixPosition(this.matrixWorld);const distance=_v1$2.distanceTo(_v2$1)/camera.zoom;levels[0].object.visible=true;let i,l;for(i=1,l=levels.length;i=levels[i].distance){levels[i-1].object.visible=false;levels[i].object.visible=true}else{break}}this._currentLevel=i-1;for(;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);const distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.far)continue;intersects2.push({distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}else{const start=Math.max(0,drawRange.start);const end=Math.min(positionAttribute.count,drawRange.start+drawRange.count);for(let i=start,l=end-1;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);const distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.far)continue;intersects2.push({distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const geometry=this.geometry;const morphAttributes=geometry.morphAttributes;const keys=Object.keys(morphAttributes);if(keys.length>0){const morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==void 0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(let m=0,ml=morphAttribute.length;m0){const morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==void 0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(let m=0,ml=morphAttribute.length;mraycaster.far)return;intersects2.push({distance,distanceToRay:Math.sqrt(rayPointDistanceSq),point:intersectPoint,index,face:null,object})}}var VideoTexture=class extends Texture{constructor(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){super(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.isVideoTexture=true;this.minFilter=minFilter!==void 0?minFilter:LinearFilter;this.magFilter=magFilter!==void 0?magFilter:LinearFilter;this.generateMipmaps=false;const scope=this;function updateVideo(){scope.needsUpdate=true;video.requestVideoFrameCallback(updateVideo)}if("requestVideoFrameCallback"in video){video.requestVideoFrameCallback(updateVideo)}}clone(){return new this.constructor(this.image).copy(this)}update(){const video=this.image;const hasVideoFrameCallback="requestVideoFrameCallback"in video;if(hasVideoFrameCallback===false&&video.readyState>=video.HAVE_CURRENT_DATA){this.needsUpdate=true}}};var FramebufferTexture=class extends Texture{constructor(width,height,format){super({width,height});this.isFramebufferTexture=true;this.format=format;this.magFilter=NearestFilter;this.minFilter=NearestFilter;this.generateMipmaps=false;this.needsUpdate=true}};var CompressedTexture=class extends Texture{constructor(mipmaps,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){super(null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.isCompressedTexture=true;this.image={width,height};this.mipmaps=mipmaps;this.flipY=false;this.generateMipmaps=false}};var CanvasTexture=class extends Texture{constructor(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){super(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.isCanvasTexture=true;this.needsUpdate=true}};var Curve=class{constructor(){this.type="Curve";this.arcLengthDivisions=200}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.");return null}getPointAt(u,optionalTarget){const t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget)}getPoints(divisions=5){const points=[];for(let d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions))}return points}getSpacedPoints(divisions=5){const points=[];for(let d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions))}return points}getLength(){const lengths=this.getLengths();return lengths[lengths.length-1]}getLengths(divisions=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths}this.needsUpdate=false;const cache=[];let current,last=this.getPoint(0);let sum=0;cache.push(0);for(let p=1;p<=divisions;p++){current=this.getPoint(p/divisions);sum+=current.distanceTo(last);cache.push(sum);last=current}this.cacheArcLengths=cache;return cache}updateArcLengths(){this.needsUpdate=true;this.getLengths()}getUtoTmapping(u,distance){const arcLengths=this.getLengths();let i=0;const il=arcLengths.length;let targetArcLength;if(distance){targetArcLength=distance}else{targetArcLength=u*arcLengths[il-1]}let low=0,high=il-1,comparison;while(low<=high){i=Math.floor(low+(high-low)/2);comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1}else if(comparison>0){high=i-1}else{high=i;break}}i=high;if(arcLengths[i]===targetArcLength){return i/(il-1)}const lengthBefore=arcLengths[i];const lengthAfter=arcLengths[i+1];const segmentLength=lengthAfter-lengthBefore;const segmentFraction=(targetArcLength-lengthBefore)/segmentLength;const t=(i+segmentFraction)/(il-1);return t}getTangent(t,optionalTarget){const delta=1e-4;let t1=t-delta;let t2=t+delta;if(t1<0)t1=0;if(t2>1)t2=1;const pt1=this.getPoint(t1);const pt2=this.getPoint(t2);const tangent=optionalTarget||(pt1.isVector2?new Vector2:new Vector3);tangent.copy(pt2).sub(pt1).normalize();return tangent}getTangentAt(u,optionalTarget){const t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget)}computeFrenetFrames(segments,closed){const normal=new Vector3;const tangents=[];const normals=[];const binormals=[];const vec=new Vector3;const mat=new Matrix4;for(let i=0;i<=segments;i++){const u=i/segments;tangents[i]=this.getTangentAt(u,new Vector3)}normals[0]=new Vector3;binormals[0]=new Vector3;let min=Number.MAX_VALUE;const tx=Math.abs(tangents[0].x);const ty=Math.abs(tangents[0].y);const tz=Math.abs(tangents[0].z);if(tx<=min){min=tx;normal.set(1,0,0)}if(ty<=min){min=ty;normal.set(0,1,0)}if(tz<=min){normal.set(0,0,1)}vec.crossVectors(tangents[0],normal).normalize();normals[0].crossVectors(tangents[0],vec);binormals[0].crossVectors(tangents[0],normals[0]);for(let i=1;i<=segments;i++){normals[i]=normals[i-1].clone();binormals[i]=binormals[i-1].clone();vec.crossVectors(tangents[i-1],tangents[i]);if(vec.length()>Number.EPSILON){vec.normalize();const theta=Math.acos(clamp(tangents[i-1].dot(tangents[i]),-1,1));normals[i].applyMatrix4(mat.makeRotationAxis(vec,theta))}binormals[i].crossVectors(tangents[i],normals[i])}if(closed===true){let theta=Math.acos(clamp(normals[0].dot(normals[segments]),-1,1));theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){theta=-theta}for(let i=1;i<=segments;i++){normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i],theta*i));binormals[i].crossVectors(tangents[i],normals[i])}}return{tangents,normals,binormals}}clone(){return new this.constructor().copy(this)}copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this}toJSON(){const data={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data}fromJSON(json){this.arcLengthDivisions=json.arcLengthDivisions;return this}};var EllipseCurve=class extends Curve{constructor(aX=0,aY=0,xRadius=1,yRadius=1,aStartAngle=0,aEndAngle=Math.PI*2,aClockwise=false,aRotation=0){super();this.isEllipseCurve=true;this.type="EllipseCurve";this.aX=aX;this.aY=aY;this.xRadius=xRadius;this.yRadius=yRadius;this.aStartAngle=aStartAngle;this.aEndAngle=aEndAngle;this.aClockwise=aClockwise;this.aRotation=aRotation}getPoint(t,optionalTarget){const point=optionalTarget||new Vector2;const twoPi=Math.PI*2;let deltaAngle=this.aEndAngle-this.aStartAngle;const samePoints=Math.abs(deltaAngle)twoPi)deltaAngle-=twoPi;if(deltaAngle0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1}let p0,p3;if(this.closed||intPoint>0){p0=points[(intPoint-1)%l]}else{tmp.subVectors(points[0],points[1]).add(points[0]);p0=tmp}const p1=points[intPoint%l];const p2=points[(intPoint+1)%l];if(this.closed||intPoint+2points.length-2?points.length-1:intPoint+1];const p3=points[intPoint>points.length-3?points.length-1:intPoint+2];point.set(CatmullRom(weight,p0.x,p1.x,p2.x,p3.x),CatmullRom(weight,p0.y,p1.y,p2.y,p3.y));return point}copy(source){super.copy(source);this.points=[];for(let i=0,l=source.points.length;i=d){const diff=curveLengths[i]-d;const curve=this.curves[i];const segmentLength=curve.getLength();const u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u,optionalTarget)}i++}return null}getLength(){const lens=this.getCurveLengths();return lens[lens.length-1]}updateArcLengths(){this.needsUpdate=true;this.cacheLengths=null;this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length){return this.cacheLengths}const lengths=[];let sums=0;for(let i=0,l=this.curves.length;i1&&!points[points.length-1].equals(points[0])){points.push(points[0])}return points}copy(source){super.copy(source);this.curves=[];for(let i=0,l=source.curves.length;i0){const firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y)}}this.curves.push(curve);const lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint);return this}copy(source){super.copy(source);this.currentPoint.copy(source.currentPoint);return this}toJSON(){const data=super.toJSON();data.currentPoint=this.currentPoint.toArray();return data}fromJSON(json){super.fromJSON(json);this.currentPoint.fromArray(json.currentPoint);return this}};var LatheGeometry=class extends BufferGeometry{constructor(points=[new Vector2(0,-.5),new Vector2(.5,0),new Vector2(0,.5)],segments=12,phiStart=0,phiLength=Math.PI*2){super();this.type="LatheGeometry";this.parameters={points,segments,phiStart,phiLength};segments=Math.floor(segments);phiLength=clamp(phiLength,0,Math.PI*2);const indices=[];const vertices=[];const uvs=[];const initNormals=[];const normals=[];const inverseSegments=1/segments;const vertex2=new Vector3;const uv=new Vector2;const normal=new Vector3;const curNormal=new Vector3;const prevNormal=new Vector3;let dx=0;let dy=0;for(let j=0;j<=points.length-1;j++){switch(j){case 0:dx=points[j+1].x-points[j].x;dy=points[j+1].y-points[j].y;normal.x=dy*1;normal.y=-dx;normal.z=dy*0;prevNormal.copy(normal);normal.normalize();initNormals.push(normal.x,normal.y,normal.z);break;case points.length-1:initNormals.push(prevNormal.x,prevNormal.y,prevNormal.z);break;default:dx=points[j+1].x-points[j].x;dy=points[j+1].y-points[j].y;normal.x=dy*1;normal.y=-dx;normal.z=dy*0;curNormal.copy(normal);normal.x+=prevNormal.x;normal.y+=prevNormal.y;normal.z+=prevNormal.z;normal.normalize();initNormals.push(normal.x,normal.y,normal.z);prevNormal.copy(curNormal)}}for(let i=0;i<=segments;i++){const phi=phiStart+i*inverseSegments*phiLength;const sin=Math.sin(phi);const cos=Math.cos(phi);for(let j=0;j<=points.length-1;j++){vertex2.x=points[j].x*sin;vertex2.y=points[j].y;vertex2.z=points[j].x*cos;vertices.push(vertex2.x,vertex2.y,vertex2.z);uv.x=i/segments;uv.y=j/(points.length-1);uvs.push(uv.x,uv.y);const x2=initNormals[3*j+0]*sin;const y2=initNormals[3*j+1];const z=initNormals[3*j+0]*cos;normals.push(x2,y2,z)}}for(let i=0;i0)generateCap(true);if(radiusBottom>0)generateCap(false)}this.setIndex(indices);this.setAttribute("position",new Float32BufferAttribute(vertices,3));this.setAttribute("normal",new Float32BufferAttribute(normals,3));this.setAttribute("uv",new Float32BufferAttribute(uvs,2));function generateTorso(){const normal=new Vector3;const vertex2=new Vector3;let groupCount=0;const slope=(radiusBottom-radiusTop)/height;for(let y2=0;y2<=heightSegments;y2++){const indexRow=[];const v=y2/heightSegments;const radius=v*(radiusBottom-radiusTop)+radiusTop;for(let x2=0;x2<=radialSegments;x2++){const u=x2/radialSegments;const theta=u*thetaLength+thetaStart;const sinTheta=Math.sin(theta);const cosTheta=Math.cos(theta);vertex2.x=radius*sinTheta;vertex2.y=-v*height+halfHeight;vertex2.z=radius*cosTheta;vertices.push(vertex2.x,vertex2.y,vertex2.z);normal.set(sinTheta,slope,cosTheta).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(u,1-v);indexRow.push(index++)}indexArray.push(indexRow)}for(let x2=0;x2.9&&min<.1){if(x0<.2)uvBuffer[i+0]+=1;if(x1<.2)uvBuffer[i+2]+=1;if(x2<.2)uvBuffer[i+4]+=1}}}function pushVertex(vertex2){vertexBuffer.push(vertex2.x,vertex2.y,vertex2.z)}function getVertexByIndex(index,vertex2){const stride=index*3;vertex2.x=vertices[stride+0];vertex2.y=vertices[stride+1];vertex2.z=vertices[stride+2]}function correctUVs(){const a=new Vector3;const b=new Vector3;const c=new Vector3;const centroid=new Vector3;const uvA=new Vector2;const uvB=new Vector2;const uvC=new Vector2;for(let i=0,j=0;i80*dim){minX=maxX=data[0];minY=maxY=data[1];for(let i=dim;imaxX)maxX=x2;if(y2>maxY)maxY=y2}invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?1/invSize:0}earcutLinked(outerNode,triangles,dim,minX,minY,invSize);return triangles}};function linkedList(data,start,end,dim,clockwise){let i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last)}if(last&&equals(last,last.next)){removeNode(last);last=last.next}return last}function filterPoints(start,end){if(!start)return start;if(!end)end=start;let p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)break;again=true}else{p=p.next}}while(again||p!==end);return end}function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);let stop=ear,prev,next;while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);ear=next.next;stop=next.next;continue}ear=next;if(ear===stop){if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1)}else if(pass===1){ear=cureLocalIntersections(filterPoints(ear),triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2)}else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize)}break}}}function isEar(ear){const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;let p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next}return true}function isEarHashed(ear,minX,minY,invSize){const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;const minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;while(p&&p.z>=minZ&&n&&n.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ}while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ}while(n&&n.z<=maxZ){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ}return true}function cureLocalIntersections(start,triangles,dim){let p=start;do{const a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);removeNode(p);removeNode(p.next);p=start=b}p=p.next}while(p!==start);return filterPoints(p)}function splitEarcut(start,triangles,dim,minX,minY,invSize){let a=start;do{let b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);a=filterPoints(a,a.next);c=filterPoints(c,c.next);earcutLinked(a,triangles,dim,minX,minY,invSize);earcutLinked(c,triangles,dim,minX,minY,invSize);return}b=b.next}a=a.next}while(a!==start)}function eliminateHoles(data,holeIndices,outerNode,dim){const queue=[];let i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){const x2=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x2<=hx&&x2>qx){qx=x2;if(x2===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))){m=p;tanMin=tan}}p=p.next}while(p!==stop);return m}function sectorContainsSector(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0}function indexCurve(start,minX,minY,invSize){let p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,invSize);p.prevZ=p.prev;p.nextZ=p.next;p=p.next}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p)}function sortLinked(list){let i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||qSize>0&&q){if(pSize!==0&&(qSize===0||!q||p.z<=q.z)){e=p;p=p.nextZ;pSize--}else{e=q;q=q.nextZ;qSize--}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e}p=q}tail.nextZ=null;inSize*=2}while(numMerges>1);return list}function zOrder(x2,y2,minX,minY,invSize){x2=32767*(x2-minX)*invSize;y2=32767*(y2-minY)*invSize;x2=(x2|x2<<8)&16711935;x2=(x2|x2<<4)&252645135;x2=(x2|x2<<2)&858993459;x2=(x2|x2<<1)&1431655765;y2=(y2|y2<<8)&16711935;y2=(y2|y2<<4)&252645135;y2=(y2|y2<<2)&858993459;y2=(y2|y2<<1)&1431655765;return x2|y2<<1}function getLeftmost(start){let p=start,leftmost=start;do{if(p.x=0&&(ax-px2)*(by-py2)-(bx-px2)*(ay-py2)>=0&&(bx-px2)*(cy-py2)-(cx-px2)*(by-py2)>=0}function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0)}function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y)}function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y}function intersects(p1,q1,p2,q2){const o1=sign(area(p1,q1,p2));const o2=sign(area(p1,q1,q2));const o3=sign(area(p2,q2,p1));const o4=sign(area(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;if(o1===0&&onSegment(p1,p2,q1))return true;if(o2===0&&onSegment(p1,q2,q1))return true;if(o3===0&&onSegment(p2,p1,q2))return true;if(o4===0&&onSegment(p2,q1,q2))return true;return false}function onSegment(p,q,r){return q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y)}function sign(num){return num>0?1:num<0?-1:0}function intersectsPolygon(a,b){let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next}while(p!==a);return false}function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0}function middleInside(a,b){let p=a,inside=false;const px2=(a.x+b.x)/2,py2=(a.y+b.y)/2;do{if(p.y>py2!==p.next.y>py2&&p.next.y!==p.y&&px2<(p.next.x-p.x)*(py2-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next}while(p!==a);return inside}function splitPolygon(a,b){const a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2}function insertNode(i,x2,y2,last){const p=new Node(i,x2,y2);if(!last){p.prev=p;p.next=p}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p}return p}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ}function Node(i,x2,y2){this.i=i;this.x=x2;this.y=y2;this.prev=null;this.next=null;this.z=null;this.prevZ=null;this.nextZ=null;this.steiner=false}function signedArea(data,start,end,dim){let sum=0;for(let i=start,j=end-dim;i2&&points[l-1].equals(points[0])){points.pop()}}function addContour(vertices,contour){for(let i=0;iNumber.EPSILON){const v_prev_len=Math.sqrt(v_prev_lensq);const v_next_len=Math.sqrt(v_next_x*v_next_x+v_next_y*v_next_y);const ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;const ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;const ptNextShift_x=inNext.x-v_next_y/v_next_len;const ptNextShift_y=inNext.y+v_next_x/v_next_len;const sf=((ptNextShift_x-ptPrevShift_x)*v_next_y-(ptNextShift_y-ptPrevShift_y)*v_next_x)/(v_prev_x*v_next_y-v_prev_y*v_next_x);v_trans_x=ptPrevShift_x+v_prev_x*sf-inPt.x;v_trans_y=ptPrevShift_y+v_prev_y*sf-inPt.y;const v_trans_lensq=v_trans_x*v_trans_x+v_trans_y*v_trans_y;if(v_trans_lensq<=2){return new Vector2(v_trans_x,v_trans_y)}else{shrink_by=Math.sqrt(v_trans_lensq/2)}}else{let direction_eq=false;if(v_prev_x>Number.EPSILON){if(v_next_x>Number.EPSILON){direction_eq=true}}else{if(v_prev_x<-Number.EPSILON){if(v_next_x<-Number.EPSILON){direction_eq=true}}else{if(Math.sign(v_prev_y)===Math.sign(v_next_y)){direction_eq=true}}}if(direction_eq){v_trans_x=-v_prev_y;v_trans_y=v_prev_x;shrink_by=Math.sqrt(v_prev_lensq)}else{v_trans_x=v_prev_x;v_trans_y=v_prev_y;shrink_by=Math.sqrt(v_prev_lensq/2)}}return new Vector2(v_trans_x/shrink_by,v_trans_y/shrink_by)}const contourMovements=[];for(let i=0,il=contour.length,j=il-1,k=i+1;i=0;b--){const t=b/bevelSegments;const z=bevelThickness*Math.cos(t*Math.PI/2);const bs2=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;for(let i=0,il=contour.length;i=0){const j=i;let k=i-1;if(k<0)k=contour2.length-1;for(let s=0,sl=steps+bevelSegments*2;s0)indices.push(a,b,d);if(iy!==heightSegments-1||thetaEnd0!==value>0){this.version++}this._sheen=value}get clearcoat(){return this._clearcoat}set clearcoat(value){if(this._clearcoat>0!==value>0){this.version++}this._clearcoat=value}get iridescence(){return this._iridescence}set iridescence(value){if(this._iridescence>0!==value>0){this.version++}this._iridescence=value}get transmission(){return this._transmission}set transmission(value){if(this._transmission>0!==value>0){this.version++}this._transmission=value}copy(source){super.copy(source);this.defines={"STANDARD":"","PHYSICAL":""};this.clearcoat=source.clearcoat;this.clearcoatMap=source.clearcoatMap;this.clearcoatRoughness=source.clearcoatRoughness;this.clearcoatRoughnessMap=source.clearcoatRoughnessMap;this.clearcoatNormalMap=source.clearcoatNormalMap;this.clearcoatNormalScale.copy(source.clearcoatNormalScale);this.ior=source.ior;this.iridescence=source.iridescence;this.iridescenceMap=source.iridescenceMap;this.iridescenceIOR=source.iridescenceIOR;this.iridescenceThicknessRange=[...source.iridescenceThicknessRange];this.iridescenceThicknessMap=source.iridescenceThicknessMap;this.sheen=source.sheen;this.sheenColor.copy(source.sheenColor);this.sheenColorMap=source.sheenColorMap;this.sheenRoughness=source.sheenRoughness;this.sheenRoughnessMap=source.sheenRoughnessMap;this.transmission=source.transmission;this.transmissionMap=source.transmissionMap;this.thickness=source.thickness;this.thicknessMap=source.thicknessMap;this.attenuationDistance=source.attenuationDistance;this.attenuationColor.copy(source.attenuationColor);this.specularIntensity=source.specularIntensity;this.specularIntensityMap=source.specularIntensityMap;this.specularColor.copy(source.specularColor);this.specularColorMap=source.specularColorMap;return this}};var MeshPhongMaterial=class extends Material{constructor(parameters){super();this.isMeshPhongMaterial=true;this.type="MeshPhongMaterial";this.color=new Color(16777215);this.specular=new Color(1118481);this.shininess=30;this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.flatShading=false;this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.specular.copy(source.specular);this.shininess=source.shininess;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.flatShading=source.flatShading;this.fog=source.fog;return this}};var MeshToonMaterial=class extends Material{constructor(parameters){super();this.isMeshToonMaterial=true;this.defines={"TOON":""};this.type="MeshToonMaterial";this.color=new Color(16777215);this.map=null;this.gradientMap=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.map=source.map;this.gradientMap=source.gradientMap;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.fog=source.fog;return this}};var MeshNormalMaterial=class extends Material{constructor(parameters){super();this.isMeshNormalMaterial=true;this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.flatShading=false;this.setValues(parameters)}copy(source){super.copy(source);this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.flatShading=source.flatShading;return this}};var MeshLambertMaterial=class extends Material{constructor(parameters){super();this.isMeshLambertMaterial=true;this.type="MeshLambertMaterial";this.color=new Color(16777215);this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.fog=source.fog;return this}};var MeshMatcapMaterial=class extends Material{constructor(parameters){super();this.isMeshMatcapMaterial=true;this.defines={"MATCAP":""};this.type="MeshMatcapMaterial";this.color=new Color(16777215);this.matcap=null;this.map=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.flatShading=false;this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.defines={"MATCAP":""};this.color.copy(source.color);this.matcap=source.matcap;this.map=source.map;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.flatShading=source.flatShading;this.fog=source.fog;return this}};var LineDashedMaterial=class extends LineBasicMaterial{constructor(parameters){super();this.isLineDashedMaterial=true;this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(parameters)}copy(source){super.copy(source);this.scale=source.scale;this.dashSize=source.dashSize;this.gapSize=source.gapSize;return this}};function arraySlice(array,from,to){if(isTypedArray2(array)){return new array.constructor(array.subarray(from,to!==void 0?to:array.length))}return array.slice(from,to)}function convertArray(array,type,forceClone){if(!array||!forceClone&&array.constructor===type)return array;if(typeof type.BYTES_PER_ELEMENT==="number"){return new type(array)}return Array.prototype.slice.call(array)}function isTypedArray2(object){return ArrayBuffer.isView(object)&&!(object instanceof DataView)}function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j]}const n=times.length;const result=new Array(n);for(let i=0;i!==n;++i)result[i]=i;result.sort(compareTime);return result}function sortedArray(values,stride,order){const nValues=values.length;const result=new values.constructor(nValues);for(let i=0,dstOffset=0;dstOffset!==nValues;++i){const srcOffset=order[i]*stride;for(let j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j]}}return result}function flattenJSON(jsonKeys,times,values,valuePropertyName){let i=1,key=jsonKeys[0];while(key!==void 0&&key[valuePropertyName]===void 0){key=jsonKeys[i++]}if(key===void 0)return;let value=key[valuePropertyName];if(value===void 0)return;if(Array.isArray(value)){do{value=key[valuePropertyName];if(value!==void 0){times.push(key.time);values.push.apply(values,value)}key=jsonKeys[i++]}while(key!==void 0)}else if(value.toArray!==void 0){do{value=key[valuePropertyName];if(value!==void 0){times.push(key.time);value.toArray(values,values.length)}key=jsonKeys[i++]}while(key!==void 0)}else{do{value=key[valuePropertyName];if(value!==void 0){times.push(key.time);values.push(value)}key=jsonKeys[i++]}while(key!==void 0)}}function subclip(sourceClip,name,startFrame,endFrame,fps=30){const clip=sourceClip.clone();clip.name=name;const tracks=[];for(let i=0;i=endFrame)continue;times.push(track.times[j]);for(let k=0;kclip.tracks[i].times[0]){minStartTime=clip.tracks[i].times[0]}}for(let i=0;i=referenceTrack.times[lastIndex]){const startIndex=lastIndex*referenceValueSize+referenceOffset;const endIndex=startIndex+referenceValueSize-referenceOffset;referenceValue=arraySlice(referenceTrack.values,startIndex,endIndex)}else{const interpolant=referenceTrack.createInterpolant();const startIndex=referenceOffset;const endIndex=referenceValueSize-referenceOffset;interpolant.evaluate(referenceTime);referenceValue=arraySlice(interpolant.resultBuffer,startIndex,endIndex)}if(referenceTrackType==="quaternion"){const referenceQuat=new Quaternion().fromArray(referenceValue).normalize().conjugate();referenceQuat.toArray(referenceValue)}const numTimes=targetTrack.times.length;for(let j=0;j=t0)){const t1global=pp[1];if(t=t0){break seek}}right=i1;i1=0;break linear_scan}break validate_interval}while(i1>>1;if(tendTime){--to}++to;if(from!==0||to!==nKeys){if(from>=to){to=Math.max(to,1);from=to-1}const stride=this.getValueSize();this.times=arraySlice(times,from,to);this.values=arraySlice(this.values,from*stride,to*stride)}return this}validate(){let valid=true;const valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error("THREE.KeyframeTrack: Invalid value size in track.",this);valid=false}const times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error("THREE.KeyframeTrack: Track is empty.",this);valid=false}let prevTime=null;for(let i=0;i!==nKeys;i++){const currTime=times[i];if(typeof currTime==="number"&&isNaN(currTime)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,i,currTime);valid=false;break}if(prevTime!==null&&prevTime>currTime){console.error("THREE.KeyframeTrack: Out of order keys.",this,i,currTime,prevTime);valid=false;break}prevTime=currTime}if(values!==void 0){if(isTypedArray2(values)){for(let i=0,n=values.length;i!==n;++i){const value=values[i];if(isNaN(value)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,i,value);valid=false;break}}}}return valid}optimize(){const times=arraySlice(this.times),values=arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,lastIndex=times.length-1;let writeIndex=1;for(let i=1;i0){times[writeIndex]=times[lastIndex];for(let readOffset=lastIndex*stride,writeOffset=writeIndex*stride,j=0;j!==stride;++j){values[writeOffset+j]=values[readOffset+j]}++writeIndex}if(writeIndex!==times.length){this.times=arraySlice(times,0,writeIndex);this.values=arraySlice(values,0,writeIndex*stride)}else{this.times=times;this.values=values}return this}clone(){const times=arraySlice(this.times,0);const values=arraySlice(this.values,0);const TypedKeyframeTrack=this.constructor;const track=new TypedKeyframeTrack(this.name,times,values);track.createInterpolant=this.createInterpolant;return track}};KeyframeTrack.prototype.TimeBufferType=Float32Array;KeyframeTrack.prototype.ValueBufferType=Float32Array;KeyframeTrack.prototype.DefaultInterpolation=InterpolateLinear;var BooleanKeyframeTrack=class extends KeyframeTrack{};BooleanKeyframeTrack.prototype.ValueTypeName="bool";BooleanKeyframeTrack.prototype.ValueBufferType=Array;BooleanKeyframeTrack.prototype.DefaultInterpolation=InterpolateDiscrete;BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0;BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;var ColorKeyframeTrack=class extends KeyframeTrack{};ColorKeyframeTrack.prototype.ValueTypeName="color";var NumberKeyframeTrack=class extends KeyframeTrack{};NumberKeyframeTrack.prototype.ValueTypeName="number";var QuaternionLinearInterpolant=class extends Interpolant{constructor(parameterPositions,sampleValues,sampleSize,resultBuffer){super(parameterPositions,sampleValues,sampleSize,resultBuffer)}interpolate_(i1,t0,t,t1){const result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,alpha=(t-t0)/(t1-t0);let offset=i1*stride;for(let end=offset+stride;offset!==end;offset+=4){Quaternion.slerpFlat(result,0,values,offset-stride,values,offset,alpha)}return result}};var QuaternionKeyframeTrack=class extends KeyframeTrack{InterpolantFactoryMethodLinear(result){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),result)}};QuaternionKeyframeTrack.prototype.ValueTypeName="quaternion";QuaternionKeyframeTrack.prototype.DefaultInterpolation=InterpolateLinear;QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;var StringKeyframeTrack=class extends KeyframeTrack{};StringKeyframeTrack.prototype.ValueTypeName="string";StringKeyframeTrack.prototype.ValueBufferType=Array;StringKeyframeTrack.prototype.DefaultInterpolation=InterpolateDiscrete;StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0;StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;var VectorKeyframeTrack=class extends KeyframeTrack{};VectorKeyframeTrack.prototype.ValueTypeName="vector";var AnimationClip=class{constructor(name,duration=-1,tracks,blendMode=NormalAnimationBlendMode){this.name=name;this.tracks=tracks;this.duration=duration;this.blendMode=blendMode;this.uuid=generateUUID();if(this.duration<0){this.resetDuration()}}static parse(json){const tracks=[],jsonTracks=json.tracks,frameTime=1/(json.fps||1);for(let i=0,n=jsonTracks.length;i!==n;++i){tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime))}const clip=new this(json.name,json.duration,tracks,json.blendMode);clip.uuid=json.uuid;return clip}static toJSON(clip){const tracks=[],clipTracks=clip.tracks;const json={"name":clip.name,"duration":clip.duration,"tracks":tracks,"uuid":clip.uuid,"blendMode":clip.blendMode};for(let i=0,n=clipTracks.length;i!==n;++i){tracks.push(KeyframeTrack.toJSON(clipTracks[i]))}return json}static CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){const numMorphTargets=morphTargetSequence.length;const tracks=[];for(let i=0;i1){const name=parts[1];let animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[]}animationMorphTargets.push(morphTarget)}}const clips=[];for(const name in animationToMorphTargets){clips.push(this.CreateFromMorphTargetSequence(name,animationToMorphTargets[name],fps,noLoop))}return clips}static parseAnimation(animation,bones){if(!animation){console.error("THREE.AnimationClip: No animation in JSONLoader data.");return null}const addNonemptyTrack=function(trackType,trackName,animationKeys,propertyName,destTracks){if(animationKeys.length!==0){const times=[];const values=[];flattenJSON(animationKeys,times,values,propertyName);if(times.length!==0){destTracks.push(new trackType(trackName,times,values))}}};const tracks=[];const clipName=animation.name||"default";const fps=animation.fps||30;const blendMode=animation.blendMode;let duration=animation.length||-1;const hierarchyTracks=animation.hierarchy||[];for(let h=0;h{if(onLoad)onLoad(cached);this.manager.itemEnd(url)},0);return cached}if(loading[url]!==void 0){loading[url].push({onLoad,onProgress,onError});return}loading[url]=[];loading[url].push({onLoad,onProgress,onError});const req=new Request(url,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"});const mimeType=this.mimeType;const responseType=this.responseType;fetch(req).then(response=>{if(response.status===200||response.status===0){if(response.status===0){console.warn("THREE.FileLoader: HTTP Status 0 received.")}if(typeof ReadableStream==="undefined"||response.body===void 0||response.body.getReader===void 0){return response}const callbacks=loading[url];const reader=response.body.getReader();const contentLength=response.headers.get("Content-Length");const total=contentLength?parseInt(contentLength):0;const lengthComputable=total!==0;let loaded=0;const stream=new ReadableStream({start(controller){readData();function readData(){reader.read().then(({done,value})=>{if(done){controller.close()}else{loaded+=value.byteLength;const event=new ProgressEvent("progress",{lengthComputable,loaded,total});for(let i=0,il=callbacks.length;i{switch(responseType){case"arraybuffer":return response.arrayBuffer();case"blob":return response.blob();case"document":return response.text().then(text=>{const parser=new DOMParser;return parser.parseFromString(text,mimeType)});case"json":return response.json();default:if(mimeType===void 0){return response.text()}else{const re=/charset="?([^;"\\s]*)"?/i;const exec=re.exec(mimeType);const label=exec&&exec[1]?exec[1].toLowerCase():void 0;const decoder=new TextDecoder(label);return response.arrayBuffer().then(ab=>decoder.decode(ab))}}}).then(data=>{Cache.add(url,data);const callbacks=loading[url];delete loading[url];for(let i=0,il=callbacks.length;i{const callbacks=loading[url];if(callbacks===void 0){this.manager.itemError(url);throw err}delete loading[url];for(let i=0,il=callbacks.length;i{this.manager.itemEnd(url)});this.manager.itemStart(url)}setResponseType(value){this.responseType=value;return this}setMimeType(value){this.mimeType=value;return this}};var AnimationLoader=class extends Loader{constructor(manager){super(manager)}load(url,onLoad,onProgress,onError){const scope=this;const loader=new FileLoader(this.manager);loader.setPath(this.path);loader.setRequestHeader(this.requestHeader);loader.setWithCredentials(this.withCredentials);loader.load(url,function(text){try{onLoad(scope.parse(JSON.parse(text)))}catch(e){if(onError){onError(e)}else{console.error(e)}scope.manager.itemError(url)}},onProgress,onError)}parse(json){const animations=[];for(let i=0;i0?true:false}else{material.vertexColors=json.vertexColors}}if(json.uniforms!==void 0){for(const name in json.uniforms){const uniform=json.uniforms[name];material.uniforms[name]={};switch(uniform.type){case"t":material.uniforms[name].value=getTexture(uniform.value);break;case"c":material.uniforms[name].value=new Color().setHex(uniform.value);break;case"v2":material.uniforms[name].value=new Vector2().fromArray(uniform.value);break;case"v3":material.uniforms[name].value=new Vector3().fromArray(uniform.value);break;case"v4":material.uniforms[name].value=new Vector4().fromArray(uniform.value);break;case"m3":material.uniforms[name].value=new Matrix3().fromArray(uniform.value);break;case"m4":material.uniforms[name].value=new Matrix4().fromArray(uniform.value);break;default:material.uniforms[name].value=uniform.value}}}if(json.defines!==void 0)material.defines=json.defines;if(json.vertexShader!==void 0)material.vertexShader=json.vertexShader;if(json.fragmentShader!==void 0)material.fragmentShader=json.fragmentShader;if(json.extensions!==void 0){for(const key in json.extensions){material.extensions[key]=json.extensions[key]}}if(json.shading!==void 0)material.flatShading=json.shading===1;if(json.size!==void 0)material.size=json.size;if(json.sizeAttenuation!==void 0)material.sizeAttenuation=json.sizeAttenuation;if(json.map!==void 0)material.map=getTexture(json.map);if(json.matcap!==void 0)material.matcap=getTexture(json.matcap);if(json.alphaMap!==void 0)material.alphaMap=getTexture(json.alphaMap);if(json.bumpMap!==void 0)material.bumpMap=getTexture(json.bumpMap);if(json.bumpScale!==void 0)material.bumpScale=json.bumpScale;if(json.normalMap!==void 0)material.normalMap=getTexture(json.normalMap);if(json.normalMapType!==void 0)material.normalMapType=json.normalMapType;if(json.normalScale!==void 0){let normalScale=json.normalScale;if(Array.isArray(normalScale)===false){normalScale=[normalScale,normalScale]}material.normalScale=new Vector2().fromArray(normalScale)}if(json.displacementMap!==void 0)material.displacementMap=getTexture(json.displacementMap);if(json.displacementScale!==void 0)material.displacementScale=json.displacementScale;if(json.displacementBias!==void 0)material.displacementBias=json.displacementBias;if(json.roughnessMap!==void 0)material.roughnessMap=getTexture(json.roughnessMap);if(json.metalnessMap!==void 0)material.metalnessMap=getTexture(json.metalnessMap);if(json.emissiveMap!==void 0)material.emissiveMap=getTexture(json.emissiveMap);if(json.emissiveIntensity!==void 0)material.emissiveIntensity=json.emissiveIntensity;if(json.specularMap!==void 0)material.specularMap=getTexture(json.specularMap);if(json.specularIntensityMap!==void 0)material.specularIntensityMap=getTexture(json.specularIntensityMap);if(json.specularColorMap!==void 0)material.specularColorMap=getTexture(json.specularColorMap);if(json.envMap!==void 0)material.envMap=getTexture(json.envMap);if(json.envMapIntensity!==void 0)material.envMapIntensity=json.envMapIntensity;if(json.reflectivity!==void 0)material.reflectivity=json.reflectivity;if(json.refractionRatio!==void 0)material.refractionRatio=json.refractionRatio;if(json.lightMap!==void 0)material.lightMap=getTexture(json.lightMap);if(json.lightMapIntensity!==void 0)material.lightMapIntensity=json.lightMapIntensity;if(json.aoMap!==void 0)material.aoMap=getTexture(json.aoMap);if(json.aoMapIntensity!==void 0)material.aoMapIntensity=json.aoMapIntensity;if(json.gradientMap!==void 0)material.gradientMap=getTexture(json.gradientMap);if(json.clearcoatMap!==void 0)material.clearcoatMap=getTexture(json.clearcoatMap);if(json.clearcoatRoughnessMap!==void 0)material.clearcoatRoughnessMap=getTexture(json.clearcoatRoughnessMap);if(json.clearcoatNormalMap!==void 0)material.clearcoatNormalMap=getTexture(json.clearcoatNormalMap);if(json.clearcoatNormalScale!==void 0)material.clearcoatNormalScale=new Vector2().fromArray(json.clearcoatNormalScale);if(json.iridescenceMap!==void 0)material.iridescenceMap=getTexture(json.iridescenceMap);if(json.iridescenceThicknessMap!==void 0)material.iridescenceThicknessMap=getTexture(json.iridescenceThicknessMap);if(json.transmissionMap!==void 0)material.transmissionMap=getTexture(json.transmissionMap);if(json.thicknessMap!==void 0)material.thicknessMap=getTexture(json.thicknessMap);if(json.sheenColorMap!==void 0)material.sheenColorMap=getTexture(json.sheenColorMap);if(json.sheenRoughnessMap!==void 0)material.sheenRoughnessMap=getTexture(json.sheenRoughnessMap);return material}setTextures(value){this.textures=value;return this}static createMaterialFromType(type){const materialLib={ShadowMaterial,SpriteMaterial,RawShaderMaterial,ShaderMaterial,PointsMaterial,MeshPhysicalMaterial,MeshStandardMaterial,MeshPhongMaterial,MeshToonMaterial,MeshNormalMaterial,MeshLambertMaterial,MeshDepthMaterial,MeshDistanceMaterial,MeshBasicMaterial,MeshMatcapMaterial,LineDashedMaterial,LineBasicMaterial,Material};return new materialLib[type]}};var LoaderUtils=class{static decodeText(array){if(typeof TextDecoder!=="undefined"){return new TextDecoder().decode(array)}let s="";for(let i=0,il=array.length;i0){const manager=new LoadingManager(onLoad);loader=new ImageLoader(manager);loader.setCrossOrigin(this.crossOrigin);for(let i=0,il=json.length;i0){loader=new ImageLoader(this.manager);loader.setCrossOrigin(this.crossOrigin);for(let i=0,il=json.length;i0){this.source.connect(this.filters[0]);for(let i=1,l=this.filters.length;i0){this.source.disconnect(this.filters[0]);for(let i=1,l=this.filters.length;i0){this._mixBufferRegionAdditive(buffer,offset,this._addIndex*stride,1,stride)}for(let i=stride,e=stride+stride;i!==e;++i){if(buffer[i]!==buffer[i+stride]){binding.setValue(buffer,offset);break}}}saveOriginalState(){const binding=this.binding;const buffer=this.buffer,stride=this.valueSize,originalValueOffset=stride*this._origIndex;binding.getValue(buffer,originalValueOffset);for(let i=stride,e=originalValueOffset;i!==e;++i){buffer[i]=buffer[originalValueOffset+i%stride]}this._setIdentity();this.cumulativeWeight=0;this.cumulativeWeightAdditive=0}restoreOriginalState(){const originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset)}_setAdditiveIdentityNumeric(){const startIndex=this._addIndex*this.valueSize;const endIndex=startIndex+this.valueSize;for(let i=startIndex;i=.5){for(let i=0;i!==stride;++i){buffer[dstOffset+i]=buffer[srcOffset+i]}}}_slerp(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t)}_slerpAdditive(buffer,dstOffset,srcOffset,t,stride){const workOffset=this._workIndex*stride;Quaternion.multiplyQuaternionsFlat(buffer,workOffset,buffer,dstOffset,buffer,srcOffset);Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,workOffset,t)}_lerp(buffer,dstOffset,srcOffset,t,stride){const s=1-t;for(let i=0;i!==stride;++i){const j=dstOffset+i;buffer[j]=buffer[j]*s+buffer[srcOffset+i]*t}}_lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(let i=0;i!==stride;++i){const j=dstOffset+i;buffer[j]=buffer[j]+buffer[srcOffset+i]*t}}};var _RESERVED_CHARS_RE="\\\\[\\\\]\\\\.:\\\\/";var _reservedRe=new RegExp("["+_RESERVED_CHARS_RE+"]","g");var _wordChar="[^"+_RESERVED_CHARS_RE+"]";var _wordCharOrDot="[^"+_RESERVED_CHARS_RE.replace("\\\\.","")+"]";var _directoryRe=/((?:WC+[\\/:])*)/.source.replace("WC",_wordChar);var _nodeRe=/(WCOD+)?/.source.replace("WCOD",_wordCharOrDot);var _objectRe=/(?:\\.(WC+)(?:\\[(.+)\\])?)?/.source.replace("WC",_wordChar);var _propertyRe=/\\.(WC+)(?:\\[(.+)\\])?/.source.replace("WC",_wordChar);var _trackRe=new RegExp("^"+_directoryRe+_nodeRe+_objectRe+_propertyRe+"$");var _supportedObjectNames=["material","materials","bones"];var Composite=class{constructor(targetGroup,path,optionalParsedPath){const parsedPath=optionalParsedPath||PropertyBinding.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath)}getValue(array,offset){this.bind();const firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];if(binding!==void 0)binding.getValue(array,offset)}setValue(array,offset){const bindings=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].setValue(array,offset)}}bind(){const bindings=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].bind()}}unbind(){const bindings=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].unbind()}}};var PropertyBinding=class{constructor(rootNode,path,parsedPath){this.path=path;this.parsedPath=parsedPath||PropertyBinding.parseTrackName(path);this.node=PropertyBinding.findNode(rootNode,this.parsedPath.nodeName)||rootNode;this.rootNode=rootNode;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}static create(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding(root,path,parsedPath)}else{return new PropertyBinding.Composite(root,path,parsedPath)}}static sanitizeNodeName(name){return name.replace(/\\s/g,"_").replace(_reservedRe,"")}static parseTrackName(trackName){const matches=_trackRe.exec(trackName);if(matches===null){throw new Error("PropertyBinding: Cannot parse trackName: "+trackName)}const results={nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],propertyIndex:matches[6]};const lastDot=results.nodeName&&results.nodeName.lastIndexOf(".");if(lastDot!==void 0&&lastDot!==-1){const objectName=results.nodeName.substring(lastDot+1);if(_supportedObjectNames.indexOf(objectName)!==-1){results.nodeName=results.nodeName.substring(0,lastDot);results.objectName=objectName}}if(results.propertyName===null||results.propertyName.length===0){throw new Error("PropertyBinding: can not parse propertyName from trackName: "+trackName)}return results}static findNode(root,nodeName){if(nodeName===void 0||nodeName===""||nodeName==="."||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root}if(root.skeleton){const bone=root.skeleton.getBoneByName(nodeName);if(bone!==void 0){return bone}}if(root.children){const searchNodeSubtree=function(children){for(let i=0;i=nCachedObjects){const lastCachedIndex=nCachedObjects++,firstActiveObject=objects2[lastCachedIndex];indicesByUUID[firstActiveObject.uuid]=index;objects2[index]=firstActiveObject;indicesByUUID[uuid]=lastCachedIndex;objects2[lastCachedIndex]=object;for(let j=0,m=nBindings;j!==m;++j){const bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding}}}this.nCachedObjects_=nCachedObjects}uncache(){const objects2=this._objects,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;let nCachedObjects=this.nCachedObjects_,nObjects=objects2.length;for(let i=0,n=arguments.length;i!==n;++i){const object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==void 0){delete indicesByUUID[uuid];if(index0){indicesByUUID[lastObject.uuid]=index}objects2[index]=lastObject;objects2.pop();for(let j=0,m=nBindings;j!==m;++j){const bindingsForPath=bindings[j];bindingsForPath[index]=bindingsForPath[lastIndex];bindingsForPath.pop()}}}}this.nCachedObjects_=nCachedObjects}subscribe_(path,parsedPath){const indicesByPath=this._bindingsIndicesByPath;let index=indicesByPath[path];const bindings=this._bindings;if(index!==void 0)return bindings[index];const paths=this._paths,parsedPaths=this._parsedPaths,objects2=this._objects,nObjects=objects2.length,nCachedObjects=this.nCachedObjects_,bindingsForPath=new Array(nObjects);index=bindings.length;indicesByPath[path]=index;paths.push(path);parsedPaths.push(parsedPath);bindings.push(bindingsForPath);for(let i=nCachedObjects,n=objects2.length;i!==n;++i){const object=objects2[i];bindingsForPath[i]=new PropertyBinding(object,path,parsedPath)}return bindingsForPath}unsubscribe_(path){const indicesByPath=this._bindingsIndicesByPath,index=indicesByPath[path];if(index!==void 0){const paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,lastBindingsIndex=bindings.length-1,lastBindings=bindings[lastBindingsIndex],lastBindingsPath=path[lastBindingsIndex];indicesByPath[lastBindingsPath]=index;bindings[index]=lastBindings;bindings.pop();parsedPaths[index]=parsedPaths[lastBindingsIndex];parsedPaths.pop();paths[index]=paths[lastBindingsIndex];paths.pop()}}};var AnimationAction=class{constructor(mixer,clip,localRoot=null,blendMode=clip.blendMode){this._mixer=mixer;this._clip=clip;this._localRoot=localRoot;this.blendMode=blendMode;const tracks=clip.tracks,nTracks=tracks.length,interpolants=new Array(nTracks);const interpolantSettings={endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding};for(let i=0;i!==nTracks;++i){const interpolant=tracks[i].createInterpolant(null);interpolants[i]=interpolant;interpolant.settings=interpolantSettings}this._interpolantSettings=interpolantSettings;this._interpolants=interpolants;this._propertyBindings=new Array(nTracks);this._cacheIndex=null;this._byClipCacheIndex=null;this._timeScaleInterpolant=null;this._weightInterpolant=null;this.loop=LoopRepeat;this._loopCount=-1;this._startTime=null;this.time=0;this.timeScale=1;this._effectiveTimeScale=1;this.weight=1;this._effectiveWeight=1;this.repetitions=Infinity;this.paused=false;this.enabled=true;this.clampWhenFinished=false;this.zeroSlopeAtStart=true;this.zeroSlopeAtEnd=true}play(){this._mixer._activateAction(this);return this}stop(){this._mixer._deactivateAction(this);return this.reset()}reset(){this.paused=false;this.enabled=true;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(time){this._startTime=time;return this}setLoop(mode,repetitions){this.loop=mode;this.repetitions=repetitions;return this}setEffectiveWeight(weight){this.weight=weight;this._effectiveWeight=this.enabled?weight:0;return this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(duration){return this._scheduleFading(duration,0,1)}fadeOut(duration){return this._scheduleFading(duration,1,0)}crossFadeFrom(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){const fadeInDuration=this._clip.duration,fadeOutDuration=fadeOutAction._clip.duration,startEndRatio=fadeOutDuration/fadeInDuration,endStartRatio=fadeInDuration/fadeOutDuration;fadeOutAction.warp(1,startEndRatio,duration);this.warp(endStartRatio,1,duration)}return this}crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp)}stopFading(){const weightInterpolant=this._weightInterpolant;if(weightInterpolant!==null){this._weightInterpolant=null;this._mixer._takeBackControlInterpolant(weightInterpolant)}return this}setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping()}syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping()}halt(duration){return this.warp(this._effectiveTimeScale,0,duration)}warp(startTimeScale,endTimeScale,duration){const mixer=this._mixer,now2=mixer.time,timeScale=this.timeScale;let interpolant=this._timeScaleInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant}const times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now2;times[1]=now2+duration;values[0]=startTimeScale/timeScale;values[1]=endTimeScale/timeScale;return this}stopWarping(){const timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant)}return this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(time,deltaTime,timeDirection,accuIndex){if(!this.enabled){this._updateWeight(time);return}const startTime=this._startTime;if(startTime!==null){const timeRunning=(time-startTime)*timeDirection;if(timeRunning<0||timeDirection===0){return}this._startTime=null;deltaTime=timeDirection*timeRunning}deltaTime*=this._updateTimeScale(time);const clipTime=this._updateTime(deltaTime);const weight=this._updateWeight(time);if(weight>0){const interpolants=this._interpolants;const propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode:for(let j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight)}break;case NormalAnimationBlendMode:default:for(let j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulate(accuIndex,weight)}}}}_updateWeight(time){let weight=0;if(this.enabled){weight=this.weight;const interpolant=this._weightInterpolant;if(interpolant!==null){const interpolantValue=interpolant.evaluate(time)[0];weight*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopFading();if(interpolantValue===0){this.enabled=false}}}}this._effectiveWeight=weight;return weight}_updateTimeScale(time){let timeScale=0;if(!this.paused){timeScale=this.timeScale;const interpolant=this._timeScaleInterpolant;if(interpolant!==null){const interpolantValue=interpolant.evaluate(time)[0];timeScale*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopWarping();if(timeScale===0){this.paused=true}else{this.timeScale=timeScale}}}}this._effectiveTimeScale=timeScale;return timeScale}_updateTime(deltaTime){const duration=this._clip.duration;const loop2=this.loop;let time=this.time+deltaTime;let loopCount=this._loopCount;const pingPong=loop2===LoopPingPong;if(deltaTime===0){if(loopCount===-1)return time;return pingPong&&(loopCount&1)===1?duration-time:time}if(loop2===LoopOnce){if(loopCount===-1){this._loopCount=0;this._setEndings(true,true,false)}handle_stop:{if(time>=duration){time=duration}else if(time<0){time=0}else{this.time=time;break handle_stop}if(this.clampWhenFinished)this.paused=true;else this.enabled=false;this.time=time;this._mixer.dispatchEvent({type:"finished",action:this,direction:deltaTime<0?-1:1})}}else{if(loopCount===-1){if(deltaTime>=0){loopCount=0;this._setEndings(true,this.repetitions===0,pingPong)}else{this._setEndings(this.repetitions===0,true,pingPong)}}if(time>=duration||time<0){const loopDelta=Math.floor(time/duration);time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);const pending=this.repetitions-loopCount;if(pending<=0){if(this.clampWhenFinished)this.paused=true;else this.enabled=false;time=deltaTime>0?duration:0;this.time=time;this._mixer.dispatchEvent({type:"finished",action:this,direction:deltaTime>0?1:-1})}else{if(pending===1){const atStart=deltaTime<0;this._setEndings(atStart,!atStart,pingPong)}else{this._setEndings(false,false,pingPong)}this._loopCount=loopCount;this.time=time;this._mixer.dispatchEvent({type:"loop",action:this,loopDelta})}}else{this.time=time}if(pingPong&&(loopCount&1)===1){return duration-time}}return time}_setEndings(atStart,atEnd,pingPong){const settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding;settings.endingEnd=ZeroSlopeEnding}else{if(atStart){settings.endingStart=this.zeroSlopeAtStart?ZeroSlopeEnding:ZeroCurvatureEnding}else{settings.endingStart=WrapAroundEnding}if(atEnd){settings.endingEnd=this.zeroSlopeAtEnd?ZeroSlopeEnding:ZeroCurvatureEnding}else{settings.endingEnd=WrapAroundEnding}}}_scheduleFading(duration,weightNow,weightThen){const mixer=this._mixer,now2=mixer.time;let interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant}const times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now2;values[0]=weightNow;times[1]=now2+duration;values[1]=weightThen;return this}};var _controlInterpolantsResultBuffer=new Float32Array(1);var AnimationMixer=class extends EventDispatcher2{constructor(root){super();this._root=root;this._initMemoryManager();this._accuIndex=0;this.time=0;this.timeScale=1}_bindAction(action,prototypeAction){const root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName;let bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===void 0){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName}for(let i=0;i!==nTracks;++i){const track=tracks[i],trackName=track.name;let binding=bindingsByName[trackName];if(binding!==void 0){++binding.referenceCount;bindings[i]=binding}else{binding=bindings[i];if(binding!==void 0){if(binding._cacheIndex===null){++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName)}continue}const path=prototypeAction&&prototypeAction._propertyBindings[i].binding.parsedPath;binding=new PropertyMixer(PropertyBinding.create(root,trackName,path),track.ValueTypeName,track.getValueSize());++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);bindings[i]=binding}interpolants[i].resultBuffer=binding.buffer}}_activateAction(action){if(!this._isActiveAction(action)){if(action._cacheIndex===null){const rootUuid=(action._localRoot||this._root).uuid,clipUuid=action._clip.uuid,actionsForClip=this._actionsByClip[clipUuid];this._bindAction(action,actionsForClip&&actionsForClip.knownActions[0]);this._addInactiveAction(action,clipUuid,rootUuid)}const bindings=action._propertyBindings;for(let i=0,n=bindings.length;i!==n;++i){const binding=bindings[i];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState()}}this._lendAction(action)}}_deactivateAction(action){if(this._isActiveAction(action)){const bindings=action._propertyBindings;for(let i=0,n=bindings.length;i!==n;++i){const binding=bindings[i];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding)}}this._takeBackAction(action)}}_initMemoryManager(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;const scope=this;this.stats={actions:{get total(){return scope._actions.length},get inUse(){return scope._nActiveActions}},bindings:{get total(){return scope._bindings.length},get inUse(){return scope._nActiveBindings}},controlInterpolants:{get total(){return scope._controlInterpolants.length},get inUse(){return scope._nActiveControlInterpolants}}}}_isActiveAction(action){const index=action._cacheIndex;return index!==null&&index=0;--i){actions[i].stop()}return this}update(deltaTime){deltaTime*=this.timeScale;const actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;for(let i=0;i!==nActions;++i){const action=actions[i];action._update(time,deltaTime,timeDirection,accuIndex)}const bindings=this._bindings,nBindings=this._nActiveBindings;for(let i=0;i!==nBindings;++i){bindings[i].apply(accuIndex)}return this}setTime(timeInSeconds){this.time=0;for(let i=0;ithis.max.x||point.ythis.max.y?false:true}containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y}getParameter(point,target){return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(box){return box.max.xthis.max.x||box.max.ythis.max.y?false:true}clampPoint(point,target){return target.copy(point).clamp(this.min,this.max)}distanceToPoint(point){const clampedPoint=_vector$4.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length()}intersect(box){this.min.max(box.min);this.max.min(box.max);return this}union(box){this.min.min(box.min);this.max.max(box.max);return this}translate(offset){this.min.add(offset);this.max.add(offset);return this}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max)}};var _startP=new Vector3;var _startEnd=new Vector3;var Line3=class{constructor(start=new Vector3,end=new Vector3){this.start=start;this.end=end}set(start,end){this.start.copy(start);this.end.copy(end);return this}copy(line){this.start.copy(line.start);this.end.copy(line.end);return this}getCenter(target){return target.addVectors(this.start,this.end).multiplyScalar(.5)}delta(target){return target.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,target){return this.delta(target).multiplyScalar(t).add(this.start)}closestPointToPointParameter(point,clampToLine){_startP.subVectors(point,this.start);_startEnd.subVectors(this.end,this.start);const startEnd2=_startEnd.dot(_startEnd);const startEnd_startP=_startEnd.dot(_startP);let t=startEnd_startP/startEnd2;if(clampToLine){t=clamp(t,0,1)}return t}closestPointToPoint(point,clampToLine,target){const t=this.closestPointToPointParameter(point,clampToLine);return this.delta(target).multiplyScalar(t).add(this.start)}applyMatrix4(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this}equals(line){return line.start.equals(this.start)&&line.end.equals(this.end)}clone(){return new this.constructor().copy(this)}};var _vector$3=new Vector3;var SpotLightHelper=class extends Object3D{constructor(light,color){super();this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;const geometry=new BufferGeometry;const positions=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let i=0,j=1,l=32;i.99999){this.quaternion.set(0,0,0,1)}else if(dir.y<-.99999){this.quaternion.set(1,0,0,0)}else{_axis.set(dir.z,0,-dir.x).normalize();const radians=Math.acos(dir.y);this.quaternion.setFromAxisAngle(_axis,radians)}}setLength(length,headLength=length*.2,headWidth=headLength*.2){this.line.scale.set(1,Math.max(1e-4,length-headLength),1);this.line.updateMatrix();this.cone.scale.set(headWidth,headLength,headWidth);this.cone.position.y=length;this.cone.updateMatrix()}setColor(color){this.line.material.color.set(color);this.cone.material.color.set(color)}copy(source){super.copy(source,false);this.line.copy(source.line);this.cone.copy(source.cone);return this}};var AxesHelper=class extends LineSegments{constructor(size=1){const vertices=[0,0,0,size,0,0,0,0,0,0,size,0,0,0,0,0,0,size];const colors=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1];const geometry=new BufferGeometry;geometry.setAttribute("position",new Float32BufferAttribute(vertices,3));geometry.setAttribute("color",new Float32BufferAttribute(colors,3));const material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type="AxesHelper"}setColors(xAxisColor,yAxisColor,zAxisColor){const color=new Color;const array=this.geometry.attributes.color.array;color.set(xAxisColor);color.toArray(array,0);color.toArray(array,3);color.set(yAxisColor);color.toArray(array,6);color.toArray(array,9);color.set(zAxisColor);color.toArray(array,12);color.toArray(array,15);this.geometry.attributes.color.needsUpdate=true;return this}dispose(){this.geometry.dispose();this.material.dispose()}};var ShapePath=class{constructor(){this.type="ShapePath";this.color=new Color;this.subPaths=[];this.currentPath=null}moveTo(x2,y2){this.currentPath=new Path;this.subPaths.push(this.currentPath);this.currentPath.moveTo(x2,y2);return this}lineTo(x2,y2){this.currentPath.lineTo(x2,y2);return this}quadraticCurveTo(aCPx,aCPy,aX,aY){this.currentPath.quadraticCurveTo(aCPx,aCPy,aX,aY);return this}bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){this.currentPath.bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY);return this}splineThru(pts){this.currentPath.splineThru(pts);return this}toShapes(isCCW,noHoles){function toShapesNoHoles(inSubpaths){const shapes2=[];for(let i=0,l=inSubpaths.length;iNumber.EPSILON){if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy}if(inPt.yedgeHighPt.y)continue;if(inPt.y===edgeLowPt.y){if(inPt.x===edgeLowPt.x)return true}else{const perpEdge=edgeDy*(inPt.x-edgeLowPt.x)-edgeDx*(inPt.y-edgeLowPt.y);if(perpEdge===0)return true;if(perpEdge<0)continue;inside=!inside}}else{if(inPt.y!==edgeLowPt.y)continue;if(edgeHighPt.x<=inPt.x&&inPt.x<=edgeLowPt.x||edgeLowPt.x<=inPt.x&&inPt.x<=edgeHighPt.x)return true}}return inside}const isClockWise=ShapeUtils.isClockWise;const subPaths=this.subPaths;if(subPaths.length===0)return[];if(noHoles===true)return toShapesNoHoles(subPaths);let solid,tmpPath,tmpShape;const shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape;tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes}let holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;const betterShapeHoles=[];const newShapes=[];let newShapeHoles=[];let mainIdx=0;let tmpPoints;newShapes[mainIdx]=void 0;newShapeHoles[mainIdx]=[];for(let i=0,l=subPaths.length;i1){let ambiguous=false;let toChange=0;for(let sIdx=0,sLen=newShapes.length;sIdx0&&ambiguous===false){newShapeHoles=betterShapeHoles}}let tmpHoles;for(let i=0,il=newShapes.length;i>-e-14;baseTable[i|256]=1024>>-e-14|32768;shiftTable[i]=-e-1;shiftTable[i|256]=-e-1}else if(e<=15){baseTable[i]=e+15<<10;baseTable[i|256]=e+15<<10|32768;shiftTable[i]=13;shiftTable[i|256]=13}else if(e<128){baseTable[i]=31744;baseTable[i|256]=64512;shiftTable[i]=24;shiftTable[i|256]=24}else{baseTable[i]=31744;baseTable[i|256]=64512;shiftTable[i]=13;shiftTable[i|256]=13}}const mantissaTable=new Uint32Array(2048);const exponentTable=new Uint32Array(64);const offsetTable=new Uint32Array(64);for(let i=1;i<1024;++i){let m=i<<13;let e=0;while((m&8388608)===0){m<<=1;e-=8388608}m&=~8388608;e+=947912704;mantissaTable[i]=m|e}for(let i=1024;i<2048;++i){mantissaTable[i]=939524096+(i-1024<<13)}for(let i=1;i<31;++i){exponentTable[i]=i<<23}exponentTable[31]=1199570944;exponentTable[32]=2147483648;for(let i=33;i<63;++i){exponentTable[i]=2147483648+(i-32<<23)}exponentTable[63]=3347054592;for(let i=1;i<64;++i){if(i!==32){offsetTable[i]=1024}}return{floatView,uint32View,baseTable,shiftTable,mantissaTable,exponentTable,offsetTable}}function toHalfFloat(val){if(Math.abs(val)>65504)console.warn("THREE.DataUtils.toHalfFloat(): Value out of range.");val=clamp(val,-65504,65504);_tables.floatView[0]=val;const f=_tables.uint32View[0];const e=f>>23&511;return _tables.baseTable[e]+((f&8388607)>>_tables.shiftTable[e])}function fromHalfFloat(val){const m=val>>10;_tables.uint32View[0]=_tables.mantissaTable[_tables.offsetTable[m]+(val&1023)]+_tables.exponentTable[m];return _tables.floatView[0]}var DataUtils=Object.freeze({__proto__:null,toHalfFloat,fromHalfFloat});var ParametricGeometry=class extends BufferGeometry{constructor(){console.error("THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js");super()}};var TextGeometry=class extends BufferGeometry{constructor(){console.error("THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js");super()}};function FontLoader(){console.error("THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js")}function Font(){console.error("THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js")}function ImmediateRenderObject(){console.error("THREE.ImmediateRenderObject has been removed.")}var WebGLMultisampleRenderTarget=class extends WebGLRenderTarget{constructor(width,height,options){console.error(\'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.\');super(width,height,options);this.samples=4}};var DataTexture2DArray=class extends DataArrayTexture{constructor(data,width,height,depth){console.warn("THREE.DataTexture2DArray has been renamed to DataArrayTexture.");super(data,width,height,depth)}};var DataTexture3D=class extends Data3DTexture{constructor(data,width,height,depth){console.warn("THREE.DataTexture3D has been renamed to Data3DTexture.");super(data,width,height,depth)}};if(typeof __THREE_DEVTOOLS__!=="undefined"){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:REVISION}}))}if(typeof window!=="undefined"){if(window.__THREE__){console.warn("WARNING: Multiple instances of Three.js being imported.")}else{window.__THREE__=REVISION}}var _changeEvent={type:"change"};var _startEvent={type:"start"};var _endEvent={type:"end"};var OrbitControls=class extends EventDispatcher2{constructor(object,domElement){super();if(domElement===void 0)console.warn(\'THREE.OrbitControls: The second parameter "domElement" is now mandatory.\');if(domElement===document)console.error(\'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.\');this.object=object;this.domElement=domElement;this.domElement.style.touchAction="none";this.enabled=true;this.target=new Vector3;this.minDistance=0;this.maxDistance=Infinity;this.minZoom=0;this.maxZoom=Infinity;this.minPolarAngle=0;this.maxPolarAngle=Math.PI;this.minAzimuthAngle=-Infinity;this.maxAzimuthAngle=Infinity;this.enableDamping=false;this.dampingFactor=.05;this.enableZoom=true;this.zoomSpeed=1;this.enableRotate=true;this.rotateSpeed=1;this.enablePan=true;this.panSpeed=1;this.screenSpacePanning=true;this.keyPanSpeed=7;this.autoRotate=false;this.autoRotateSpeed=2;this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"};this.mouseButtons={LEFT:MOUSE.ROTATE,MIDDLE:MOUSE.DOLLY,RIGHT:MOUSE.PAN};this.touches={ONE:TOUCH.ROTATE,TWO:TOUCH.DOLLY_PAN};this.target0=this.target.clone();this.position0=this.object.position.clone();this.zoom0=this.object.zoom;this._domElementKeyEvents=null;this.getPolarAngle=function(){return spherical.phi};this.getAzimuthalAngle=function(){return spherical.theta};this.getDistance=function(){return this.object.position.distanceTo(this.target)};this.listenToKeyEvents=function(domElement2){domElement2.addEventListener("keydown",onKeyDown);this._domElementKeyEvents=domElement2};this.saveState=function(){scope.target0.copy(scope.target);scope.position0.copy(scope.object.position);scope.zoom0=scope.object.zoom};this.reset=function(){scope.target.copy(scope.target0);scope.object.position.copy(scope.position0);scope.object.zoom=scope.zoom0;scope.object.updateProjectionMatrix();scope.dispatchEvent(_changeEvent);scope.update();state=STATE.NONE};this.update=function(){const offset=new Vector3;const quat=new Quaternion().setFromUnitVectors(object.up,new Vector3(0,1,0));const quatInverse=quat.clone().invert();const lastPosition=new Vector3;const lastQuaternion=new Quaternion;const twoPI=2*Math.PI;return function update(){const position=scope.object.position;offset.copy(position).sub(scope.target);offset.applyQuaternion(quat);spherical.setFromVector3(offset);if(scope.autoRotate&&state===STATE.NONE){rotateLeft(getAutoRotationAngle())}if(scope.enableDamping){spherical.theta+=sphericalDelta.theta*scope.dampingFactor;spherical.phi+=sphericalDelta.phi*scope.dampingFactor}else{spherical.theta+=sphericalDelta.theta;spherical.phi+=sphericalDelta.phi}let min=scope.minAzimuthAngle;let max=scope.maxAzimuthAngle;if(isFinite(min)&&isFinite(max)){if(min<-Math.PI)min+=twoPI;else if(min>Math.PI)min-=twoPI;if(max<-Math.PI)max+=twoPI;else if(max>Math.PI)max-=twoPI;if(min<=max){spherical.theta=Math.max(min,Math.min(max,spherical.theta))}else{spherical.theta=spherical.theta>(min+max)/2?Math.max(min,spherical.theta):Math.min(max,spherical.theta)}}spherical.phi=Math.max(scope.minPolarAngle,Math.min(scope.maxPolarAngle,spherical.phi));spherical.makeSafe();spherical.radius*=scale;spherical.radius=Math.max(scope.minDistance,Math.min(scope.maxDistance,spherical.radius));if(scope.enableDamping===true){scope.target.addScaledVector(panOffset,scope.dampingFactor)}else{scope.target.add(panOffset)}offset.setFromSpherical(spherical);offset.applyQuaternion(quatInverse);position.copy(scope.target).add(offset);scope.object.lookAt(scope.target);if(scope.enableDamping===true){sphericalDelta.theta*=1-scope.dampingFactor;sphericalDelta.phi*=1-scope.dampingFactor;panOffset.multiplyScalar(1-scope.dampingFactor)}else{sphericalDelta.set(0,0,0);panOffset.set(0,0,0)}scale=1;if(zoomChanged||lastPosition.distanceToSquared(scope.object.position)>EPS||8*(1-lastQuaternion.dot(scope.object.quaternion))>EPS){scope.dispatchEvent(_changeEvent);lastPosition.copy(scope.object.position);lastQuaternion.copy(scope.object.quaternion);zoomChanged=false;return true}return false}}();this.dispose=function(){scope.domElement.removeEventListener("contextmenu",onContextMenu);scope.domElement.removeEventListener("pointerdown",onPointerDown);scope.domElement.removeEventListener("pointercancel",onPointerCancel);scope.domElement.removeEventListener("wheel",onMouseWheel);scope.domElement.removeEventListener("pointermove",onPointerMove);scope.domElement.removeEventListener("pointerup",onPointerUp);if(scope._domElementKeyEvents!==null){scope._domElementKeyEvents.removeEventListener("keydown",onKeyDown)}};const scope=this;const STATE={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let state=STATE.NONE;const EPS=1e-6;const spherical=new Spherical;const sphericalDelta=new Spherical;let scale=1;const panOffset=new Vector3;let zoomChanged=false;const rotateStart=new Vector2;const rotateEnd=new Vector2;const rotateDelta=new Vector2;const panStart=new Vector2;const panEnd=new Vector2;const panDelta=new Vector2;const dollyStart=new Vector2;const dollyEnd=new Vector2;const dollyDelta=new Vector2;const pointers=[];const pointerPositions={};function getAutoRotationAngle(){return 2*Math.PI/60/60*scope.autoRotateSpeed}function getZoomScale(){return Math.pow(.95,scope.zoomSpeed)}function rotateLeft(angle){sphericalDelta.theta-=angle}function rotateUp(angle){sphericalDelta.phi-=angle}const panLeft=function(){const v=new Vector3;return function panLeft2(distance,objectMatrix){v.setFromMatrixColumn(objectMatrix,0);v.multiplyScalar(-distance);panOffset.add(v)}}();const panUp=function(){const v=new Vector3;return function panUp2(distance,objectMatrix){if(scope.screenSpacePanning===true){v.setFromMatrixColumn(objectMatrix,1)}else{v.setFromMatrixColumn(objectMatrix,0);v.crossVectors(scope.object.up,v)}v.multiplyScalar(distance);panOffset.add(v)}}();const pan=function(){const offset=new Vector3;return function pan2(deltaX,deltaY){const element=scope.domElement;if(scope.object.isPerspectiveCamera){const position=scope.object.position;offset.copy(position).sub(scope.target);let targetDistance=offset.length();targetDistance*=Math.tan(scope.object.fov/2*Math.PI/180);panLeft(2*deltaX*targetDistance/element.clientHeight,scope.object.matrix);panUp(2*deltaY*targetDistance/element.clientHeight,scope.object.matrix)}else if(scope.object.isOrthographicCamera){panLeft(deltaX*(scope.object.right-scope.object.left)/scope.object.zoom/element.clientWidth,scope.object.matrix);panUp(deltaY*(scope.object.top-scope.object.bottom)/scope.object.zoom/element.clientHeight,scope.object.matrix)}else{console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");scope.enablePan=false}}}();function dollyOut(dollyScale){if(scope.object.isPerspectiveCamera){scale/=dollyScale}else if(scope.object.isOrthographicCamera){scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom*dollyScale));scope.object.updateProjectionMatrix();zoomChanged=true}else{console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");scope.enableZoom=false}}function dollyIn(dollyScale){if(scope.object.isPerspectiveCamera){scale*=dollyScale}else if(scope.object.isOrthographicCamera){scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom/dollyScale));scope.object.updateProjectionMatrix();zoomChanged=true}else{console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");scope.enableZoom=false}}function handleMouseDownRotate(event){rotateStart.set(event.clientX,event.clientY)}function handleMouseDownDolly(event){dollyStart.set(event.clientX,event.clientY)}function handleMouseDownPan(event){panStart.set(event.clientX,event.clientY)}function handleMouseMoveRotate(event){rotateEnd.set(event.clientX,event.clientY);rotateDelta.subVectors(rotateEnd,rotateStart).multiplyScalar(scope.rotateSpeed);const element=scope.domElement;rotateLeft(2*Math.PI*rotateDelta.x/element.clientHeight);rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight);rotateStart.copy(rotateEnd);scope.update()}function handleMouseMoveDolly(event){dollyEnd.set(event.clientX,event.clientY);dollyDelta.subVectors(dollyEnd,dollyStart);if(dollyDelta.y>0){dollyOut(getZoomScale())}else if(dollyDelta.y<0){dollyIn(getZoomScale())}dollyStart.copy(dollyEnd);scope.update()}function handleMouseMovePan(event){panEnd.set(event.clientX,event.clientY);panDelta.subVectors(panEnd,panStart).multiplyScalar(scope.panSpeed);pan(panDelta.x,panDelta.y);panStart.copy(panEnd);scope.update()}function handleMouseWheel(event){if(event.deltaY<0){dollyIn(getZoomScale())}else if(event.deltaY>0){dollyOut(getZoomScale())}scope.update()}function handleKeyDown(event){let needsUpdate=false;switch(event.code){case scope.keys.UP:pan(0,scope.keyPanSpeed);needsUpdate=true;break;case scope.keys.BOTTOM:pan(0,-scope.keyPanSpeed);needsUpdate=true;break;case scope.keys.LEFT:pan(scope.keyPanSpeed,0);needsUpdate=true;break;case scope.keys.RIGHT:pan(-scope.keyPanSpeed,0);needsUpdate=true;break}if(needsUpdate){event.preventDefault();scope.update()}}function handleTouchStartRotate(){if(pointers.length===1){rotateStart.set(pointers[0].pageX,pointers[0].pageY)}else{const x2=.5*(pointers[0].pageX+pointers[1].pageX);const y2=.5*(pointers[0].pageY+pointers[1].pageY);rotateStart.set(x2,y2)}}function handleTouchStartPan(){if(pointers.length===1){panStart.set(pointers[0].pageX,pointers[0].pageY)}else{const x2=.5*(pointers[0].pageX+pointers[1].pageX);const y2=.5*(pointers[0].pageY+pointers[1].pageY);panStart.set(x2,y2)}}function handleTouchStartDolly(){const dx=pointers[0].pageX-pointers[1].pageX;const dy=pointers[0].pageY-pointers[1].pageY;const distance=Math.sqrt(dx*dx+dy*dy);dollyStart.set(0,distance)}function handleTouchStartDollyPan(){if(scope.enableZoom)handleTouchStartDolly();if(scope.enablePan)handleTouchStartPan()}function handleTouchStartDollyRotate(){if(scope.enableZoom)handleTouchStartDolly();if(scope.enableRotate)handleTouchStartRotate()}function handleTouchMoveRotate(event){if(pointers.length==1){rotateEnd.set(event.pageX,event.pageY)}else{const position=getSecondPointerPosition(event);const x2=.5*(event.pageX+position.x);const y2=.5*(event.pageY+position.y);rotateEnd.set(x2,y2)}rotateDelta.subVectors(rotateEnd,rotateStart).multiplyScalar(scope.rotateSpeed);const element=scope.domElement;rotateLeft(2*Math.PI*rotateDelta.x/element.clientHeight);rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight);rotateStart.copy(rotateEnd)}function handleTouchMovePan(event){if(pointers.length===1){panEnd.set(event.pageX,event.pageY)}else{const position=getSecondPointerPosition(event);const x2=.5*(event.pageX+position.x);const y2=.5*(event.pageY+position.y);panEnd.set(x2,y2)}panDelta.subVectors(panEnd,panStart).multiplyScalar(scope.panSpeed);pan(panDelta.x,panDelta.y);panStart.copy(panEnd)}function handleTouchMoveDolly(event){const position=getSecondPointerPosition(event);const dx=event.pageX-position.x;const dy=event.pageY-position.y;const distance=Math.sqrt(dx*dx+dy*dy);dollyEnd.set(0,distance);dollyDelta.set(0,Math.pow(dollyEnd.y/dollyStart.y,scope.zoomSpeed));dollyOut(dollyDelta.y);dollyStart.copy(dollyEnd)}function handleTouchMoveDollyPan(event){if(scope.enableZoom)handleTouchMoveDolly(event);if(scope.enablePan)handleTouchMovePan(event)}function handleTouchMoveDollyRotate(event){if(scope.enableZoom)handleTouchMoveDolly(event);if(scope.enableRotate)handleTouchMoveRotate(event)}function onPointerDown(event){if(scope.enabled===false)return;if(pointers.length===0){scope.domElement.setPointerCapture(event.pointerId);scope.domElement.addEventListener("pointermove",onPointerMove);scope.domElement.addEventListener("pointerup",onPointerUp)}addPointer(event);if(event.pointerType==="touch"){onTouchStart(event)}else{onMouseDown(event)}}function onPointerMove(event){if(scope.enabled===false)return;if(event.pointerType==="touch"){onTouchMove(event)}else{onMouseMove(event)}}function onPointerUp(event){removePointer(event);if(pointers.length===0){scope.domElement.releasePointerCapture(event.pointerId);scope.domElement.removeEventListener("pointermove",onPointerMove);scope.domElement.removeEventListener("pointerup",onPointerUp)}scope.dispatchEvent(_endEvent);state=STATE.NONE}function onPointerCancel(event){removePointer(event)}function onMouseDown(event){let mouseAction;switch(event.button){case 0:mouseAction=scope.mouseButtons.LEFT;break;case 1:mouseAction=scope.mouseButtons.MIDDLE;break;case 2:mouseAction=scope.mouseButtons.RIGHT;break;default:mouseAction=-1}switch(mouseAction){case MOUSE.DOLLY:if(scope.enableZoom===false)return;handleMouseDownDolly(event);state=STATE.DOLLY;break;case MOUSE.ROTATE:if(event.ctrlKey||event.metaKey||event.shiftKey){if(scope.enablePan===false)return;handleMouseDownPan(event);state=STATE.PAN}else{if(scope.enableRotate===false)return;handleMouseDownRotate(event);state=STATE.ROTATE}break;case MOUSE.PAN:if(event.ctrlKey||event.metaKey||event.shiftKey){if(scope.enableRotate===false)return;handleMouseDownRotate(event);state=STATE.ROTATE}else{if(scope.enablePan===false)return;handleMouseDownPan(event);state=STATE.PAN}break;default:state=STATE.NONE}if(state!==STATE.NONE){scope.dispatchEvent(_startEvent)}}function onMouseMove(event){switch(state){case STATE.ROTATE:if(scope.enableRotate===false)return;handleMouseMoveRotate(event);break;case STATE.DOLLY:if(scope.enableZoom===false)return;handleMouseMoveDolly(event);break;case STATE.PAN:if(scope.enablePan===false)return;handleMouseMovePan(event);break}}function onMouseWheel(event){if(scope.enabled===false||scope.enableZoom===false||state!==STATE.NONE)return;event.preventDefault();scope.dispatchEvent(_startEvent);handleMouseWheel(event);scope.dispatchEvent(_endEvent)}function onKeyDown(event){if(scope.enabled===false||scope.enablePan===false)return;handleKeyDown(event)}function onTouchStart(event){trackPointer(event);switch(pointers.length){case 1:switch(scope.touches.ONE){case TOUCH.ROTATE:if(scope.enableRotate===false)return;handleTouchStartRotate();state=STATE.TOUCH_ROTATE;break;case TOUCH.PAN:if(scope.enablePan===false)return;handleTouchStartPan();state=STATE.TOUCH_PAN;break;default:state=STATE.NONE}break;case 2:switch(scope.touches.TWO){case TOUCH.DOLLY_PAN:if(scope.enableZoom===false&&scope.enablePan===false)return;handleTouchStartDollyPan();state=STATE.TOUCH_DOLLY_PAN;break;case TOUCH.DOLLY_ROTATE:if(scope.enableZoom===false&&scope.enableRotate===false)return;handleTouchStartDollyRotate();state=STATE.TOUCH_DOLLY_ROTATE;break;default:state=STATE.NONE}break;default:state=STATE.NONE}if(state!==STATE.NONE){scope.dispatchEvent(_startEvent)}}function onTouchMove(event){trackPointer(event);switch(state){case STATE.TOUCH_ROTATE:if(scope.enableRotate===false)return;handleTouchMoveRotate(event);scope.update();break;case STATE.TOUCH_PAN:if(scope.enablePan===false)return;handleTouchMovePan(event);scope.update();break;case STATE.TOUCH_DOLLY_PAN:if(scope.enableZoom===false&&scope.enablePan===false)return;handleTouchMoveDollyPan(event);scope.update();break;case STATE.TOUCH_DOLLY_ROTATE:if(scope.enableZoom===false&&scope.enableRotate===false)return;handleTouchMoveDollyRotate(event);scope.update();break;default:state=STATE.NONE}}function onContextMenu(event){if(scope.enabled===false)return;event.preventDefault()}function addPointer(event){pointers.push(event)}function removePointer(event){delete pointerPositions[event.pointerId];for(let i=0;i end && e.g > 0.8281 && e.r == 0.0 ) ) break;\n }\n\n // We correct the previous (-0.25, -0.125) offset we applied:\n texcoord.x += 0.25 * resolution.x;\n\n // The searches are bias by 1, so adjust the coords accordingly:\n texcoord.x += resolution.x;\n\n // Disambiguate the length added by the last step:\n texcoord.x += 2.0 * resolution.x; // Undo last step\n texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);\n\n return texcoord.x;\n }\n\n float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {\n vec2 e = vec2( 0.0, 1.0 );\n\n for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for\n e = texture2D( edgesTex, texcoord, 0.0 ).rg;\n texcoord += vec2( 2.0, 0.0 ) * resolution;\n if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;\n }\n\n texcoord.x -= 0.25 * resolution.x;\n texcoord.x -= resolution.x;\n texcoord.x -= 2.0 * resolution.x;\n texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );\n\n return texcoord.x;\n }\n\n float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {\n vec2 e = vec2( 1.0, 0.0 );\n\n for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for\n e = texture2D( edgesTex, texcoord, 0.0 ).rg;\n texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign\n if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;\n }\n\n texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign\n texcoord.y -= resolution.y; // WebGL port note: Changed sign\n texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign\n texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign\n\n return texcoord.y;\n }\n\n float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {\n vec2 e = vec2( 1.0, 0.0 );\n\n for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for\n e = texture2D( edgesTex, texcoord, 0.0 ).rg;\n texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign\n if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;\n }\n\n texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign\n texcoord.y += resolution.y; // WebGL port note: Changed sign\n texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign\n texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign\n\n return texcoord.y;\n }\n\n vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {\n // Rounding prevents precision errors of bilinear filtering:\n vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;\n\n // We do a scale and bias for mapping to texel space:\n texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );\n\n // Move to proper place, according to the subpixel offset:\n texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;\n\n return texture2D( areaTex, texcoord, 0.0 ).rg;\n }\n\n vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {\n vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );\n\n vec2 e = texture2D( edgesTex, texcoord ).rg;\n\n if ( e.g > 0.0 ) { // Edge at north\n vec2 d;\n\n // Find the distance to the left:\n vec2 coords;\n coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );\n coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET)\n d.x = coords.x;\n\n // Now fetch the left crossing edges, two at a time using bilinear\n // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to\n // discern what value each edge has:\n float e1 = texture2D( edgesTex, coords, 0.0 ).r;\n\n // Find the distance to the right:\n coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );\n d.y = coords.x;\n\n // We want the distances to be in pixel units (doing this here allow to\n // better interleave arithmetic and memory accesses):\n d = d / resolution.x - pixcoord.x;\n\n // SMAAArea below needs a sqrt, as the areas texture is compressed\n // quadratically:\n vec2 sqrt_d = sqrt( abs( d ) );\n\n // Fetch the right crossing edges:\n coords.y -= 1.0 * resolution.y; // WebGL port note: Added\n float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;\n\n // Ok, we know how this pattern looks like, now it is time for getting\n // the actual area:\n weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );\n }\n\n if ( e.r > 0.0 ) { // Edge at west\n vec2 d;\n\n // Find the distance to the top:\n vec2 coords;\n\n coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );\n coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x;\n d.x = coords.y;\n\n // Fetch the top crossing edges:\n float e1 = texture2D( edgesTex, coords, 0.0 ).g;\n\n // Find the distance to the bottom:\n coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );\n d.y = coords.y;\n\n // We want the distances to be in pixel units:\n d = d / resolution.y - pixcoord.y;\n\n // SMAAArea below needs a sqrt, as the areas texture is compressed\n // quadratically:\n vec2 sqrt_d = sqrt( abs( d ) );\n\n // Fetch the bottom crossing edges:\n coords.y -= 1.0 * resolution.y; // WebGL port note: Added\n float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;\n\n // Get the area for this direction:\n weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );\n }\n\n return weights;\n }\n\n void main() {\n\n gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );\n\n }`};var SMAABlendShader={uniforms:{"tDiffuse":{value:null},"tColor":{value:null},"resolution":{value:new Vector2(1/1024,1/512)}},vertexShader:`\n\n uniform vec2 resolution;\n\n varying vec2 vUv;\n varying vec4 vOffset[ 2 ];\n\n void SMAANeighborhoodBlendingVS( vec2 texcoord ) {\n vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component\n vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component\n }\n\n void main() {\n\n vUv = uv;\n\n SMAANeighborhoodBlendingVS( vUv );\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n }`,fragmentShader:`\n\n uniform sampler2D tDiffuse;\n uniform sampler2D tColor;\n uniform vec2 resolution;\n\n varying vec2 vUv;\n varying vec4 vOffset[ 2 ];\n\n vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {\n // Fetch the blending weights for current pixel:\n vec4 a;\n a.xz = texture2D( blendTex, texcoord ).xz;\n a.y = texture2D( blendTex, offset[ 1 ].zw ).g;\n a.w = texture2D( blendTex, offset[ 1 ].xy ).a;\n\n // Is there any blending weight with a value greater than 0.0?\n if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {\n return texture2D( colorTex, texcoord, 0.0 );\n } else {\n // Up to 4 lines can be crossing a pixel (one through each edge). We\n // favor blending by choosing the line with the maximum weight for each\n // direction:\n vec2 offset;\n offset.x = a.a > a.b ? a.a : -a.b; // left vs. right\n offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs\n\n // Then we go in the direction that has the maximum weight:\n if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical\n offset.y = 0.0;\n } else {\n offset.x = 0.0;\n }\n\n // Fetch the opposite color and lerp by hand:\n vec4 C = texture2D( colorTex, texcoord, 0.0 );\n texcoord += sign( offset ) * resolution;\n vec4 Cop = texture2D( colorTex, texcoord, 0.0 );\n float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );\n\n // WebGL port note: Added gamma correction\n C.xyz = pow(C.xyz, vec3(2.2));\n Cop.xyz = pow(Cop.xyz, vec3(2.2));\n vec4 mixed = mix(C, Cop, s);\n mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));\n\n return mixed;\n }\n }\n\n void main() {\n\n gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );\n\n }`};var SMAAPass=class extends Pass{constructor(width,height){super();this.edgesRT=new WebGLRenderTarget(width,height,{depthBuffer:false});this.edgesRT.texture.name="SMAAPass.edges";this.weightsRT=new WebGLRenderTarget(width,height,{depthBuffer:false});this.weightsRT.texture.name="SMAAPass.weights";const scope=this;const areaTextureImage=new Image;areaTextureImage.src=this.getAreaTexture();areaTextureImage.onload=function(){scope.areaTexture.needsUpdate=true};this.areaTexture=new Texture;this.areaTexture.name="SMAAPass.area";this.areaTexture.image=areaTextureImage;this.areaTexture.minFilter=LinearFilter;this.areaTexture.generateMipmaps=false;this.areaTexture.flipY=false;const searchTextureImage=new Image;searchTextureImage.src=this.getSearchTexture();searchTextureImage.onload=function(){scope.searchTexture.needsUpdate=true};this.searchTexture=new Texture;this.searchTexture.name="SMAAPass.search";this.searchTexture.image=searchTextureImage;this.searchTexture.magFilter=NearestFilter;this.searchTexture.minFilter=NearestFilter;this.searchTexture.generateMipmaps=false;this.searchTexture.flipY=false;if(SMAAEdgesShader===void 0){console.error("THREE.SMAAPass relies on SMAAShader")}this.uniformsEdges=UniformsUtils.clone(SMAAEdgesShader.uniforms);this.uniformsEdges["resolution"].value.set(1/width,1/height);this.materialEdges=new ShaderMaterial({defines:Object.assign({},SMAAEdgesShader.defines),uniforms:this.uniformsEdges,vertexShader:SMAAEdgesShader.vertexShader,fragmentShader:SMAAEdgesShader.fragmentShader});this.uniformsWeights=UniformsUtils.clone(SMAAWeightsShader.uniforms);this.uniformsWeights["resolution"].value.set(1/width,1/height);this.uniformsWeights["tDiffuse"].value=this.edgesRT.texture;this.uniformsWeights["tArea"].value=this.areaTexture;this.uniformsWeights["tSearch"].value=this.searchTexture;this.materialWeights=new ShaderMaterial({defines:Object.assign({},SMAAWeightsShader.defines),uniforms:this.uniformsWeights,vertexShader:SMAAWeightsShader.vertexShader,fragmentShader:SMAAWeightsShader.fragmentShader});this.uniformsBlend=UniformsUtils.clone(SMAABlendShader.uniforms);this.uniformsBlend["resolution"].value.set(1/width,1/height);this.uniformsBlend["tDiffuse"].value=this.weightsRT.texture;this.materialBlend=new ShaderMaterial({uniforms:this.uniformsBlend,vertexShader:SMAABlendShader.vertexShader,fragmentShader:SMAABlendShader.fragmentShader});this.needsSwap=false;this.fsQuad=new FullScreenQuad(null)}render(renderer,writeBuffer,readBuffer){this.uniformsEdges["tDiffuse"].value=readBuffer.texture;this.fsQuad.material=this.materialEdges;renderer.setRenderTarget(this.edgesRT);if(this.clear)renderer.clear();this.fsQuad.render(renderer);this.fsQuad.material=this.materialWeights;renderer.setRenderTarget(this.weightsRT);if(this.clear)renderer.clear();this.fsQuad.render(renderer);this.uniformsBlend["tColor"].value=readBuffer.texture;this.fsQuad.material=this.materialBlend;if(this.renderToScreen){renderer.setRenderTarget(null);this.fsQuad.render(renderer)}else{renderer.setRenderTarget(writeBuffer);if(this.clear)renderer.clear();this.fsQuad.render(renderer)}}setSize(width,height){this.edgesRT.setSize(width,height);this.weightsRT.setSize(width,height);this.materialEdges.uniforms["resolution"].value.set(1/width,1/height);this.materialWeights.uniforms["resolution"].value.set(1/width,1/height);this.materialBlend.uniforms["resolution"].value.set(1/width,1/height)}getAreaTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K+e0N11yNfkKvwUdwdlUAXPHHL38oa15f/i/46Ih6SuMSPmLAYAwyRKn7dfMGH97jaMFBYCJUgotIC2YAdu+LyW9vvubxAP8kAL8H/koAuOKP3+q6+xGnd5kdYCeECnGIJViwGJMAkQKfDvB3WZxjLKGh8VSCCzhwEWBpMc5/kBbjawT4HnwJfhr+pPBIu7uu+OOTo9vsmtQcniMBGkKFd4jDWMSCRUpLjJYNJkM+IRzQ+PQvIeAMTrBS2LEiaiR9b/5PuT6Ap/AcfAFO4Y3dA3DFH7/VS+M8k4baEAQfMI4QfbVDDGIRg7GKaIY52qAjTAgTvGBAPGIIghOCYAUrGFNgzA7Q3QhgCwfwAnwe5vDejgG44o/fbm1C5ZlYQvQDARPAIQGxCWBM+wWl37ZQESb4gImexGMDouhGLx1Cst0Saa4b4AqO4Hk4gxo+3DHAV/nx27p3JziPM2pVgoiia5MdEzCGULprIN7gEEeQ5IQxEBBBQnxhsDb5auGmAAYcHMA9eAAz8PBol8/xij9+C4Djlim4gJjWcwZBhCBgMIIYxGAVIkH3ZtcBuLdtRFMWsPGoY9rN+HoBji9VBYdwD2ZQg4cnO7OSq/z4rU5KKdwVbFAjNojCQzTlCLPFSxtamwh2jMUcEgg2Wm/6XgErIBhBckQtGN3CzbVacERgCnfgLswhnvqf7QyAq/z4rRZm1YglYE3affGITaZsdIe2FmMIpnOCap25I6jt2kCwCW0D1uAD9sZctNGXcQIHCkINDQgc78aCr+zjtw3BU/ijdpw3zhCwcaONwBvdeS2YZKkJNJsMPf2JKEvC28RXxxI0ASJyzQCjCEQrO4Q7sFArEzjZhaFc4cdv+/JFdKULM4px0DfUBI2hIsy06BqLhGTQEVdbfAIZXYMPesq6VoCHICzUyjwInO4Y411//LYLs6TDa9wvg2CC2rElgAnpTBziThxaL22MYhzfkghz6GAs2VHbbdM91VZu1MEEpupMMwKyVTb5ij9+u4VJG/5EgEMMmFF01cFai3isRbKbzb+YaU/MQbAm2XSMoUPAmvZzbuKYRIFApbtlrfFuUGd6vq2hXNnH78ZLh/iFhsQG3T4D1ib7k5CC6vY0DCbtrohgLEIClXiGtl10zc0CnEGIhhatLBva7NP58Tvw0qE8yWhARLQ8h4+AhQSP+I4F5xoU+VilGRJs6wnS7ruti/4KvAY/CfdgqjsMy4pf8fodQO8/gnuX3f/3xi3om1/h7THr+co3x93PP9+FBUfbNUjcjEmhcrkT+8K7ml7V10Jo05mpIEFy1NmCJWx9SIKKt+EjAL4Ez8EBVOB6havuT/rByPvHXK+9zUcfcbb254+9fydJknYnRr1oGfdaiAgpxu1Rx/Rek8KISftx3L+DfsLWAANn8Hvw0/AFeAGO9DFV3c6D+CcWbL8Dj9e7f+T1k8AZv/d7+PXWM/Z+VvdCrIvuAKO09RpEEQJM0Ci6+B4xhTWr4cZNOvhktabw0ta0rSJmqz3Yw5/AKXwenod7cAhTmBSPKf6JBdvH8IP17h95pXqw50/+BFnj88fev4NchyaK47OPhhtI8RFSvAfDSNh0Ck0p2gLxGkib5NJj/JWCr90EWQJvwBzO4AHcgztwAFN1evHPUVGwfXON+0debT1YeGON9Yy9/63X+OguiwmhIhQhD7l4sMqlG3D86Suc3qWZ4rWjI1X7u0Ytw6x3rIMeIOPDprfe2XzNgyj6PahhBjO4C3e6puDgXrdg+/5l948vF3bqwZetZ+z9Rx9zdIY5pInPK4Nk0t+l52xdK2B45Qd87nM8fsD5EfUhIcJcERw4RdqqH7Yde5V7m1vhNmtedkz6EDzUMF/2jJYWbC+4fzzA/Y+/8PPH3j9dcBAPIRP8JLXd5BpAu03aziOL3VVHZzz3CXWDPWd+SH2AnxIqQoTZpo9Ckc6HIrFbAbzNmlcg8Ag8NFDDAhbJvTBZXbC94P7t68EXfv6o+21gUtPETU7bbkLxvNKRFG2+KXzvtObonPP4rBvsgmaKj404DlshFole1Glfh02fE7bYR7dZ82oTewIBGn1Md6CG6YUF26X376oevOLzx95vhUmgblI6LBZwTCDY7vMq0op5WVXgsObOXJ+1x3qaBl9j1FeLxbhU9w1F+Wiba6s1X/TBz1LnUfuYDi4r2C69f1f14BWfP+p+W2GFKuC9phcELMYRRLur9DEZTUdEH+iEqWdaM7X4WOoPGI+ZYD2+wcQ+y+ioHUZ9dTDbArzxmi/bJI9BND0Ynd6lBdve/butBw8+f/T9D3ABa3AG8W3VPX4hBin+bj8dMMmSpp5pg7fJ6xrBFE2WQQEWnV8Qg3FbAWzYfM1rREEnmvkN2o1+acG2d/9u68GDzx91v3mAjb1zkpqT21OipPKO0b9TO5W0nTdOmAQm0TObts3aBKgwARtoPDiCT0gHgwnbArzxmtcLc08HgF1asN0C4Ms/fvD5I+7PhfqyXE/b7RbbrGyRQRT9ARZcwAUmgdoz0ehJ9Fn7QAhUjhDAQSw0bV3T3WbNa59jzmiP6GsWbGXDX2ytjy8+f9T97fiBPq9YeLdBmyuizZHaqXITnXiMUEEVcJ7K4j3BFPurtB4bixW8wTpweL8DC95szWMOqucFYGsWbGU7p3TxxxefP+r+oTVktxY0v5hbq3KiOKYnY8ddJVSBxuMMVffNbxwIOERShst73HZ78DZrHpmJmH3K6sGz0fe3UUj0eyRrSCGTTc+rjVNoGzNSv05srAxUBh8IhqChiQgVNIIBH3AVPnrsnXQZbLTm8ammv8eVXn/vWpaTem5IXRlt+U/LA21zhSb9cye6jcOfCnOwhIAYXAMVTUNV0QhVha9xjgA27ODJbLbmitt3tRN80lqG6N/khgot4ZVlOyO4WNg3OIMzhIZQpUEHieg2im6F91hB3I2tubql6BYNN9Hj5S7G0G2tahslBWKDnOiIvuAEDzakDQKDNFQT6gbn8E2y4BBubM230YIpBnDbMa+y3dx0n1S0BtuG62lCCXwcY0F72T1VRR3t2ONcsmDjbmzNt9RFs2LO2hQNyb022JisaI8rAWuw4HI3FuAIhZdOGIcdjLJvvObqlpqvWTJnnQbyi/1M9O8UxWhBs//H42I0q1Yb/XPGONzcmm+ri172mHKvZBpHkJaNJz6v9jxqiklDj3U4CA2ugpAaYMWqNXsdXbmJNd9egCnJEsphXNM+MnK3m0FCJ5S1kmJpa3DgPVbnQnPGWIDspW9ozbcO4K/9LkfaQO2KHuqlfFXSbdNzcEcwoqNEFE9zcIXu9/6n/ym/BC/C3aJLzEKPuYVlbFnfhZ8kcWxV3dbv4bKl28566wD+8C53aw49lTABp9PWbsB+knfc/Li3eVizf5vv/xmvnPKg5ihwKEwlrcHqucuVcVOxEv8aH37E3ZqpZypUulrHEtIWKUr+txHg+ojZDGlwnqmkGlzcVi1dLiNSJiHjfbRNOPwKpx9TVdTn3K05DBx4psIk4Ei8aCkJahRgffk4YnEXe07T4H2RR1u27E6wfQsBDofUgjFUFnwC2AiVtA+05J2zpiDK2Oa0c5fmAecN1iJzmpqFZxqYBCYhFTCsUNEmUnIcZ6aEA5rQVhEywG6w7HSW02XfOoBlQmjwulOFQAg66SvJblrTEX1YtJ3uG15T/BH1OfOQeuR8g/c0gdpT5fx2SKbs9EfHTKdM8A1GaJRHLVIwhcGyydZsbifAFVKl5EMKNU2Hryo+06BeTgqnxzYjThVySDikbtJPieco75lYfKAJOMEZBTjoITuWHXXZVhcUDIS2hpiXHV9Ku4u44bN5OYLDOkJo8w+xJSMbhBRHEdEs9JZUCkQrPMAvaHyLkxgkEHxiNkx/x2YB0mGsQ8EUWj/stW5YLhtS5SMu+/YBbNPDCkGTUybN8krRLBGPlZkVOA0j+a1+rkyQKWGaPHPLZOkJhioQYnVZ2hS3zVxMtgC46KuRwbJNd9nV2PHgb36F194ecf/Yeu2vAFe5nm/bRBFrnY4BauE8ERmZRFUn0k8hbftiVYSKMEme2dJCJSCGYAlNqh87bXOPdUkGy24P6d1ll21MBqqx48Fvv8ZHH8HZFY7j/uAq1xMJUFqCSUlJPmNbIiNsmwuMs/q9CMtsZsFO6SprzCS1Z7QL8xCQClEelpjTduDMsmWD8S1PT152BtvmIGvUeDA/yRn83u/x0/4qxoPHjx+PXY9pqX9bgMvh/Nz9kpP4pOe1/fYf3axUiMdHLlPpZCNjgtNFAhcHEDxTumNONhHrBduW+vOyY++70WWnPXj98eA4kOt/mj/5E05l9+O4o8ePx67HFqyC+qSSnyselqjZGaVK2TadbFLPWAQ4NBhHqDCCV7OTpo34AlSSylPtIdd2AJZlyzYQrDJ5lcWGNceD80CunPLGGzsfD+7wRb95NevJI5docQ3tgCyr5bGnyaPRlmwNsFELViOOx9loebGNq2moDOKpHLVP5al2cymWHbkfzGXL7kfRl44H9wZy33tvt+PB/Xnf93e+nh5ZlU18wCiRUa9m7kib9LYuOk+hudQNbxwm0AQqbfloimaB2lM5fChex+ylMwuTbfmXQtmWlenZljbdXTLuOxjI/fDDHY4Hjx8/Hrse0zXfPFxbUN1kKqSCCSk50m0Ajtx3ub9XHBKHXESb8iO6E+qGytF4nO0OG3SXzbJlhxBnKtKyl0NwybjvYCD30aMdjgePHz8eu56SVTBbgxJMliQ3Oauwg0QHxXE2Ez/EIReLdQj42Gzb4CLS0YJD9xUx7bsi0vJi5mUbW1QzL0h0PFk17rtiIPfJk52MB48fPx67npJJwyrBa2RCCQRTbGZSPCxTPOiND4G2pYyOQ4h4jINIJh5wFU1NFZt+IsZ59LSnDqBjZ2awbOku+yInunLcd8VA7rNnOxkPHj9+PGY9B0MWJJNozOJmlglvDMXDEozdhQWbgs/U6oBanGzLrdSNNnZFjOkmbi5bNt1lX7JLLhn3vXAg9/h4y/Hg8ePHI9dzQMEkWCgdRfYykYKnkP7D4rIujsujaKPBsB54vE2TS00ccvFY/Tth7JXeq1hz+qgVy04sAJawTsvOknHfCwdyT062HA8eP348Zj0vdoXF4pilKa2BROed+9fyw9rWRXeTFXESMOanvDZfJuJaSXouQdMdDJZtekZcLLvEeK04d8m474UDuaenW44Hjx8/Xns9YYqZpszGWB3AN/4VHw+k7WSFtJ3Qicuqb/NlVmgXWsxh570xg2UwxUw3WfO6B5nOuO8aA7lnZxuPB48fPx6znm1i4bsfcbaptF3zNT78eFPtwi1OaCNOqp1x3zUGcs/PN++AGD1+fMXrSVm2baTtPhPahbPhA71wIHd2bXzRa69nG+3CraTtPivahV/55tXWg8fyRY/9AdsY8VbSdp8V7cKrrgdfM//z6ILQFtJ2nxHtwmuoB4/kf74+gLeRtvvMaBdeSz34+vifx0YG20jbfTa0C6+tHrwe//NmOG0L8EbSdp8R7cLrrQe/996O+ai3ujQOskpTNULa7jOjXXj99eCd8lHvoFiwsbTdZ0a78PrrwTvlo966pLuRtB2fFe3Cm6oHP9kNH/W2FryxtN1nTLvwRurBO+Kj3pWXHidtx2dFu/Bm68Fb81HvykuPlrb7LGkX3mw9eGs+6h1Y8MbSdjegXcguQLjmevDpTQLMxtJ2N6NdyBZu9AbrwVvwUW+LbteULUpCdqm0HTelXbhNPe8G68Gb8lFvVfYfSNuxvrTdTWoXbozAzdaDZzfkorOj1oxVxlIMlpSIlpLrt8D4hrQL17z+c3h6hU/wv4Q/utps4+bm+6P/hIcf0JwQ5oQGPBL0eKPTYEXTW+eL/2DKn73J9BTXYANG57hz1cEMviVf/4tf5b/6C5pTQkMIWoAq7hTpOJjtAM4pxKu5vg5vXeUrtI09/Mo/5H+4z+Mp5xULh7cEm2QbRP2tFIKR7WM3fPf/jZ3SWCqLM2l4NxID5zB72HQXv3jj/8mLR5xXNA5v8EbFQEz7PpRfl1+MB/hlAN65qgDn3wTgH13hK7T59bmP+NIx1SHHU84nLOITt3iVz8mNO+lPrjGAnBFqmioNn1mTyk1ta47R6d4MrX7tjrnjYUpdUbv2rVr6YpVfsGG58AG8Ah9eyUN8CX4WfgV+G8LVWPDGb+Zd4cU584CtqSbMKxauxTg+dyn/LkVgA+IR8KHtejeFKRtTmLLpxN6mYVLjYxwXf5x2VofiZcp/lwKk4wGOpYDnoIZPdg/AAbwMfx0+ge9dgZvYjuqKe4HnGnykYo5TvJbG0Vj12JagRhwKa44H95ShkZa5RyLGGdfYvG7aw1TsF6iapPAS29mNS3NmsTQZCmgTzFwgL3upCTgtBTRwvGMAKrgLn4evwin8+afJRcff+8izUGUM63GOOuAs3tJkw7J4kyoNreqrpO6cYLQeFUd7TTpr5YOTLc9RUUogUOVJQ1GYJaFLAW0oTmKyYS46ZooP4S4EON3xQ5zC8/CX4CnM4c1PE8ApexpoYuzqlP3d4S3OJP8ZDK7cKWNaTlqmgDiiHwl1YsE41w1zT4iRTm3DBqxvOUsbMKKDa/EHxagtnta072ejc3DOIh5ojvh8l3tk1JF/AV6FU6jh3U8HwEazLgdCLYSQ+MYiAI2ltomkzttUb0gGHdSUUgsIYjTzLG3mObX4FBRaYtpDVNZrih9TgTeYOBxsEnN1gOCTM8Bsw/ieMc75w9kuAT6A+/AiHGvN/+Gn4KRkiuzpNNDYhDGFndWRpE6SVfm8U5bxnSgVV2jrg6JCKmneqey8VMFgq2+AM/i4L4RUbfSi27lNXZ7R7W9RTcq/q9fk4Xw3AMQd4I5ifAZz8FcVtm9SAom/dyN4lczJQW/kC42ZrHgcCoIf1oVMKkVItmMBi9cOeNHGLqOZk+QqQmrbc5YmYgxELUUN35z2iohstgfLIFmcMV7s4CFmI74L9+EFmGsi+tGnAOD4Yk9gIpo01Y4cA43BWGygMdr4YZekG3OBIUXXNukvJS8tqa06e+lSDCtnqqMFu6hWHXCF+WaYt64m9QBmNxi7Ioy7D+fa1yHw+FMAcPt7SysFLtoG4PXAk7JOA3aAxBRqUiAdU9Yp5lK3HLSRFtOim0sa8euEt08xvKjYjzeJ2GU7YawexrnKI9tmobInjFXCewpwriY9+RR4aaezFhMhGCppKwom0ChrgFlKzyPKkGlTW1YQrE9HJqu8hKGgMc6hVi5QRq0PZxNfrYNgE64utmRv6KKHRpxf6VDUaOvNP5jCEx5q185My/7RKz69UQu2im5k4/eownpxZxNLwiZ1AZTO2ZjWjkU9uaB2HFn6Q3u0JcsSx/qV9hTEApRzeBLDJQXxYmTnq7bdLa3+uqFrxLJ5w1TehnNHx5ECvCh2g2c3hHH5YsfdaSKddztfjQ6imKFGSyFwlLzxEGPp6r5IevVjk1AMx3wMqi1NxDVjLBiPs9tbsCkIY5we5/ML22zrCScFxnNtzsr9Wcc3CnD+pYO+4VXXiDE0oc/vQQ/fDK3oPESJMYXNmJa/DuloJZkcTpcYE8lIH8Dz8DJMiynNC86Mb2lNaaqP/+L7f2fcE/yP7/Lde8xfgSOdMxvOixZf/9p3+M4hT1+F+zApxg9XfUvYjc8qX2lfOOpK2gNRtB4flpFu9FTKCp2XJRgXnX6olp1zyYjTKJSkGmLE2NjUr1bxFM4AeAAHBUFIeSLqXR+NvH/M9fOnfHzOD2vCSyQJKzfgsCh+yi/Mmc35F2fUrw7miW33W9hBD1vpuUojFphIyvg7aTeoymDkIkeW3XLHmguMzbIAJejN6B5MDrhipE2y6SoFRO/AK/AcHHZHNIfiWrEe/C6cr3f/yOvrQKB+zMM55/GQdLDsR+ifr5Fiuu+/y+M78LzOE5dsNuXC3PYvYWd8NXvphLSkJIasrlD2/HOqQ+RjcRdjKTGWYhhVUm4yxlyiGPuMsZR7sMCHUBeTuNWA7if+ifXgc/hovftHXs/DV+Fvwe+f8shzMiMcweFgBly3//vwJfg5AN4450fn1Hd1Rm1aBLu22Dy3y3H2+OqMemkbGZ4jozcDjJf6596xOLpC0eMTHbKnxLxH27uZ/bMTGs2jOaMOY4m87CfQwF0dw53oa1k80JRuz/XgS+8fX3N9Af4qPIMfzKgCp4H5TDGe9GGeFPzSsZz80SlPTxXjgwJmC45njzgt2vbQ4b4OAdUK4/vWhO8d8v6EE8fMUsfakXbPpFJeLs2ubM/qdm/la3WP91uWhxXHjoWhyRUq2iJ/+5mA73zwIIo+LoZ/SgvIRjAd1IMvvn98PfgOvAJfhhm8scAKVWDuaRaK8aQ9f7vuPDH6Bj47ZXau7rqYJ66mTDwEDU6lLbCjCK0qTXyl5mnDoeNRxanj3FJbaksTk0faXxHxLrssgPkWB9LnA/MFleXcJozzjwsUvUG0X/QCve51qkMDXp9mtcyOy3rwBfdvVJK7D6/ACSzg3RoruIq5UDeESfEmVclDxnniU82vxMLtceD0hGZWzBNPMM/jSPne2OVatiTKUpY5vY7gc0LdUAWeWM5tH+O2I66AOWw9xT2BuyRVLGdoDHUsVRXOo/c+ZdRXvFfnxWyIV4upFLCl9eAL7h8Zv0QH8Ry8pA2cHzQpGesctVA37ZtklBTgHjyvdSeKY/RZw/kJMk0Y25cSNRWSigQtlULPTw+kzuJPeYEkXjQRpoGZobYsLF79pyd1dMRHInbgFTZqNLhDqiIsTNpoex2WLcy0/X6rHcdMMQvFSd5dWA++4P7xv89deACnmr36uGlL69bRCL6BSZsS6c0TU2TKK5gtWCzgAOOwQcurqk9j8whvziZSMLcq5hbuwBEsYjopUBkqw1yYBGpLA97SRElEmx5MCInBY5vgLk94iKqSWmhIGmkJ4Bi9m4L645J68LyY4wsFYBfUg5feP/6gWWm58IEmKQM89hq7KsZNaKtP5TxxrUZZVkNmMJtjbKrGxLNEbHPJxhqy7lAmbC32ZqeF6lTaknRWcYaFpfLUBh/rwaQycCCJmW15Kstv6jRHyJFry2C1ahkkIW0LO75s61+owxK1y3XqweX9m5YLM2DPFeOjn/iiqCKJ+yKXF8t5Yl/kNsqaSCryxPq5xWTFIaP8KSW0RYxqupaUf0RcTNSSdJZGcKYdYA6kdtrtmyBckfKXwqk0pHpUHlwWaffjNRBYFPUDWa8e3Lt/o0R0CdisKDM89cX0pvRHEfM8ca4t0s2Xx4kgo91MPQJ/0c9MQYq0co8MBh7bz1fio0UUHLR4aAIOvOmoYO6kwlEVODSSTliWtOtH6sPkrtctF9ZtJ9GIerBskvhdVS5cFNv9s1BU0AbdUgdK4FG+dRnjFmDTzniRMdZO1QhzMK355vigbdkpz9P6qjUGE5J2qAcXmwJ20cZUiAD0z+pGMx6xkzJkmEf40Hr4qZfVg2XzF9YOyoV5BjzVkUJngKf8lgNYwKECEHrCNDrWZzMlflS3yBhr/InyoUgBc/lKT4pxVrrC6g1YwcceK3BmNxZcAtz3j5EIpqguh9H6wc011YN75cKDLpFDxuwkrPQmUwW4KTbj9mZTwBwLq4aQMUZbHm1rylJ46dzR0dua2n3RYCWZsiHROeywyJGR7mXKlpryyCiouY56sFkBWEnkEB/raeh/Sw4162KeuAxMQpEkzy5alMY5wamMsWKKrtW2WpEWNnReZWONKWjrdsKZarpFjqCslq773PLmEhM448Pc3+FKr1+94vv/rfw4tEcu+lKTBe4kZSdijBrykwv9vbCMPcLQTygBjzVckSLPRVGslqdunwJ4oegtFOYb4SwxNgWLCmD7T9kVjTv5YDgpo0XBmN34Z/rEHp0sgyz7lngsrm4lvMm2Mr1zNOJYJ5cuxuQxwMGJq/TP5emlb8fsQBZviK4t8hFL+zbhtlpwaRSxQRWfeETjuauPsdGxsBVdO7nmP4xvzSoT29pRl7kGqz+k26B3Oy0YNV+SXbbQas1ctC/GarskRdFpKczVAF1ZXnLcpaMuzVe6lZ2g/1ndcvOVgRG3sdUAY1bKD6achijMPdMxV4muKVorSpiDHituH7rSTs7n/4y5DhRXo4FVBN4vO/zbAcxhENzGbHCzU/98Mcx5e7a31kWjw9FCe/zNeYyQjZsWb1uc7U33pN4Mji6hCLhivqfa9Ss6xLg031AgfesA/l99m9fgvnaF9JoE6bYKmkGNK3aPbHB96w3+DnxFm4hs0drLsk7U8kf/N/CvwQNtllna0rjq61sH8L80HAuvwH1tvBy2ChqWSCaYTaGN19sTvlfzFD6n+iKTbvtayfrfe9ueWh6GJFoxLdr7V72a5ZpvHcCPDzma0wTO4EgbLyedxstO81n57LYBOBzyfsOhUKsW1J1BB5vr/tz8RyqOFylQP9Tvst2JALsC5lsH8PyQ40DV4ANzYa4dedNiKNR1s+x2wwbR7q4/4cTxqEk4LWDebfisuo36JXLiWFjOtLrlNWh3K1rRS4xvHcDNlFnNmWBBAl5SWaL3oPOfnvbr5pdjVnEaeBJSYjuLEkyLLsWhKccadmOphZkOPgVdalj2QpSmfOsADhMWE2ZBu4+EEJI4wKTAuCoC4xwQbWXBltpxbjkXJtKxxabo9e7tyhlgb6gNlSbUpMh+l/FaqzVwewGu8BW1Zx7pTpQDJUjb8tsUTW6+GDXbMn3mLbXlXJiGdggxFAoUrtPS3wE4Nk02UZG2OOzlk7fRs7i95QCLo3E0jtrjnM7SR3uS1p4qtS2nJ5OwtQVHgOvArLBFijZUV9QtSl8dAY5d0E0hM0w3HS2DpIeB6m/A1+HfhJcGUq4sOxH+x3f5+VO+Ds9rYNI7zPXOYWPrtf8bYMx6fuOAX5jzNR0PdsuON+X1f7EERxMJJoU6GkTEWBvVolVlb5lh3tKCg6Wx1IbaMDdJ+9sUCc5KC46hKGCk3IVOS4TCqdBNfUs7Kd4iXf2RjnT/LLysJy3XDcHLh/vde3x8DoGvwgsa67vBk91G5Pe/HbOe7xwym0NXbtiuuDkGO2IJDh9oQvJ4cY4vdoqLDuoH9Zl2F/ofsekn8lkuhIlhQcffUtSjytFyp++p6NiE7Rqx/lodgKVoceEp/CP4FfjrquZaTtj2AvH5K/ywpn7M34K/SsoYDAdIN448I1/0/wveW289T1/lX5xBzc8N5IaHr0XMOQdHsIkDuJFifj20pBm5jzwUv9e2FhwRsvhAbalCIuIw3bhJihY3p6nTFFIZgiSYjfTf3aXuOjmeGn4bPoGvwl+CFzTRczBIuHBEeImHc37/lGfwZR0cXzVDOvaKfNHvwe+suZ771K/y/XcBlsoN996JpBhoE2toYxOznNEOS5TJc6Id5GEXLjrWo+LEWGNpPDU4WAwsIRROu+1vM+0oW37z/MBN9kqHnSArwPfgFJ7Cq/Ai3Ie7g7ncmI09v8sjzw9mzOAEXoIHxURueaAce5V80f/DOuuZwHM8vsMb5wBzOFWM7wymTXPAEvm4vcFpZ2ut0VZRjkiP2MlmLd6DIpbGSiHOjdnUHN90hRYmhTnmvhzp1iKDNj+b7t5hi79lWGwQ+HN9RsfFMy0FXbEwhfuczKgCbyxYwBmcFhhvo/7a44v+i3XWcwDP86PzpGQYdWh7csP5dBvZ1jNzdxC8pBGuxqSW5vw40nBpj5JhMwvOzN0RWqERHMr4Lv1kWX84xLR830G3j6yqZ1a8UstTlW+qJPOZ+sZ7xZPKTJLhiNOAFd6tk+jrTH31ncLOxid8+nzRb128HhUcru/y0Wn6iT254YPC6FtVSIMoW2sk727AhvTtrWKZTvgsmckfXYZWeNRXx/3YQ2OUxLDrbHtN11IwrgXT6c8dATDwLniYwxzO4RzuQqTKSC5gAofMZ1QBK3zQ4JWobFbcvJm87FK+6JXrKahLn54m3p+McXzzYtP8VF/QpJuh1OwieElEoI1pRxPS09FBrkq2tWCU59+HdhNtTIqKm8EBrw2RTOEDpG3IKo2Y7mFdLm3ZeVjYwVw11o/oznceMve4CgMfNym/utA/d/ILMR7gpXzRy9eDsgLcgbs8O2Va1L0zzIdwGGemTBuwROHeoMShkUc7P+ISY3KH5ZZeWqO8mFTxQYeXTNuzvvK5FGPdQfuu00DwYFY9dyhctEt+OJDdnucfpmyhzUJzfsJjr29l8S0bXBfwRS9ZT26tmMIdZucch5ZboMz3Nio3nIOsYHCGoDT4kUA9MiXEp9Xsui1S8th/kbWIrMBxDGLodWUQIWcvnXy+9M23xPiSMOiRPqM+YMXkUN3gXFrZJwXGzUaMpJfyRS9ZT0lPe8TpScuRlbMHeUmlaKDoNuy62iWNTWNFYjoxFzuJs8oR+RhRx7O4SVNSXpa0ZJQ0K1LAHDQ+D9IepkMXpcsq5EVCvClBUIzDhDoyKwDw1Lc59GbTeORivugw1IcuaEOaGWdNm+Ps5fQ7/tm0DjMegq3yM3vb5j12qUId5UZD2oxDSEWOZMSqFl/W+5oynWDa/aI04tJRQ2eTXusg86SQVu/nwSYwpW6wLjlqIzwLuxGIvoAvul0PS+ZNz0/akp/pniO/8JDnGyaCkzbhl6YcqmK/69prxPqtpx2+Km9al9sjL+rwMgHw4jE/C8/HQ3m1vBuL1fldbzd8mOueVJ92syqdEY4KJjSCde3mcRw2TA6szxedn+zwhZMps0XrqEsiUjnC1hw0TELC2Ek7uAAdzcheXv1BYLagspxpzSAoZZUsIzIq35MnFQ9DOrlNB30jq3L4pkhccKUAA8/ocvN1Rzx9QyOtERs4CVsJRK/DF71kPYrxYsGsm6RMh4cps5g1DOmM54Ly1ii0Hd3Y/BMk8VWFgBVmhqrkJCPBHAolwZaWzLR9Vb7bcWdX9NyUYE+uB2BKfuaeBUcjDljbYVY4DdtsVWvzRZdWnyUzDpjNl1Du3aloAjVJTNDpcIOVVhrHFF66lLfJL1zJr9PQ2nFJSBaKoDe+sAvLufZVHVzYh7W0h/c6AAZ+7Tvj6q9j68G/cTCS/3n1vLKHZwNi+P+pS0WkZNMBMUl+LDLuiE4omZy71r3UFMwNJV+VJ/GC5ixVUkBStsT4gGKh0Gm4Oy3qvq7Lbmq24nPdDuDR9deR11XzP4vFu3TYzfnIyiSVmgizUYGqkIXNdKTY9pgb9D2Ix5t0+NHkVzCdU03suWkkVZAoCONCn0T35gAeW38de43mf97sMOpSvj4aa1KYUm58USI7Wxxes03bAZdRzk6UtbzMaCQ6IxO0dy7X+XsjoD16hpsBeGz9dfzHj+R/Hp8nCxZRqkEDTaCKCSywjiaoMJ1TITE9eg7Jqnq8HL6gDwiZb0u0V0Rr/rmvqjxKuaLCX7ZWXTvAY+uvm3z8CP7nzVpngqrJpZKwWnCUjIviYVlirlGOzPLI3SMVyp/elvBUjjDkNhrtufFFErQ8pmdSlbK16toBHlt/HV8uHMX/vEGALkV3RJREiSlopxwdMXOZPLZ+ix+kAHpMKIk8UtE1ygtquttwxNhphrIZ1IBzjGF3IIGxGcBj6q8bHJBG8T9vdsoWrTFEuebEZuVxhhClH6P5Zo89OG9fwHNjtNQTpD0TG9PJLEYqvEY6Rlxy+ZZGfL0Aj62/bnQCXp//eeM4KzfQVJbgMQbUjlMFIm6TpcfWlZje7NBSV6IsEVmumWIbjiloUzQX9OzYdo8L1wjw2PrrpimONfmfNyzKklrgnEkSzT5QWYQW40YShyzqsRmMXbvVxKtGuYyMKaU1ugenLDm5Ily4iT14fP11Mx+xJv+zZ3MvnfdFqxU3a1W/FTB4m3Qfsyc1XUcdVhDeUDZXSFHHLQj/Y5jtC7ZqM0CXGwB4bP11i3LhOvzPGygYtiUBiwQV/4wFO0majijGsafHyRLu0yG6q35cL1rOpVxr2s5cM2jJYMCdc10Aj6q/blRpWJ//+dmm5psMl0KA2+AFRx9jMe2WbC4jQxnikd4DU8TwUjRVacgdlhmr3bpddzuJ9zXqr2xnxJfzP29RexdtjDVZqzkqa6PyvcojGrfkXiJ8SEtml/nYskicv0ivlxbqjemwUjMw5evdg8fUX9nOiC/lf94Q2i7MURk9nW1MSj5j8eAyV6y5CN2S6qbnw3vdA1Iwq+XOSCl663udN3IzLnrt+us25cI1+Z83SXQUldqQq0b5XOT17bGpLd6ssN1VMPf8c+jG8L3NeCnMdF+Ra3fRa9dft39/LuZ/3vwHoHrqGmQFafmiQw6eyzMxS05K4bL9uA+SKUQzCnSDkqOGokXyJvbgJ/BHI+qvY69//4rl20NsmK2ou2dTsyIALv/91/8n3P2Aao71WFGi8KKv1fRC5+J67Q/507/E/SOshqN5TsmYIjVt+kcjAx98iz/4SaojbIV1rexE7/C29HcYD/DX4a0rBOF5VTu7omsb11L/AWcVlcVZHSsqGuXLLp9ha8I//w3Mv+T4Ew7nTBsmgapoCrNFObIcN4pf/Ob/mrvHTGqqgAupL8qWjWPS9m/31jAe4DjA+4+uCoQoT/zOzlrNd3qd4SdphFxsUvYwGWbTWtISc3wNOWH+kHBMfc6kpmpwPgHWwqaSUG2ZWWheYOGQGaHB+eQ/kn6b3pOgLV+ODSn94wDvr8Bvb70/LLuiPPEr8OGVWfDmr45PZyccEmsVXZGe1pRNX9SU5+AVQkNTIVPCHF/jGmyDC9j4R9LfWcQvfiETmgMMUCMN1uNCakkweZsowdYobiMSlnKA93u7NzTXlSfe+SVbfnPQXmg9LpYAQxpwEtONyEyaueWM4FPjjyjG3uOaFmBTWDNgBXGEiQpsaWhnAqIijB07Dlsy3fUGeP989xbWkyf+FF2SNEtT1E0f4DYYVlxFlbaSMPIRMk/3iMU5pME2SIWJvjckciebkQuIRRyhUvkHg/iUljG5kzVog5hV7vIlCuBrmlhvgPfNHQM8lCf+FEGsYbMIBC0qC9a0uuy2wLXVbLBaP5kjHokCRxapkQyzI4QEcwgYHRZBp+XEFTqXFuNVzMtjXLJgX4gAid24Hjwc4N3dtVSe+NNiwTrzH4WVUOlDobUqr1FuAgYllc8pmzoVrELRHSIW8ViPxNy4xwjBpyR55I6J220qQTZYR4guvUICJiSpr9gFFle4RcF/OMB7BRiX8sSfhpNSO3lvEZCQfLUVTKT78Ek1LRLhWN+yLyTnp8qWUZ46b6vxdRGXfHVqx3eI75YaLa4iNNiK4NOW7wPW6lhbSOF9/M9qw8e/aoB3d156qTzxp8pXx5BKAsYSTOIIiPkp68GmTq7sZtvyzBQaRLNxIZ+paozHWoLFeExIhRBrWitHCAHrCF7/thhD8JhYz84wg93QRV88wLuLY8zF8sQ36qF1J455bOlgnELfshKVxYOXKVuKx0jaj22sczTQqPqtV/XDgpswmGTWWMSDw3ssyUunLLrVPGjYRsH5ggHeHSWiV8kT33ycFSfMgkoOK8apCye0J6VW6GOYvffgU9RWsukEi2kUV2nl4dOYUzRik9p7bcA4ggdJ53LxKcEe17B1R8eqAd7dOepV8sTXf5lhejoL85hUdhDdknPtKHFhljOT+bdq0hxbm35p2nc8+Ja1Iw+tJykgp0EWuAAZYwMVwac5KzYMslhvgHdHRrxKnvhTYcfKsxTxtTETkjHO7rr3zjoV25lAQHrqpV7bTiy2aXMmUhTBnKS91jhtR3GEoF0oLnWhWNnYgtcc4N0FxlcgT7yz3TgNIKkscx9jtV1ZKpWW+Ub1tc1eOv5ucdgpx+FJy9pgbLE7xDyXb/f+hLHVGeitHOi6A7ybo3sF8sS7w7cgdk0nJaOn3hLj3uyD0Zp5pazFIUXUpuTTU18d1EPkDoX8SkmWTnVIozEdbTcZjoqxhNHf1JrSS/AcvHjZ/SMHhL/7i5z+POsTUh/8BvNfYMTA8n+yU/MlTZxSJDRStqvEuLQKWwDctMTQogUDyQRoTQG5Kc6oQRE1yV1jCA7ri7jdZyK0sYTRjCR0Hnnd+y7nHxNgTULqw+8wj0mQKxpYvhjm9uSUxg+TTy7s2GtLUGcywhXSKZN275GsqlclX90J6bRI1aouxmgL7Q0Nen5ziM80SqMIo8cSOo+8XplT/5DHNWsSUr/6lLN/QQ3rDyzLruEW5enpf7KqZoShEduuSFOV7DLX7Ye+GmXb6/hnNNqKsVXuMDFpb9Y9eH3C6NGEzuOuI3gpMH/I6e+zDiH1fXi15t3vA1czsLws0TGEtmPEJdiiFPwlwKbgLHAFk4P6ZyPdymYYHGE0dutsChQBl2JcBFlrEkY/N5bQeXQ18gjunuMfMfsBlxJSx3niO485fwO4fGD5T/+3fPQqkneWVdwnw/3bMPkW9Wbqg+iC765Zk+xcT98ibKZc2EdgHcLoF8cSOo/Oc8fS+OyEULF4g4sJqXVcmfMfsc7A8v1/yfGXmL9I6Fn5pRwZhsPv0TxFNlAfZCvG+Oohi82UC5f/2IsJo0cTOm9YrDoKhFPEUr/LBYTUNht9zelHXDqwfPCIw4owp3mOcIQcLttWXFe3VZ/j5H3cIc0G6oPbCR+6Y2xF2EC5cGUm6wKC5tGEzhsWqw5hNidUiKX5gFWE1GXh4/Qplw4sVzOmx9QxU78g3EF6wnZlEN4FzJ1QPSLEZz1KfXC7vd8ssGdIbNUYpVx4UapyFUHzJoTOo1McSkeNn1M5MDQfs4qQuhhX5vQZFw8suwWTcyYTgioISk2YdmkhehG4PkE7w51inyAGGaU+uCXADabGzJR1fn3lwkty0asIo8cROm9Vy1g0yDxxtPvHDAmpu+PKnM8Ix1wwsGw91YJqhteaWgjYBmmQiebmSpwKKzE19hx7jkzSWOm66oPbzZ8Yj6kxVSpYjVAuvLzYMCRo3oTQecOOjjgi3NQ4l9K5/hOGhNTdcWVOTrlgYNkEXINbpCkBRyqhp+LdRB3g0OU6rMfW2HPCFFMV9nSp+uB2woepdbLBuJQyaw/ZFysXrlXwHxI0b0LovEkiOpXGA1Ijagf+KUNC6rKNa9bQnLFqYNkEnMc1uJrg2u64ELPBHpkgWbmwKpJoDhMwNbbGzAp7Yg31wS2T5rGtzit59PrKhesWG550CZpHEzpv2NGRaxlNjbMqpmEIzygJqQfjypycs2pg2cS2RY9r8HUqkqdEgKTWtWTKoRvOBPDYBltja2SO0RGjy9UHtxwRjA11ujbKF+ti5cIR9eCnxUg6owidtyoU5tK4NLji5Q3HCtiyF2IqLGYsHViOXTXOYxucDqG0HyttqYAKqYo3KTY1ekyDXRAm2AWh9JmsVh/ccg9WJ2E8YjG201sPq5ULxxX8n3XLXuMInbft2mk80rRGjCGctJ8/GFdmEQ9Ug4FlE1ll1Y7jtiraqm5Fe04VV8lvSVBL8hiPrfFVd8+7QH3Qbu2ipTVi8cvSGivc9cj8yvH11YMHdNSERtuOslM97feYFOPKzGcsI4zW0YGAbTAOaxCnxdfiYUmVWslxiIblCeAYr9VYR1gM7GmoPrilunSxxeT3DN/2eBQ9H11+nk1adn6VK71+5+Jfct4/el10/7KBZfNryUunWSCPxPECk1rdOv1WVSrQmpC+Tl46YD3ikQYcpunSQgzVB2VHFhxHVGKDgMEY5GLlQnP7FMDzw7IacAWnO6sBr12u+XanW2AO0wQ8pknnFhsL7KYIqhkEPmEXFkwaN5KQphbkUmG72wgw7WSm9RiL9QT925hkjiVIIhphFS9HKI6/8QAjlpXqg9W2C0apyaVDwKQwrwLY3j6ADR13ZyUNByQXHQu6RY09Hu6zMqXRaNZGS/KEJs0cJEe9VH1QdvBSJv9h09eiRmy0V2uJcqHcShcdvbSNg5fxkenkVprXM9rDVnX24/y9MVtncvbKY706anNl3ASll9a43UiacVquXGhvq4s2FP62NGKfQLIQYu9q1WmdMfmUrDGt8eDS0cXozH/fjmUH6Jruvm50hBDSaEU/2Ru2LEN/dl006TSc/g7tfJERxGMsgDUEr104pfWH9lQaN+M4KWQjwZbVc2rZVNHsyHal23wZtIs2JJqtIc/WLXXRFCpJkfE9jvWlfFbsNQ9pP5ZBS0zKh4R0aMFj1IjTcTnvi0Zz2rt7NdvQb2mgbju1plsH8MmbnEk7KbK0b+wC2iy3aX3szW8xeZvDwET6hWZYwqTXSSG+wMETKum0Dq/q+x62gt2ua2ppAo309TRk9TPazfV3qL9H8z7uhGqGqxNVg/FKx0HBl9OVUORn8Q8Jx9gFttGQUDr3tzcXX9xGgN0EpzN9mdZ3GATtPhL+CjxFDmkeEU6x56kqZRusLzALXVqkCN7zMEcqwjmywDQ6OhyUe0Xao1Qpyncrg6wKp9XfWDsaZplElvQ/b3sdweeghorwBDlHzgk1JmMc/wiERICVy2VJFdMjFuLQSp3S0W3+sngt2njwNgLssFGVQdJ0tu0KH4ky1LW4yrbkuaA6Iy9oz/qEMMXMMDWyIHhsAyFZc2peV9hc7kiKvfULxCl9iddfRK1f8kk9qvbdOoBtOg7ZkOZ5MsGrSHsokgLXUp9y88smniwWyuFSIRVmjplga3yD8Uij5QS1ZiM4U3Qw5QlSm2bXjFe6jzzBFtpg+/YBbLAWG7OPynNjlCw65fukGNdkJRf7yM1fOxVzbxOJVocFoYIaGwH22mIQkrvu1E2nGuebxIgW9U9TSiukPGU+Lt++c3DJPKhyhEEbXCQLUpae2exiKy6tMPe9mDRBFCEMTWrtwxN8qvuGnt6MoihKWS5NSyBhbH8StXoAz8PLOrRgLtOT/+4vcu+7vDLnqNvztOq7fmd8sMmY9Xzn1zj8Dq8+XVdu2Nv0IIySgEdQo3xVHps3Q5i3fLFsV4aiqzAiBhbgMDEd1uh8qZZ+lwhjkgokkOIv4xNJmyncdfUUzgB4oFMBtiu71Xumpz/P+cfUP+SlwFExwWW62r7b+LSPxqxn/gvMZ5z9C16t15UbNlq+jbGJtco7p8wbYlL4alSyfWdeuu0j7JA3JFNuVAwtst7F7FhWBbPFNKIUORndWtLraFLmMu7KFVDDOzqkeaiN33YAW/r76wR4XDN/yN1z7hejPau06EddkS/6XThfcz1fI/4K736fO48vlxt2PXJYFaeUkFS8U15XE3428xdtn2kc8GQlf1vkIaNRRnOMvLTWrZbElEHeLWi1o0dlKPAh1MVgbbVquPJ5+Cr8LU5/H/+I2QlHIU2ClXM9G8v7Rr7oc/hozfUUgsPnb3D+I+7WF8kNO92GY0SNvuxiE+2Bt8prVJTkzE64sfOstxuwfxUUoyk8VjcTlsqe2qITSFoSj6Epd4KsT6BZOWmtgE3hBfir8IzZDwgV4ZTZvD8VvPHERo8v+vL1DASHTz/i9OlKueHDjK5Rnx/JB1Vb1ioXdBra16dmt7dgik10yA/FwJSVY6XjA3oy4SqM2frqDPPSRMex9qs3XQtoWxMj7/Er8GWYsXgjaVz4OYumP2+9kbxvny/6kvWsEBw+fcb5bInc8APdhpOSs01tEqIkoiZjbAqKMruLbJYddHuHFRIyJcbdEdbl2sVLaySygunutBg96Y2/JjKRCdyHV+AEFtTvIpbKIXOamknYSiB6KV/0JetZITgcjjk5ZdaskBtWO86UF0ap6ozGXJk2WNiRUlCPFir66lzdm/SLSuK7EUdPz8f1z29Skq6F1fXg8+5UVR6bszncP4Tn4KUkkdJ8UFCY1zR1i8RmL/qQL3rlei4THG7OODlnKko4oI01kd3CaM08Ia18kC3GNoVaO9iDh+hWxSyTXFABXoau7Q6q9OxYg/OVEMw6jdbtSrJ9cBcewGmaZmg+bvkUnUUaGr+ZfnMH45Ivevl61hMcXsxYLFTu1hTm2zViCp7u0o5l+2PSUh9bDj6FgYypufBDhqK2+oXkiuHFHR3zfj+9PtA8oR0xnqX8qn+sx3bFODSbbF0X8EUvWQ8jBIcjo5bRmLOljDNtcqNtOe756h3l0VhKa9hDd2l1eqmsnh0MNMT/Cqnx6BInumhLT8luljzQ53RiJeA/0dxe5NK0o2fA1+GLXr6eNQWHNUOJssQaTRlGpLHKL9fD+IrQzTOMZS9fNQD4AnRNVxvTdjC+fJdcDDWQcyB00B0t9BDwTxXgaAfzDZ/DBXzRnfWMFRwuNqocOmX6OKNkY63h5n/fFcB28McVHqnXZVI27K0i4rDLNE9lDKV/rT+udVbD8dFFu2GGZ8mOt0kAXcoX3ZkIWVtw+MNf5NjR2FbivROHmhV1/pj2egv/fMGIOWTIWrV3Av8N9imV9IWml36H6cUjqEWNv9aNc+veb2sH46PRaHSuMBxvtW+twxctq0z+QsHhux8Q7rCY4Ct8lqsx7c6Sy0dl5T89rIeEuZKoVctIk1hNpfavER6yyH1Vvm3MbsUHy4ab4hWr/OZPcsRBphnaV65/ZcdYPNNwsjN/djlf9NqCw9U5ExCPcdhKxUgLSmfROpLp4WSUr8ojdwbncbvCf+a/YzRaEc6QOvXcGO256TXc5Lab9POvB+AWY7PigWYjzhifbovuunzRawsO24ZqQQAqguBtmpmPB7ysXJfyDDaV/aPGillgz1MdQg4u5MYaEtBNNHFjkRlSpd65lp4hd2AVPTfbV7FGpyIOfmNc/XVsPfg7vzaS/3nkvLL593ANLvMuRMGpQIhiF7kUEW9QDpAUbTWYBcbp4WpacHHY1aacqQyjGZS9HI3yCBT9kUZJhVOD+zUDvEH9ddR11fzPcTDQ5TlgB0KwqdXSavk9BC0pKp0WmcuowSw07VXmXC5guzSa4p0UvRw2lbDiYUx0ExJJRzWzi6Gm8cnEkfXXsdcG/M/jAJa0+bmCgdmQ9CYlNlSYZOKixmRsgiFxkrmW4l3KdFKv1DM8tk6WxPYJZhUUzcd8Kdtgrw/gkfXXDT7+avmfVak32qhtkg6NVdUS5wgkru1YzIkSduTW1FDwVWV3JQVJVuieTc0y4iDpFwc7/BvSalvKdQM8sv662cevz/+8sQVnjVAT0W2wLllw1JiMhJRxgDjCjLQsOzSFSgZqx7lAW1JW0e03yAD3asC+GD3NbQhbe+mN5GXH1F83KDOM4n/e5JIuH4NpdQARrFPBVptUNcjj4cVMcFSRTE2NpR1LEYbYMmfWpXgP9KejaPsLUhuvLCsVXznAG9dfx9SR1ud/3hZdCLHb1GMdPqRJgqDmm76mHbvOXDtiO2QPUcKo/TWkQ0i2JFXpBoo7vij1i1Lp3ADAo+qvG3V0rM//vFnnTE4hxd5Ka/Cor5YEdsLVJyKtDgVoHgtW11pWSjolPNMnrlrVj9Fv2Qn60twMwKPqr+N/wvr8z5tZcDsDrv06tkqyzESM85Ycv6XBWA2birlNCXrI6VbD2lx2L0vQO0QVTVVLH4SE67fgsfVXv8n7sz7/85Z7cMtbE6f088wSaR4kCkCm10s6pKbJhfqiUNGLq+0gLWC6eUAZFPnLjwqtKd8EwGvWX59t7iPW4X/eAN1svgRVSY990YZg06BD1ohLMtyFTI4pKTJsS9xREq9EOaPWiO2gpms7397x6nQJkbh+Fz2q/rqRROX6/M8bJrqlVW4l6JEptKeUFuMYUbtCQ7CIttpGc6MY93x1r1vgAnRXvY5cvwWPqb9uWQm+lP95QxdNMeWhOq1x0Db55C7GcUv2ZUuN6n8iKzsvOxibC//Yfs9Na8r2Rlz02vXXDT57FP/zJi66/EJSmsJKa8QxnoqW3VLQ+jZVUtJwJ8PNX1NQCwfNgdhhHD9on7PdRdrdGPF28rJr1F+3LBdeyv+8yYfLoMYet1vX4upNAjVvwOUWnlNXJXlkzk5Il6kqeoiL0C07qno+/CYBXq/+utlnsz7/Mzvy0tmI4zm4ag23PRN3t/CWryoUVJGm+5+K8RJ0V8Hc88/XHUX/HfiAq7t+BH+x6v8t438enWmdJwFA6ZINriLGKv/95f8lT9/FnyA1NMVEvQyaXuu+gz36f/DD73E4pwqpLcvm/o0Vle78n//+L/NPvoefp1pTJye6e4A/D082FERa5/opeH9zpvh13cNm19/4v/LDe5xMWTi8I0Ta0qKlK27AS/v3/r+/x/2GO9K2c7kVMonDpq7//jc5PKCxeNPpFVzaRr01wF8C4Pu76hXuX18H4LduTr79guuFD3n5BHfI+ZRFhY8w29TYhbbLi/bvBdqKE4fUgg1pBKnV3FEaCWOWyA+m3WpORZr/j+9TKJtW8yBTF2/ZEODI9/QavHkVdGFp/Pjn4Q+u5hXapsP5sOH+OXXA1LiKuqJxiMNbhTkbdJTCy4llEt6NnqRT4dhg1V3nbdrm6dYMecA1yTOL4PWTE9L5VzPFlLBCvlG58AhehnN4uHsAYinyJ+AZ/NkVvELbfOBUuOO5syBIEtiqHU1k9XeISX5bsimrkUUhnGDxourN8SgUsCZVtKyGbyGzHXdjOhsAvOAswSRyIBddRdEZWP6GZhNK/yjwew9ehBo+3jEADu7Ay2n8mDc+TS7awUHg0OMzR0LABhqLD4hJEh/BEGyBdGlSJoXYXtr+3HS4ijzVpgi0paWXtdruGTknXBz+11qT1Q2inxaTzQCO46P3lfLpyS4fou2PH/PupwZgCxNhGlj4IvUuWEsTkqMWm6i4xCSMc9N1RDQoCVcuGItJ/MRWefais+3synowi/dESgJjkilnWnBTGvRWmaw8oR15257t7CHmCf8HOn7cwI8+NQBXMBEmAa8PMRemrNCEhLGEhDQKcGZWS319BX9PFBEwGTbRBhLbDcaV3drFcDqk5kCTd2JF1Wp0HraqBx8U0wwBTnbpCadwBA/gTH/CDrcCs93LV8E0YlmmcyQRQnjBa8JESmGUfIjK/7fkaDJpmD2QptFNVJU1bbtIAjjWQizepOKptRjbzR9Kag6xZmMLLjHOtcLT3Tx9o/0EcTT1XN3E45u24AiwEypDJXihKjQxjLprEwcmRKclaDNZCVqr/V8mYWyFADbusiY5hvgFoU2vio49RgJLn5OsReRFN6tabeetiiy0V7KFHT3HyZLx491u95sn4K1QQSPKM9hNT0wMVvAWbzDSVdrKw4zRjZMyJIHkfq1VAVCDl/bUhNKlGq0zGr05+YAceXVPCttVk0oqjVwMPt+BBefx4yPtGVkUsqY3CHDPiCM5ngupUwCdbkpd8kbPrCWHhkmtIKLEetF2499eS1jZlIPGYnlcPXeM2KD9vLS0bW3ktYNqUllpKLn5ZrsxlIzxvDu5eHxzGLctkZLEY4PgSOg2IUVVcUONzUDBEpRaMoXNmUc0tFZrTZquiLyKxrSm3DvIW9Fil+AkhXu5PhEPx9mUNwqypDvZWdKlhIJQY7vn2OsnmBeOWnYZ0m1iwbbw1U60by5om47iHRV6fOgzjMf/DAZrlP40Z7syxpLK0lJ0gqaAK1c2KQKu7tabTXkLFz0sCftuwX++MyNeNn68k5Buq23YQhUh0SNTJa1ioQ0p4nUG2y0XilF1JqODqdImloPS4Bp111DEWT0jJjVv95uX9BBV7eB3bUWcu0acSVM23YZdd8R8UbQUxJ9wdu3oMuhdt929ME+mh6JXJ8di2RxbTi6TbrDquqV4aUKR2iwT6aZbyOwEXN3DUsWr8Hn4EhwNyHuXHh7/pdaUjtR7vnDh/d8c9xD/s5f501eQ1+CuDiCvGhk1AN/4Tf74RfxPwD3toLarR0zNtsnPzmS64KIRk861dMWCU8ArasG9T9H0ZBpsDGnjtAOM2+/LuIb2iIUGXNgl5ZmKD/Tw8TlaAuihaFP5yrw18v4x1898zIdP+DDAX1bM3GAMvPgRP/cJn3zCW013nrhHkrITyvYuwOUkcHuKlRSW5C6rzIdY4ppnF7J8aAJbQepgbJYBjCY9usGXDKQxq7RZfh9eg5d1UHMVATRaD/4BHK93/1iAgYZ/+jqPn8Dn4UExmWrpa3+ZOK6MvM3bjwfzxNWA2dhs8+51XHSPJiaAhGSpWevEs5xHLXcEGFXYiCONySH3fPWq93JIsBiSWvWyc3CAN+EcXoT7rCSANloPPoa31rt/5PUA/gp8Q/jDD3hyrjzlR8VkanfOvB1XPubt17vzxAfdSVbD1pzAnfgyF3ycadOTOTXhpEUoLC1HZyNGW3dtmjeXgr2r56JNmRwdNNWaQVBddd6rh4MhviEB9EFRD/7RGvePvCbwAL4Mx/D6M541hHO4D3e7g6PafdcZVw689z7NGTwo5om7A8sPhccT6qKcl9NJl9aM/9kX+e59Hh1yPqGuCCZxuITcsmNaJ5F7d0q6J3H48TO1/+M57085q2icdu2U+W36Ldllz9Agiv4YGljoEN908EzvDOrBF98/vtJwCC/BF2AG75xxEmjmMIcjxbjoaxqOK3/4hPOZzhMPBpYPG44CM0dTVm1LjLtUWWVz1Bcf8tEx0zs8O2A2YVHRxKYOiy/aOVoAaMu0i7ubu43njjmd4ibMHU1sIDHaQNKrZND/FZYdk54oCXetjq7E7IVl9eAL7t+oHnwXXtLx44czzoRFHBztYVwtH1d+NOMkupZ5MTM+gUmq90X+Bh9zjRlmaQ+m7YMqUL/veemcecAtOJ0yq1JnVlN27di2E0+Klp1tAJ4KRw1eMI7aJjsO3R8kPSI3fUFXnIOfdQe86sIIVtWDL7h//Ok6vj8vwDk08NEcI8zz7OhBy+WwalzZeZ4+0XniRfst9pAJqQHDGLzVQ2pheZnnv1OWhwO43/AgcvAEXEVVpa4db9sGvNK8wjaENHkfFQ4Ci5i7dqnQlPoLQrHXZDvO3BIXZbJOBrOaEbML6sFL798I4FhKihjHMsPjBUZYCMFr6nvaArxqXPn4lCa+cHfSa2cP27g3Z3ziYTRrcbQNGLQmGF3F3cBdzzzX7AILx0IB9rbwn9kx2G1FW3Inic+ZLIsVvKR8Zwfj0l1fkqo8LWY1M3IX14OX3r9RKTIO+d9XzAI8qRPGPn/4NC2n6o4rN8XJ82TOIvuVA8zLKUHRFgBCetlDZlqR1gLKjS39xoE7Bt8UvA6BxuEDjU3tFsEijgA+615tmZkXKqiEENrh41iLDDZNq4pKTWR3LZfnos81LOuNa15cD956vLMsJd1rqYp51gDUQqMYm2XsxnUhD2jg1DM7SeuJxxgrmpfISSXVIJIS5qJJSvJPEQ49DQTVIbYWJ9QWa/E2+c/oPK1drmC7WSfJRNKBO5Yjvcp7Gc3dmmI/Xh1kDTEuiSnWqQf37h+fTMhGnDf6dsS8SQfQWlqqwXXGlc/PEZ/SC5mtzIV0nAshlQdM/LvUtYutrEZ/Y+EAFtq1k28zQhOwLr1AIeANzhF8t9qzTdZf2qRKO6MWE9ohBYwibbOmrFtNmg3mcS+tB28xv2uKd/agYCvOP+GkSc+0lr7RXzyufL7QbkUpjLjEWFLqOIkAGu2B0tNlO9Eau2W1qcOUvVRgKzypKIQZ5KI3q0MLzqTNRYqiZOqmtqloIRlmkBHVpHmRYV6/HixbO6UC47KOFJnoMrVyr7wYz+SlW6GUaghYbY1I6kkxA2W1fSJokUdSh2LQ1GAimRGm0MT+uu57H5l7QgOWxERpO9moLRPgTtquWCfFlGlIjQaRly9odmzMOWY+IBO5tB4sW/0+VWGUh32qYk79EidWKrjWuiLpiVNGFWFRJVktyeXWmbgBBzVl8anPuXyNJlBJOlKLTgAbi/EYHVHxWiDaVR06GnHQNpJcWcK2jJtiCfG2sEHLzuI66sGrMK47nPIInPnu799935aOK2cvmvubrE38ZzZjrELCmXM2hM7UcpXD2oC3+ECVp7xtIuxptJ0jUr3sBmBS47TVxlvJ1Sqb/E0uLdvLj0lLr29ypdd/eMX3f6lrxGlKwKQxEGvw0qHbkbwrF3uHKwVENbIV2wZ13kNEF6zD+x24aLNMfDTCbDPnEikZFyTNttxWBXDaBuM8KtI2rmaMdUY7cXcUPstqTGvBGSrFWIpNMfbdea990bvAOC1YX0qbc6smDS1mPxSJoW4fwEXvjMmhlijDRq6qale6aJEuFGoppYDoBELQzLBuh/mZNx7jkinv0EtnUp50lO9hbNK57lZaMAWuWR5Yo9/kYwcYI0t4gWM47Umnl3YmpeBPqSyNp3K7s2DSAS/39KRuEN2bS4xvowV3dFRMx/VFcp2Yp8w2nTO9hCXtHG1kF1L4KlrJr2wKfyq77R7MKpFKzWlY9UkhYxyHWW6nBWPaudvEAl3CGcNpSXPZ6R9BbBtIl6cHL3gIBi+42CYXqCx1gfGWe7Ap0h3luyXdt1MKy4YUT9xSF01G16YEdWsouW9mgDHd3veyA97H+Ya47ZmEbqMY72oPztCGvK0onL44AvgC49saZKkWRz4veWljE1FHjbRJaWv6ZKKtl875h4CziFCZhG5rx7tefsl0aRT1bMHZjm8dwL/6u7wCRysaQblQoG5yAQN5zpatMNY/+yf8z+GLcH/Qn0iX2W2oEfXP4GvwQHuIL9AYGnaO3zqAX6946nkgqZNnUhx43DIdQtMFeOPrgy/y3Yd85HlJWwjLFkU3kFwq28xPnuPhMWeS+tDLV9Otllq7pQCf3uXJDN9wFDiUTgefHaiYbdfi3b3u8+iY6TnzhgehI1LTe8lcd7s1wJSzKbahCRxKKztTLXstGAiu3a6rPuQs5pk9TWAan5f0BZmGf7Ylxzzk/A7PAs4QPPPAHeFQ2hbFHszlgZuKZsJcUmbDC40sEU403cEjczstOEypa+YxevL4QBC8oRYqWdK6b7sK25tfE+oDZgtOQ2Jg8T41HGcBE6fTWHn4JtHcu9S7uYgU5KSCkl/mcnq+5/YBXOEr6lCUCwOTOM1taOI8mSxx1NsCXBEmLKbMAg5MkwbLmpBaFOPrNSlO2HnLiEqW3tHEwd8AeiQLmn+2gxjC3k6AxREqvKcJbTEzlpLiw4rNZK6oJdidbMMGX9FULKr0AkW+2qDEPBNNm5QAt2Ik2nftNWHetubosHLo2nG4vQA7GkcVCgVCgaDixHqo9UUn1A6OshapaNR/LPRYFV8siT1cCtJE0k/3WtaNSuUZYKPnsVIW0xXWnMUxq5+En4Kvw/MqQmVXnAXj9Z+9zM98zM/Agy7F/qqj2Nh67b8HjFnPP3iBn/tkpdzwEJX/whIcQUXOaikeliCRGUk7tiwF0rItwMEhjkZ309hikFoRAmLTpEXWuHS6y+am/KB/fM50aLEhGnSMwkpxzOov4H0AvgovwJ1iGzDLtJn/9BU+fAINfwUe6FHSLhu83viV/+/HrOePX+STT2B9uWGbrMHHLldRBlhS/CJQmcRxJFqZica01XixAZsYiH1uolZxLrR/SgxVIJjkpQP4PE9sE59LKLr7kltSBogS5tyszzH8Fvw8/AS8rNOg0xUS9fIaHwb+6et8Q/gyvKRjf5OusOzGx8evA/BP4IP11uN/grca5O0lcsPLJ5YjwI4QkJBOHa0WdMZYGxPbh2W2nR9v3WxEWqgp/G3+6VZbRLSAAZ3BhdhAaUL33VUSw9yjEsvbaQ9u4A/gGXwZXoEHOuU1GSj2chf+Mo+f8IcfcAxfIKVmyunRbYQVnoevwgfw3TXXcw++xNuP4fhyueEUNttEduRVaDttddoP0eSxLe2LENk6itYxlrxBNBYrNNKSQmeaLcm9c8UsaB5WyO6675yyQIAWSDpBVoA/gxmcwEvwoDv0m58UE7gHn+fJOa8/Ywan8EKRfjsopF83eCglX/Sfr7OeaRoQfvt1CGvIDccH5BCvw1sWIzRGC/66t0VTcLZQZtm6PlAasbOJ9iwWtUo7biktTSIPxnR24jxP1ZKaqq+2RcXM9OrBAm/AAs7hDJ5bNmGb+KIfwCs8a3jnjBrOFeMjHSCdbKr+2uOLfnOd9eiA8Hvvwwq54VbP2OqwkB48Ytc4YEOiH2vTXqodabfWEOzso4qxdbqD5L6tbtNPECqbhnA708DZH4QOJUXqScmUlks7Ot6FBuZw3n2mEbaUX7kDzxHOOQk8nKWMzAzu6ZZ8sOFw4RK+6PcuXo9tB4SbMz58ApfKDXf3szjNIIbGpD5TKTRxGkEMLjLl+K3wlWXBsCUxIDU+jbOiysESqAy1MGUJpXgwbTWzNOVEziIXZrJ+VIztl1PUBxTSo0dwn2bOmfDRPD3TRTGlfbCJvO9KvuhL1hMHhB9wPuPRLGHcdOWG2xc0U+5bQtAJT0nRTewXL1pgk2+rZAdeWmz3jxAqfNQQdzTlbF8uJ5ecEIWvTkevAHpwz7w78QujlD/Lr491bD8/1vhM2yrUQRrWXNQY4fGilfctMWYjL72UL/qS9eiA8EmN88nbNdour+PBbbAjOjIa4iBhfFg6rxeKdEGcL6p3EWR1Qq2Qkhs2DrnkRnmN9tG2EAqmgPw6hoL7Oza7B+3SCrR9tRftko+Lsf2F/mkTndN2LmzuMcKTuj/mX2+4Va3ki16+nnJY+S7MefpkidxwnV+4wkXH8TKnX0tsYzYp29DOOoSW1nf7nTh2akYiWmcJOuTidSaqESrTYpwjJJNVGQr+rLI7WsqerHW6Kp/oM2pKuV7T1QY9gjqlZp41/WfKpl56FV/0kvXQFRyeQ83xaTu5E8p5dNP3dUF34ihyI3GSpeCsywSh22ZJdWto9winhqifb7VRvgktxp13vyjrS0EjvrRfZ62uyqddSWaWYlwTPAtJZ2oZ3j/Sgi/mi+6vpzesfAcWNA0n8xVyw90GVFGuZjTXEQy+6GfLGLMLL523f5E0OmxVjDoOuRiH91RKU+vtoCtH7TgmvBLvtFXWLW15H9GTdVw8ow4IlRLeHECN9ym1e9K0I+Cbnhgv4Yu+aD2HaQJ80XDqOzSGAV4+4yCqBxrsJAX6ZTIoX36QnvzhhzzMfFW2dZVLOJfo0zbce5OvwXMFaZ81mOnlTVXpDZsQNuoYWveketKb5+6JOOsgX+NTm7H49fUTlx+WLuWL7qxnOFh4BxpmJx0p2gDzA/BUARuS6phR+pUsY7MMboAHx5xNsSVfVZcYSwqCKrqon7zM+8ecCkeS4nm3rINuaWvVNnMRI1IRpxTqx8PZUZ0Br/UEduo3B3hNvmgZfs9gQPj8vIOxd2kndir3awvJ6BLvoUuOfFWNYB0LR1OQJoUySKb9IlOBx74q1+ADC2G6rOdmFdJcD8BkfualA+BdjOOzP9uUhGUEX/TwhZsUduwRr8wNuXKurCixLBgpQI0mDbJr9dIqUuV+92ngkJZ7xduCk2yZKbfWrH1VBiTg9VdzsgRjW3CVXCvAwDd+c1z9dWw9+B+8MJL/eY15ZQ/HqvTwVdsZn5WQsgRRnMaWaecu3jFvMBEmgg+FJFZsnSl0zjB9OqPYaBD7qmoVyImFvzi41usesV0julaAR9dfR15Xzv9sEruRDyk1nb+QaLU67T885GTls6YgcY+UiMa25M/pwGrbCfzkvR3e0jjtuaFtnwuagHTSb5y7boBH119HXhvwP487jJLsLJ4XnUkHX5sLbS61dpiAXRoZSCrFJ+EjpeU3puVfitngYNo6PJrAigKktmwjyQdZpfq30mmtulaAx9Zfx15Xzv+cyeuiBFUs9zq8Kq+XB9a4PVvph3GV4E3y8HENJrN55H1X2p8VyqSKwVusJDKzXOZzplWdzBUFK9e+B4+uv468xvI/b5xtSAkBHQaPvtqWzllVvEOxPbuiE6+j2pvjcKsbvI7txnRErgfH7LdXqjq0IokKzga14GzQ23SSbCQvO6r+Or7SMIr/efOkkqSdMnj9mBx2DRsiY29Uj6+qK9ZrssCKaptR6HKURdwUYeUWA2kPzVKQO8ku2nU3Anhs/XWkBx3F/7wJtCTTTIKftthue1ty9xvNYLY/zo5KSbIuKbXpbEdSyeRyYdAIwKY2neyoc3+k1XUaufYga3T9daMUx/r8z1s10ITknIO0kuoMt+TB8jK0lpayqqjsJ2qtXAYwBU932zinimgmd6mTRDnQfr88q36NAI+tv24E8Pr8zxtasBqx0+xHH9HhlrwsxxNUfKOHQaZBITNf0uccj8GXiVmXAuPEAKSdN/4GLHhs/XWj92dN/uetNuBMnVR+XWDc25JLjo5Mg5IZIq226tmCsip2zZliL213YrTlL2hcFjpCduyim3M7/eB16q/blQsv5X/esDRbtJeabLIosWy3ycavwLhtxdWzbMmHiBTiVjJo6lCLjXZsi7p9PEPnsq6X6wd4bP11i0rD5fzPm/0A6brrIsllenZs0lCJlU4abakR59enZKrKe3BZihbTxlyZ2zl1+g0wvgmA166/bhwDrcn/7Ddz0eWZuJvfSESug6NzZsox3Z04FIxz0mUjMwVOOVTq1CQ0AhdbBGVdjG/CgsfUX7esJl3K/7ytWHRv683praW/8iDOCqWLLhpljDY1ZpzK75QiaZoOTpLKl60auHS/97oBXrv+umU9+FL+5+NtLFgjqVLCdbmj7pY5zPCPLOHNCwXGOcLquOhi8CmCWvbcuO73XmMUPab+ug3A6/A/78Bwe0bcS2+tgHn4J5pyS2WbOck0F51Vq3LcjhLvZ67p1ABbaL2H67bg78BfjKi/jr3+T/ABV3ilLmNXTI2SpvxWBtt6/Z//D0z/FXaGbSBgylzlsEGp+5//xrd4/ae4d8DUUjlslfIYS3t06HZpvfQtvv0N7AHWqtjP2pW08QD/FLy//da38vo8PNlKHf5y37Dxdfe/oj4kVIgFq3koLReSR76W/bx//n9k8jonZxzWTANVwEniDsg87sOSd/z7//PvMp3jQiptGVWFX2caezzAXwfgtzYUvbr0iozs32c3Uge7varH+CNE6cvEYmzbPZ9hMaYDdjK4V2iecf6EcEbdUDVUARda2KzO/JtCuDbNQB/iTeL0EG1JSO1jbXS+nLxtPMDPw1fh5+EPrgSEKE/8Gry5A73ui87AmxwdatyMEBCPNOCSKUeRZ2P6Myb5MRvgCHmA9ywsMifU+AYXcB6Xa5GibUC5TSyerxyh0j6QgLVpdyhfArRTTLqQjwe4HOD9s92D4Ap54odXAPBWLAwB02igG5Kkc+piN4lvODIFGAZgT+EO4Si1s7fjSR7vcQETUkRm9O+MXyo9OYhfe4xt9STQ2pcZRLayCV90b4D3jR0DYAfyxJ+eywg2IL7NTMXna7S/RpQ63JhWEM8U41ZyQGjwsVS0QBrEKLu8xwZsbi4wLcCT+OGidPIOCe1PiSc9Qt+go+vYqB7cG+B9d8cAD+WJPz0Am2gxXgU9IneOqDpAAXOsOltVuMzpdakJXrdPCzXiNVUpCeOos5cxnpQT39G+XVLhs1osQVvJKPZyNq8HDwd4d7pNDuWJPxVX7MSzqUDU6gfadKiNlUFTzLeFHHDlzO4kpa7aiKhBPGKwOqxsBAmYkOIpipyXcQSPlRTf+Tii0U3EJGaZsDER2qoB3h2hu0qe+NNwUooYU8y5mILbJe6OuX+2FTKy7bieTDAemaQyQ0CPthljSWO+xmFDIYiESjM5xKd6Ik5lvLq5GrQ3aCMLvmCA9wowLuWJb9xF59hVVP6O0CrBi3ZjZSNOvRy+I6klNVRJYRBaEzdN+imiUXQ8iVF8fsp+W4JXw7WISW7fDh7lptWkCwZ4d7QTXyBPfJMYK7SijjFppGnlIVJBJBYj7eUwtiP1IBXGI1XCsjNpbjENVpSAJ2hq2LTywEly3hUYazt31J8w2+aiLx3g3fohXixPfOMYm6zCGs9LVo9MoW3MCJE7R5u/WsOIjrqBoHUO0bJE9vxBpbhsd3+Nb4/vtPCZ4oZYCitNeYuC/8UDvDvy0qvkiW/cgqNqRyzqSZa/s0mqNGjtKOoTm14zZpUauiQgVfqtQiZjq7Q27JNaSK5ExRcrGCXO1FJYh6jR6CFqK7bZdQZ4t8g0rSlPfP1RdBtqaa9diqtzJkQ9duSryi2brQXbxDwbRUpFMBHjRj8+Nt7GDKgvph9okW7LX47gu0SpGnnFQ1S1lYldOsC7hYteR574ZuKs7Ei1lBsfdz7IZoxzzCVmmVqaSySzQbBVAWDek+N4jh9E/4VqZrJjPwiv9BC1XcvOWgO8275CVyBPvAtTVlDJfZkaZGU7NpqBogAj/xEHkeAuJihWYCxGN6e8+9JtSegFXF1TrhhLGP1fak3pebgPz192/8gB4d/6WT7+GdYnpH7hH/DJzzFiYPn/vjW0SgNpTNuPIZoAEZv8tlGw4+RLxy+ZjnKa5NdFoC7UaW0aduoYse6+bXg1DLg6UfRYwmhGEjqPvF75U558SANrElK/+MdpXvmqBpaXOa/MTZaa1DOcSiLaw9j0NNNst3c+63c7EKTpkvKHzu6bPbP0RkuHAVcbRY8ijP46MIbQeeT1mhA+5PV/inyDdQipf8LTvMXbwvoDy7IruDNVZKTfV4CTSRUYdybUCnGU7KUTDxLgCknqUm5aAW6/1p6eMsOYsphLzsHrE0Y/P5bQedx1F/4yPHnMB3/IOoTU9+BL8PhtjuFKBpZXnYNJxTuv+2XqolKR2UQgHhS5novuxVySJhBNRF3SoKK1XZbbXjVwWNyOjlqWJjrWJIy+P5bQedyldNScP+HZ61xKSK3jyrz+NiHG1hcOLL/+P+PDF2gOkekKGiNWKgJ+8Z/x8Iv4DdQHzcpZyF4v19I27w9/yPGDFQvmEpKtqv/TLiWMfn4sofMm9eAH8Ao0zzh7h4sJqYtxZd5/D7hkYPneDzl5idlzNHcIB0jVlQ+8ULzw/nc5/ojzl2juE0apD7LRnJxe04dMz2iOCFNtGFpTuXA5AhcTRo8mdN4kz30nVjEC4YTZQy4gpC7GlTlrePKhGsKKgeXpCYeO0MAd/GH7yKQUlXPLOasOH3FnSphjHuDvEu4gB8g66oNbtr6eMbFIA4fIBJkgayoXriw2XEDQPJrQeROAlY6aeYOcMf+IVYTU3XFlZufMHinGywaW3YLpObVBAsbjF4QJMsVUSayjk4voPsHJOQfPWDhCgDnmDl6XIRerD24HsGtw86RMHOLvVSHrKBdeVE26gKB5NKHzaIwLOmrqBWJYZDLhASG16c0Tn+CdRhWDgWXnqRZUTnPIHuMJTfLVpkoYy5CzylHVTGZMTwkGAo2HBlkQplrJX6U+uF1wZz2uwS1SQ12IqWaPuO4baZaEFBdukksJmkcTOm+YJSvoqPFzxFA/YUhIvWxcmSdPWTWwbAKVp6rxTtPFUZfKIwpzm4IoMfaYQLWgmlG5FME2gdBgm+J7J+rtS/XBbaVLsR7bpPQnpMFlo2doWaVceHk9+MkyguZNCJ1He+kuHTWyQAzNM5YSUg/GlTk9ZunAsg1qELVOhUSAK0LABIJHLKbqaEbHZLL1VA3VgqoiOKXYiS+HRyaEKgsfIqX64HYWbLRXy/qWoylIV9gudL1OWBNgBgTNmxA6b4txDT4gi3Ri7xFSLxtXpmmYnzAcWDZgY8d503LFogz5sbonDgkKcxGsWsE1OI+rcQtlgBBCSOKD1mtqYpIU8cTvBmAT0yZe+zUzeY92fYjTtGipXLhuR0ePoHk0ofNWBX+lo8Z7pAZDk8mEw5L7dVyZZoE/pTewbI6SNbiAL5xeygW4xPRuLCGbhcO4RIeTMFYHEJkYyEO9HmJfXMDEj/LaH781wHHZEtqSQ/69UnGpzH7LKIAZEDSPJnTesJTUa+rwTepI9dLJEawYV+ZkRn9g+QirD8vF8Mq0jFQ29js6kCS3E1+jZIhgPNanHdHFqFvPJLHqFwQqbIA4jhDxcNsOCCQLDomaL/dr5lyJaJU6FxPFjO3JOh3kVMcROo8u+C+jo05GjMF3P3/FuDLn5x2M04xXULPwaS6hBYki+MrMdZJSgPHlcB7nCR5bJ9Kr5ACUn9jk5kivdd8tk95SOGrtqu9lr2IhK65ZtEl7ZKrp7DrqwZfRUSN1el7+7NJxZbywOC8neNKTch5vsTEMNsoCCqHBCqIPRjIPkm0BjvFODGtto99rCl+d3wmHkW0FPdpZtC7MMcVtGFQjJLX5bdQ2+x9ypdc313uj8xlsrfuLgWXz1cRhZvJYX0iNVBRcVcmCXZs6aEf3RQF2WI/TcCbKmGU3IOoDJGDdDub0+hYckt6PlGu2BcxmhbTdj/klhccLGJMcqRjMJP1jW2ETqLSWJ/29MAoORluJ+6LPffBZbi5gqi5h6catQpmOT7/OFf5UorRpLzCqcMltBLhwd1are3kztrSzXO0LUbXRQcdLh/RdSZ+swRm819REDrtqzC4es6Gw4JCKlSnjYVpo0xeq33PrADbFLL3RuCmObVmPN+24kfa+AojDuM4umKe2QwCf6EN906HwjujaitDs5o0s1y+k3lgbT2W2i7FJdnwbLXhJUBq/9liTctSmFC/0OqUinb0QddTWamtjbHRFuWJJ6NpqZ8vO3fZJ37Db+2GkaPYLGHs7XTTdiFQJ68SkVJFVmY6McR5UycflNCsccHFaV9FNbR4NttLxw4pQ7wJd066Z0ohVbzihaxHVExd/ay04oxUKWt+AsdiQ9OUyZ2krzN19IZIwafSTFgIBnMV73ADj7V/K8u1MaY2sJp2HWm0f41tqwajEvdHWOJs510MaAqN4aoSiPCXtN2KSi46dUxHdaMquar82O1x5jqhDGvqmoE9LfxcY3zqA7/x3HA67r9ZG4O6Cuxu12/+TP+eLP+I+HErqDDCDVmBDO4larujNe7x8om2rMug0MX0rL1+IWwdwfR+p1TNTyNmVJ85ljWzbWuGv8/C7HD/izjkHNZNYlhZcUOKVzKFUxsxxN/kax+8zPWPSFKw80rJr9Tizyj3o1gEsdwgWGoxPezDdZ1TSENE1dLdNvuKL+I84nxKesZgxXVA1VA1OcL49dFlpFV5yJMhzyCmNQ+a4BqusPJ2bB+xo8V9u3x48VVIEPS/mc3DvAbXyoYr6VgDfh5do5hhHOCXMqBZUPhWYbWZECwVJljLgMUWOCB4MUuMaxGNUQDVI50TQ+S3kFgIcu2qKkNSHVoM0SHsgoZxP2d5HH8B9woOk4x5bPkKtAHucZsdykjxuIpbUrSILgrT8G7G5oCW+K0990o7E3T6AdW4TilH5kDjds+H64kS0mz24grtwlzDHBJqI8YJQExotPvoC4JBq0lEjjQkyBZ8oH2LnRsQ4Hu1QsgDTJbO8fQDnllitkxuVskoiKbRF9VwzMDvxHAdwB7mD9yCplhHFEyUWHx3WtwCbSMMTCUCcEmSGlg4gTXkHpZXWQ7kpznK3EmCHiXInqndkQjunG5kxTKEeGye7jWz9cyMR2mGiFQ15ENRBTbCp+Gh86vAyASdgmJq2MC6hoADQ3GosP0QHbnMHjyBQvQqfhy/BUbeHd5WY/G/9LK/8Ka8Jd7UFeNWEZvzPb458Dn8DGLOe3/wGL/4xP+HXlRt+M1PE2iLhR8t+lfgxsuh7AfO2AOf+owWhSZRYQbd622hbpKWKuU+XuvNzP0OseRDa+mObgDHJUSc/pKx31QdKffQ5OIJpt8GWjlgTwMc/w5MPCR/yl1XC2a2Yut54SvOtMev55Of45BOat9aWG27p2ZVORRvnEk1hqWMVUmqa7S2YtvlIpspuF1pt0syuZS2NV14mUidCSfzQzg+KqvIYCMljIx2YK2AO34fX4GWdu5xcIAb8MzTw+j/lyWM+Dw/gjs4GD6ehNgA48kX/AI7XXM/XAN4WHr+9ntywqoCakCqmKP0rmQrJJEErG2Upg1JObr01lKQy4jskWalKYfJ/EDLMpjNSHFEUAde2fltaDgmrNaWQ9+AAb8I5vKjz3L1n1LriB/BXkG/wwR9y/oRX4LlioHA4LzP2inzRx/DWmutRweFjeP3tNeSGlaE1Fde0OS11yOpmbIp2u/jF1n2RRZviJM0yBT3IZl2HWImKjQOxIyeU325b/qWyU9Moj1o07tS0G7qJDoGHg5m8yeCxMoEH8GU45tnrNM84D2l297DQ9t1YP7jki/7RmutRweEA77/HWXOh3HCxkRgldDQkAjNTMl2Iloc1qN5JfJeeTlyTRzxURTdn1Ixv2uKjs12AbdEWlBtmVdk2k7FFwj07PCZ9XAwW3dG+8xKzNFr4EnwBZpy9Qzhh3jDXebBpYcpuo4fQ44u+fD1dweEnHzI7v0xuuOALRUV8rXpFyfSTQYkhd7IHm07jpyhlkCmI0ALYqPTpUxXS+z4jgDj1Pflvmz5ecuItpIBxyTHpSTGWd9g1ApfD/bvwUhL4nT1EzqgX7cxfCcNmb3mPL/qi9SwTHJ49oj5ZLjccbTG3pRmlYi6JCG0mQrAt1+i2UXTZ2dv9IlQpN5naMYtviaXlTrFpoMsl3bOAFEa8sqPj2WCMrx3Yjx99qFwO59Aw/wgx+HlqNz8oZvA3exRDvuhL1jMQHPaOJ0+XyA3fp1OfM3qObEVdhxjvynxNMXQV4+GJyvOEFqeQBaIbbO7i63rpxCltdZShPFxkjM2FPVkn3TG+Rp9pO3l2RzFegGfxGDHIAh8SteR0C4HopXzRF61nheDw6TFN05Ebvq8M3VKKpGjjO6r7nhudTEGMtYM92HTDaR1FDMXJ1eThsbKfywyoWwrzRSXkc51flG3vIid62h29bIcFbTGhfV+faaB+ohj7dPN0C2e2lC96+XouFByen9AsunLDJZ9z7NExiUc0OuoYW6UZkIyx2YUR2z6/TiRjyKMx5GbbjLHvHuf7YmtKghf34LJfx63Yg8vrvN2zC7lY0x0tvKezo4HmGYDU+Gab6dFL+KI761lDcNifcjLrrr9LWZJctG1FfU1uwhoQE22ObjdfkSzY63CbU5hzs21WeTddH2BaL11Gi7lVdlxP1nkxqhnKhVY6knS3EPgVGg1JpN5cP/hivujOelhXcPj8HC/LyI6MkteVjlolBdMmF3a3DbsuAYhL44dxzthWSN065xxUd55Lmf0wRbOYOqH09/o9WbO2VtFdaMb4qBgtFJoT1SqoN8wPXMoXLb3p1PUEhxfnnLzGzBI0Ku7FxrKsNJj/8bn/H8fPIVOd3rfrklUB/DOeO+nkghgSPzrlPxluCMtOnDL4Yml6dK1r3vsgMxgtPOrMFUZbEUbTdIzii5beq72G4PD0DKnwjmBULUVFmy8t+k7fZ3pKc0Q4UC6jpVRqS9Umv8bxw35flZVOU1X7qkjnhZlsMbk24qQ6Hz7QcuL6sDC0iHHki96Uh2UdvmgZnjIvExy2TeJdMDZNSbdZyAHe/Yd1xsQhHiKzjh7GxQ4yqMPaywPkjMamvqrYpmO7Knad+ZQC5msCuAPWUoxrxVhrGv7a+KLXFhyONdTMrZ7ke23qiO40ZJUyzgYyX5XyL0mV7NiUzEs9mjtbMN0dERqwyAJpigad0B3/zRV7s4PIfXSu6YV/MK7+OrYe/JvfGMn/PHJe2fyUdtnFrKRNpXV0Y2559aWPt/G4BlvjTMtXlVIWCnNyA3YQBDmYIodFz41PvXPSa6rq9lWZawZ4dP115HXV/M/tnFkkrBOdzg6aP4pID+MZnTJ1SuuB6iZlyiox4HT2y3YBtkUKWooacBQUDTpjwaDt5poBHl1/HXltwP887lKKXxNUEyPqpGTyA699UqY/lt9yGdlUKra0fFWS+36iylVWrAyd7Uw0CZM0z7xKTOduznLIjG2Hx8cDPLb+OvK6Bv7n1DYci4CxUuRxrjBc0bb4vD3rN5Zz36ntLb83eVJIB8LiIzCmn6SMPjlX+yNlTjvIGjs+QzHPf60Aj62/jrzG8j9vYMFtm1VoRWCJdmw7z9N0t+c8cxZpPeK4aTRicS25QhrVtUp7U578chk4q04Wx4YoQSjFryUlpcQ1AbxZ/XVMknIU//OGl7Q6z9Zpxi0+3yFhSkjUDpnCIUhLWVX23KQ+L9vKvFKI0ZWFQgkDLvBoylrHNVmaw10zwCPrr5tlodfnf94EWnQ0lFRWy8pW9LbkLsyUVDc2NSTHGDtnD1uMtchjbCeb1mpxFP0YbcClhzdLu6lfO8Bj6q+bdT2sz/+8SZCV7VIxtt0DUn9L7r4cLYWDSXnseEpOGFuty0qbOVlS7NNzs5FOGJUqQpl2Q64/yBpZf90sxbE+//PGdZ02HSipCbmD6NItmQ4Lk5XUrGpDMkhbMm2ZVheNYV+VbUWTcv99+2NyX1VoafSuC+AN6q9bFIMv5X/eagNWXZxEa9JjlMwNWb00akGUkSoepp1/yRuuqHGbUn3UdBSTxBU6SEVklzWRUkPndVvw2PrrpjvxOvzPmwHc0hpmq82npi7GRro8dXp0KXnUQmhZbRL7NEVp1uuZmO45vuzKsHrktS3GLWXODVjw+vXXLYx4Hf7njRPd0i3aoAGX6W29GnaV5YdyDj9TFkakje7GHYzDoObfddHtOSpoi2SmzJHrB3hM/XUDDEbxP2/oosszcRlehWXUvzHv4TpBVktHqwenFo8uLVmy4DKLa5d3RtLrmrM3aMFr1183E4sewf+85VWeg1c5ag276NZrM9IJVNcmLEvDNaV62aq+14IAOGFsBt973Ra8Xv11YzXwNfmft7Jg2oS+XOyoC8/cwzi66Dhmgk38kUmP1CUiYWOX1bpD2zWXt2FCp7uq8703APAa9dfNdscR/M/bZLIyouVxqJfeWvG9Je+JVckHQ9+CI9NWxz+blX/KYYvO5n2tAP/vrlZ7+8/h9y+9qeB/Hnt967e5mevX10rALDWK//FaAT5MXdBXdP0C/BAes792c40H+AiAp1e1oH8HgH94g/Lttx1gp63op1eyoM/Bvw5/G/7xFbqJPcCXnmBiwDPb/YKO4FX4OjyCb289db2/Noqicw4i7N6TVtoz8tNwDH+8x/i6Ae7lmaQVENzJFb3Di/BFeAwz+Is9SjeQySpPqbLFlNmyz47z5a/AF+AYFvDmHqibSXTEzoT4Gc3OALaqAP4KPFUJ6n+1x+rGAM6Zd78bgJ0a8QN4GU614vxwD9e1Amy6CcskNrczLx1JIp6HE5UZD/DBHrFr2oNlgG4Odv226BodoryjGJ9q2T/AR3vQrsOCS0ctXZi3ruLlhpFDJYl4HmYtjQCP9rhdn4suySLKDt6wLcC52h8xPlcjju1fn+yhuw4LZsAGUuo2b4Fx2UwQu77uqRHXGtg92aN3tQCbFexc0uk93vhTXbct6y7MulLycoUljx8ngDMBg1tvJjAazpEmOtxlzclvj1vQf1Tx7QlPDpGpqgtdSKz/d9/hdy1vTfFHSmC9dGDZbLiezz7Ac801HirGZsWjydfZyPvHXL/Y8Mjzg8BxTZiuwKz4Eb8sBE9zznszmjvFwHKPIWUnwhqfVRcd4Ck0K6ate48m1oOfrX3/yOtvAsJ8zsPAM89sjnddmuLuDPjX9Bu/L7x7xpMzFk6nWtyQfPg278Gn4Aekz2ZgOmU9eJ37R14vwE/BL8G3aibCiWMWWDQ0ZtkPMnlcGeAu/Ag+8ZyecU5BPuy2ILD+sQqyZhAKmn7XZd+jIMTN9eBL7x95xVLSX4On8EcNlXDqmBlqS13jG4LpmGbkF/0CnOi3H8ETOIXzmnmtb0a16Tzxj1sUvQCBiXZGDtmB3KAefPH94xcUa/6vwRn80GOFyjEXFpba4A1e8KQfFF+259tx5XS4egYn8fQsLGrqGrHbztr+uByTahWuL1NUGbDpsnrwBfePPwHHIf9X4RnM4Z2ABWdxUBlqQ2PwhuDxoS0vvqB1JzS0P4h2nA/QgTrsJFn+Y3AOjs9JFC07CGWX1oNX3T/yHOzgDjwPn1PM3g9Jk9lZrMEpxnlPmBbjyo2+KFXRU52TJM/2ALcY57RUzjObbjqxVw++4P6RAOf58pcVsw9Daje3htriYrpDOonre3CudSe6bfkTEgHBHuDiyu5MCsc7BHhYDx7ePxLjqigXZsw+ijMHFhuwBmtoTPtOxOrTvYJDnC75dnUbhfwu/ZW9AgYd+peL68HD+0emKquiXHhWjJg/UrkJYzuiaL3E9aI/ytrCvAd4GcYZMCkSQxfUg3v3j8c4e90j5ZTPdvmJJGHnOCI2nHS8081X013pHuBlV1gB2MX1YNmWLHqqGN/TWmG0y6clJWthxNUl48q38Bi8vtMKyzzpFdSDhxZ5WBA5ZLt8Jv3895DduBlgbPYAj8C4B8hO68FDkoh5lydC4FiWvBOVqjYdqjiLv92t8yPDjrDaiHdUD15qkSURSGmXJwOMSxWAXYwr3zaAufJ66l+94vv3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/wHuD9tQd4f+0B3l97gPfXHuD9tQd4f+0B3l97gG8LwP8G/AL8O/A5OCq0Ys2KIdv/qOIXG/4mvFAMF16gZD+2Xvu/B8as5+8bfllWyg0zaNO5bfXj6vfhhwD86/Aq3NfRS9t9WPnhfnvCIw/CT8GLcFTMnpntdF/z9V+PWc/vWoIH+FL3Znv57PitcdGP4R/C34avw5fgRVUInCwbsn1yyA8C8zm/BH8NXoXnVE6wVPjdeCI38kX/3+Ct9dbz1pTmHFRu+Hm4O9Ch3clr99negxfwj+ER/DR8EV6B5+DuQOnTgUw5rnkY+FbNU3gNXh0o/JYTuWOvyBf9FvzX663HH/HejO8LwAl8Hl5YLTd8q7sqA3wbjuExfAFegQdwfyDoSkWY8swzEf6o4Qyewefg+cHNbqMQruSL/u/WWc+E5g7vnnEXgDmcDeSGb/F4cBcCgT+GGRzDU3hZYburAt9TEtHgbM6JoxJ+6NMzzTcf6c2bycv2+KK/f+l6LBzw5IwfqZJhA3M472pWT/ajKxnjv4AFnMEpnBTPND6s2J7qHbPAqcMK74T2mZ4VGB9uJA465It+/eL1WKhYOD7xHOkr1ajK7d0C4+ke4Hy9qXZwpgLr+Znm/uNFw8xQOSy8H9IzjUrd9+BIfenYaylf9FsXr8fBAadnPIEDna8IBcwlxnuA0/Wv6GAWPd7dDIKjMdSWueAsBj4M7TOd06qBbwDwKr7oleuxMOEcTuEZTHWvDYUO7aHqAe0Bbq+HEFRzOz7WVoTDQkVds7A4sIIxfCQdCefFRoIOF/NFL1mPab/nvOakSL/Q1aFtNpUb/nFOVX6gzyg/1nISyDfUhsokIzaBR9Kxm80s5mK+6P56il1jXic7nhQxsxSm3OwBHl4fFdLqi64nDQZvqE2at7cWAp/IVvrN6/BFL1mPhYrGMBfOi4PyjuSGf6wBBh7p/FZTghCNWGgMzlBbrNJoPJX2mW5mwZfyRffXo7OFi5pZcS4qZUrlViptrXtw+GQoyhDPS+ANjcGBNRiLCQDPZPMHuiZfdFpPSTcQwwKYdRNqpkjm7AFeeT0pJzALgo7g8YYGrMHS0iocy+YTm2vyRUvvpXCIpQ5pe666TJrcygnScUf/p0NDs/iAI/nqDHC8TmQT8x3NF91l76oDdQGwu61Z6E0ABv7uO1dbf/37Zlv+Zw/Pbh8f1s4Avur6657/+YYBvur6657/+YYBvur6657/+YYBvur6657/+aYBvuL6657/+VMA8FXWX/f8zzcN8BXXX/f8zzcNMFdbf93zP38KLPiK6697/uebtuArrr/u+Z9vGmCusP6653/+1FjwVdZf9/zPN7oHX339dc//fNMu+irrr3v+50+Bi+Zq6697/uebA/jz8Pudf9ht/fWv517J/XUzAP8C/BAeX9WCDrUpZ3/dEMBxgPcfbtTVvsYV5Yn32u03B3Ac4P3b8I+vxNBKeeL9dRMAlwO83959qGO78sT769oB7g3w/vGVYFzKE++v6wV4OMD7F7tckFkmT7y/rhHgpQO8b+4Y46XyxPvrugBeNcB7BRiX8sT767oAvmCA9woAHsoT76+rBJjLBnh3txOvkifeX1dswZcO8G6N7sXyxPvr6i340gHe3TnqVfLE++uKAb50gHcXLnrX8sR7gNdPRqwzwLu7Y/FO5Yn3AK9jXCMGeHdgxDuVJ75VAI8ljP7PAb3/RfjcZfePHBB+79dpfpH1CanN30d+mT1h9GqAxxJGM5LQeeQ1+Tb+EQJrElLb38VHQ94TRq900aMIo8cSOo+8Dp8QfsB8zpqE1NO3OI9Zrj1h9EV78PqE0WMJnUdeU6E+Jjyk/hbrEFIfeWbvId8H9oTRFwdZaxJGvziW0Hn0gqYB/wyZ0PwRlxJST+BOw9m77Amj14ii1yGM/txYQudN0qDzGe4EqfA/5GJCagsHcPaEPWH0esekSwmjRxM6b5JEcZ4ww50ilvAOFxBSx4yLW+A/YU8YvfY5+ALC6NGEzhtmyZoFZoarwBLeZxUhtY4rc3bKnjB6TKJjFUHzJoTOozF2YBpsjcyxDgzhQ1YRUse8+J4wenwmaylB82hC5w0zoRXUNXaRBmSMQUqiWSWkLsaVqc/ZE0aPTFUuJWgeTei8SfLZQeMxNaZSIzbII4aE1Nmr13P2hNHjc9E9guYNCZ032YlNwESMLcZiLQHkE4aE1BFg0yAR4z1h9AiAGRA0jyZ03tyIxWMajMPWBIsxYJCnlITU5ShiHYdZ94TR4wCmSxg9jtB5KyPGYzymAYexWEMwAPIsAdYdV6aObmNPGD0aYLoEzaMJnTc0Ygs+YDw0GAtqxBjkuP38bMRWCHn73xNGjz75P73WenCEJnhwyVe3AEe8TtKdJcYhBl97wuhNAObK66lvD/9J9NS75v17wuitAN5fe4D31x7g/bUHeH/tAd5fe4D3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/w/toDvAd4f/24ABzZ8o+KLsSLS+Pv/TqTb3P4hKlQrTGh+fbIBT0Axqznnb+L/V2mb3HkN5Mb/nEHeK7d4IcDld6lmDW/iH9E+AH1MdOw/Jlu2T1xNmY98sv4wHnD7D3uNHu54WUuOsBTbQuvBsPT/UfzNxGYzwkP8c+Yz3C+r/i6DcyRL/rZ+utRwWH5PmfvcvYEt9jLDS/bg0/B64DWKrQM8AL8FPwS9beQCe6EMKNZYJol37jBMy35otdaz0Bw2H/C2Smc7+WGB0HWDELBmOByA3r5QONo4V+DpzR/hFS4U8wMW1PXNB4TOqYz9urxRV++ntWCw/U59Ty9ebdWbrgfRS9AYKKN63ZokZVygr8GZ/gfIhZXIXPsAlNjPOLBby5c1eOLvmQ9lwkOy5x6QV1j5TYqpS05JtUgUHUp5toHGsVfn4NX4RnMCe+AxTpwmApTYxqMxwfCeJGjpXzRF61nbcHhUBPqWze9svwcHJ+S6NPscKrEjug78Dx8Lj3T8D4YxGIdxmJcwhi34fzZUr7olevZCw5vkOhoClq5zBPZAnygD/Tl9EzDh6kl3VhsHYcDEb+hCtJSvuiV69kLDm+WycrOTArHmB5/VYyP6jOVjwgGawk2zQOaTcc1L+aLXrKeveDwZqlKrw8U9Y1p66uK8dEzdYwBeUQAY7DbyYNezBfdWQ97weEtAKYQg2xJIkuveAT3dYeLGH+ShrWNwZgN0b2YL7qznr3g8JYAo5bQBziPjx7BPZ0d9RCQp4UZbnFdzBddor4XHN4KYMrB2qHFRIzzcLAHQZ5the5ovui94PCWAPefaYnxIdzRwdHCbuR4B+tbiy96Lzi8E4D7z7S0mEPd+eqO3cT53Z0Y8SV80XvB4Z0ADJi/f7X113f+7p7/+UYBvur6657/+YYBvur6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+VMA8FXWX/f8z58OgK+y/rrnf75RgLna+uue//lTA/CV1V/3/M837aKvvv6653++UQvmauuve/7nTwfAV1N/3fM/fzr24Cuuv+75nz8FFnxl9dc9//MOr/8/glixwRuUfM4AAAAASUVORK5CYII="}getSearchTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII="}};var LuminosityHighPassShader={shaderID:"luminosityHighPass",uniforms:{"tDiffuse":{value:null},"luminosityThreshold":{value:1},"smoothWidth":{value:1},"defaultColor":{value:new Color(0)},"defaultOpacity":{value:0}},vertexShader:`\n\n varying vec2 vUv;\n\n void main() {\n\n vUv = uv;\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n }`,fragmentShader:`\n\n uniform sampler2D tDiffuse;\n uniform vec3 defaultColor;\n uniform float defaultOpacity;\n uniform float luminosityThreshold;\n uniform float smoothWidth;\n\n varying vec2 vUv;\n\n void main() {\n\n vec4 texel = texture2D( tDiffuse, vUv );\n\n vec3 luma = vec3( 0.299, 0.587, 0.114 );\n\n float v = dot( texel.xyz, luma );\n\n vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );\n\n float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );\n\n gl_FragColor = mix( outputColor, texel, alpha );\n\n }`};var UnrealBloomPass=class extends Pass{constructor(resolution,strength,radius,threshold){super();this.strength=strength!==void 0?strength:1;this.radius=radius;this.threshold=threshold;this.resolution=resolution!==void 0?new Vector2(resolution.x,resolution.y):new Vector2(256,256);this.clearColor=new Color(0,0,0);this.renderTargetsHorizontal=[];this.renderTargetsVertical=[];this.nMips=5;let resx=Math.round(this.resolution.x/2);let resy=Math.round(this.resolution.y/2);this.renderTargetBright=new WebGLRenderTarget(resx,resy);this.renderTargetBright.texture.name="UnrealBloomPass.bright";this.renderTargetBright.texture.generateMipmaps=false;for(let i=0;i\n varying vec2 vUv;\n uniform sampler2D colorTexture;\n uniform vec2 texSize;\n uniform vec2 direction;\n\n float gaussianPdf(in float x, in float sigma) {\n return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\n }\n void main() {\n vec2 invSize = 1.0 / texSize;\n float fSigma = float(SIGMA);\n float weightSum = gaussianPdf(0.0, fSigma);\n vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\n for( int i = 1; i < KERNEL_RADIUS; i ++ ) {\n float x = float(i);\n float w = gaussianPdf(x, fSigma);\n vec2 uvOffset = direction * invSize * x;\n vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\n vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\n diffuseSum += (sample1 + sample2) * w;\n weightSum += 2.0 * w;\n }\n gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\n }`})}getCompositeMaterial(nMips){return new ShaderMaterial({defines:{"NUM_MIPS":nMips},uniforms:{"blurTexture1":{value:null},"blurTexture2":{value:null},"blurTexture3":{value:null},"blurTexture4":{value:null},"blurTexture5":{value:null},"bloomStrength":{value:1},"bloomFactors":{value:null},"bloomTintColors":{value:null},"bloomRadius":{value:0}},vertexShader:`varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }`,fragmentShader:`varying vec2 vUv;\n uniform sampler2D blurTexture1;\n uniform sampler2D blurTexture2;\n uniform sampler2D blurTexture3;\n uniform sampler2D blurTexture4;\n uniform sampler2D blurTexture5;\n uniform float bloomStrength;\n uniform float bloomRadius;\n uniform float bloomFactors[NUM_MIPS];\n uniform vec3 bloomTintColors[NUM_MIPS];\n\n float lerpBloomFactor(const in float factor) {\n float mirrorFactor = 1.2 - factor;\n return mix(factor, mirrorFactor, bloomRadius);\n }\n\n void main() {\n gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) +\n lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) +\n lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) +\n lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) +\n lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );\n }`})}};UnrealBloomPass.BlurDirectionX=new Vector2(1,0);UnrealBloomPass.BlurDirectionY=new Vector2(0,1);var PickHelper=class{constructor(){this.raycaster=new Raycaster;this.pickedObject=null;this.pickedObjectSavedColor=0}pick(normalizedPosition,scene,camera,time){if(this.pickedObject){this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);this.pickedObject=void 0}this.raycaster.setFromCamera(normalizedPosition,camera);const intersectedObjects=this.raycaster.intersectObjects(scene.children);if(intersectedObjects.length){this.pickedObject=intersectedObjects[0].object;this.pickedObjectSavedColor=this.pickedObject.material.emissive.getHex();this.pickedObject.material.emissive.setHex(time*8%2>1?16776960:16711680)}}};if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope){const worker=new WorkerService({services:{ECSService,unsafeRoutes},tree:{...workerCanvasRoutes,receiveThreeCanvas:function(options){const ThreeProps={THREE:three_module_exports,OrbitControls,EffectComposer,RenderPass,SMAAPass,UnrealBloomPass,PickHelper};Object.assign(options,ThreeProps);console.log(this);let renderId=this.__node.graph.run("setupCanvas",options);return renderId}}});worker.run("addSystems",Systems,["boid","nbody","collision","collider","movement"]);console.log(worker)}var worker_default=self;})();\n/**\n * @license\n * Copyright 2010-2022 Three.js Authors\n * SPDX-License-Identifier: MIT\n */\n')], { type: "text/javascript" })); + var worker_default = url; + + // index.ts + var workers = new WorkerService(); + var router = new Router({ + services: { + workers, + workerCanvasRoutes + }, + loaders: { + htmlloader + } + }); + console.log(router); + document.body.style.height = "100vh"; + var ret = router.setTree({ + "main": { + tagName: "div", + __children: { + "div": { + tagName: "div", + innerText: "Multithreaded canvases!" + }, + "canvas": { + tagName: "canvas", + style: { width: "100%", height: "100%" }, + __onrender: function(elm) { + const renderer = workers.addWorker({ url: worker_default }); + this.worker = renderer; + if (renderer) { + const controls = router.run("transferCanvas", renderer.worker, { + canvas: elm, + context: void 0, + _id: elm.id, + init: (self2, canvas, context) => { + const THREE = self2.THREE; + const OrbitControls = self2.OrbitControls; + const PickHelper = self2.PickHelper; + const renderer2 = new THREE.WebGLRenderer({ canvas }); + let time = 0; + let lastFrame = Date.now(); + const fov = 75; + const aspect = 2; + const near = 0.1; + const far = 100; + const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); + camera.position.z = 4; + renderer2.setSize(canvas.width, canvas.height, false); + if (camera) { + camera.aspect = canvas.clientWidth / canvas.clientHeight; + camera.updateProjectionMatrix(); + } + const controls2 = new OrbitControls(camera, canvas); + controls2.target.set(0, 0, 0); + controls2.update(); + const scene = new THREE.Scene(); + { + const color = 16777215; + const intensity = 1; + const light = new THREE.DirectionalLight(color, intensity); + light.position.set(-1, 2, 4); + scene.add(light); + } + const boxWidth = 1; + const boxHeight = 1; + const boxDepth = 1; + const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); + const makeInstance = (geometry2, color, x) => { + const material = new THREE.MeshPhongMaterial({ + color + }); + const cube = new THREE.Mesh(geometry2, material); + scene.add(cube); + cube.position.x = x; + return cube; + }; + const cubes = [ + makeInstance(geometry, 4500104, 0), + makeInstance(geometry, 8930474, -2), + makeInstance(geometry, 11176004, 2) + ]; + let getCanvasRelativePosition = (event) => { + const rect = canvas.getBoundingClientRect(); + return { + x: event.clientX - rect.left, + y: event.clientY - rect.top + }; + }; + const pickPosition = { x: -2, y: -2 }; + const pickHelper = new PickHelper(); + let setPickPosition = (event) => { + const pos = getCanvasRelativePosition(event); + pickPosition.x = pos.x / canvas.clientWidth * 2 - 1; + pickPosition.y = pos.y / canvas.clientHeight * -2 + 1; + }; + let clearPickPosition = () => { + pickPosition.x = -1e5; + pickPosition.y = -1e5; + }; + canvas.addEventListener("mousemove", setPickPosition); + canvas.addEventListener("mouseout", clearPickPosition); + canvas.addEventListener("mouseleave", clearPickPosition); + canvas.addEventListener("touchstart", (event) => { + event.preventDefault(); + setPickPosition(event.touches[0]); + }, { passive: false }); + canvas.addEventListener("touchmove", (event) => { + setPickPosition(event.touches[0]); + }); + canvas.addEventListener("touchend", clearPickPosition); + canvas.addEventListener("resize", (ev) => { + renderer2.setSize(canvas.width, canvas.height, false); + if (camera) { + camera.aspect = canvas.clientWidth / canvas.clientHeight; + camera.updateProjectionMatrix(); + } + }); + Object.assign(self2, { + renderer: renderer2, + camera, + controls: controls2, + scene, + cubes, + time, + lastFrame, + pickPosition, + pickHelper + }); + clearPickPosition(); + }, + draw: (self2, canvas, context) => { + let now = Date.now(); + self2.time += (now - self2.lastFrame) * 1e-3; + self2.lastFrame = now; + self2.cubes.forEach((cube, ndx) => { + const speed = 1 + ndx * 0.1; + const rot = self2.time * speed; + cube.rotation.x = rot; + cube.rotation.y = rot; + }); + self2.pickHelper.pick(self2.pickPosition, self2.scene, self2.camera, self2.time); + self2.renderer.render(self2.scene, self2.camera); + }, + clear: (self2, canvas, context) => { + if (self2.renderer) { + self2.render.domElement = null; + self2.renderer = null; + self2.composer = null; + self2.gui = null; + self2.controls = null; + self2.camera = null; + self2.scene = null; + } + } + }, "receiveThreeCanvas"); + } + }, + __onremove: function(elm) { + workers.terminate(this.worker._id); + } + } + } + } + }); +})(); diff --git a/examples/workerthreejs/dist/worker.js b/examples/workerthreejs/dist/worker.js new file mode 100644 index 00000000..83677152 --- /dev/null +++ b/examples/workerthreejs/dist/worker.js @@ -0,0 +1,688 @@ +(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __accessCheck=(obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)};var __privateGet=(obj,member,getter)=>{__accessCheck(obj,member,"read from private field");return getter?getter.call(obj):member.get(obj)};var __privateAdd=(obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)};var __privateSet=(obj,member,value,setter)=>{__accessCheck(obj,member,"write to private field");setter?setter.call(obj,value):member.set(obj,value);return value};var require_sjcl=__commonJS({"../../services/e2ee/sjcl.js"(exports,module){"use strict";var sjcl2={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};sjcl2.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl2.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&255]]};sjcl2.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;256>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=16843009*n^65537*e^257*l^16843008*f,n=257*h[m]^16843008*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};function t(a,b,c){if(4!==b.length)throw new sjcl2.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x2=h[4];for(m=0;m>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=0;4>m;m++)r[c?3&-m:m]=x2[e>>>24]<<24^x2[f>>16&255]<<16^x2[g>>8&255]<<8^x2[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}sjcl2.bitArray={bitSlice:function(a,b,c){a=sjcl2.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl2.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(sjcl2.bitArray.bitLength(a)!==sjcl2.bitArray.bitLength(b))return false;var c=0,d;for(d=0;d>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl2.bitArray.getPartial(e);d.push(sjcl2.bitArray.partial(b+a&31,32>>24|c>>>8&65280|(c&65280)<<8|c<<24;return a}};sjcl2.codec.utf8String={fromBits:function(a){var b="",c=sjcl2.bitArray.bitLength(a),d,e;for(d=0;d>>8>>>8>>>8),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c>>g)>>>e),gn){if(!b)try{return sjcl2.codec.base32hex.toBits(a)}catch(p){}throw new sjcl2.exception.invalid("this isn't "+m+"!")}h>e?(h-=e,f.push(l^n>>>h),l=n<>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl2.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;dh)throw new sjcl2.exception.invalid("this isn't base64!");26>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl2.bitArray.partial(e&56,g,1));return c}};sjcl2.codec.base64url={fromBits:function(a){return sjcl2.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl2.codec.base64.toBits(a,1)}};sjcl2.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl2.hash.sha256.hash=function(a){return new sjcl2.hash.sha256().update(a).finalize()};sjcl2.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));var b,c=this.A=sjcl2.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl2.bitArray.bitLength(a);if(9007199254740991b;c++){e=true;for(d=2;d*d<=c;d++)if(0===c%d){e=false;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=f[7]+q|0}sjcl2.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl2.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl2.mode.ccm.G.indexOf(a);-1k)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,8*(15-f));b=sjcl2.mode.ccm.V(a,b,c,d,e,f);g=sjcl2.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl2.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl2.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl2.mode.ccm.C(a,k,c,l,e,b);a=sjcl2.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl2.exception.corrupt("ccm: tag doesn't match");return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl2.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:4294967295>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;be||16n&&(sjcl2.mode.ccm.fa(g/k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};sjcl2.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl2.bitArray.bitLength(c))throw new sjcl2.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl2.mode.ocb2.S,k=sjcl2.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};sjcl2.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl2.bitArray;d=d||[];a=sjcl2.mode.gcm.C(true,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl2.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl2.mode.gcm.C(false,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl2.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl2.bitArray.i;e=[0,0,0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-520093696)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;de&&(a=b.hash(a));for(d=0;dd||0>c)throw new sjcl2.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl2.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl2.codec.utf8String.toBits(b));e=e||sjcl2.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl2.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;gg;g++)e.push(4294967296*Math.random()|0);for(g=0;g=1<this.o&&(this.o=f);this.P++;this.b=sjcl2.hash.sha256.hash(this.b.concat(e));this.L=new sjcl2.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case"string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl2.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&new Date().valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,false),window.addEventListener("mousemove",this.a.mouseCollector,false),window.addEventListener("keypress",this.a.keyboardCollector,false),window.addEventListener("devicemotion",this.a.accelerometerCollector,false),window.addEventListener("touchmove",this.a.touchCollector,false);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl2.exception.bug("can't attach event");this.D=true}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,false),window.removeEventListener("mousemove",this.a.mouseCollector,false),window.removeEventListener("keypress",this.a.keyboardCollector,false),window.removeEventListener("devicemotion",this.a.accelerometerCollector,false),window.removeEventListener("touchmove",this.a.touchCollector,false)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=false)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;cb&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}function B(a,b){return function(){b.apply(a,arguments)}}sjcl2.random=new sjcl2.prng(6);a:try{if(G="undefined"!==typeof module&&module.exports){try{H=__require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array(new Uint8Array(D).buffer),sjcl2.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);else break a;sjcl2.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}var D;var E;var F;var G;var H;sjcl2.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl2.json,f=e.g({iv:sjcl2.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl2.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl2.codec.base64.toBits(f.iv));if(!sjcl2.mode[f.mode]||!sjcl2.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&256!==f.ks||2>f.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||4{try{return _Buffer}catch(_){try{return Buffer}catch(_2){return null}}})();var isBuffer=function(obj){return!!(obj!=null&&obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj))};var hexTable=[];for(i=0;i<256;i++){hexTable[i]=(i<=15?"0":"")+i.toString(16)}var i;var checkForHexRegExp=new RegExp("^[0-9a-fA-F]{24}$");var decodeLookup=[];i=0;while(i<10)decodeLookup[48+i]=i++;while(i<16)decodeLookup[65-10+i]=decodeLookup[97-10+i]=i++;function ObjectID2(id2){if(!(this instanceof ObjectID2))return new ObjectID2(id2);if(id2&&(id2 instanceof ObjectID2||id2._bsontype==="ObjectID"))return id2;this._bsontype="ObjectID";if(id2==null||typeof id2==="number"){this.id=this.generate(id2);return}var valid=ObjectID2.isValid(id2);if(!valid&&id2!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(valid&&typeof id2==="string"&&id2.length===24){return ObjectID2.createFromHexString(id2)}else if(id2!=null&&id2.length===12){this.id=id2}else if(id2!=null&&typeof id2.toHexString==="function"){return id2}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}}module.exports=ObjectID2;ObjectID2.default=ObjectID2;ObjectID2.createFromTime=function(time){time=parseInt(time,10)%4294967295;return new ObjectID2(hex(8,time)+"0000000000000000")};ObjectID2.createFromHexString=function(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}var data="";var i2=0;while(i2<24){data+=String.fromCharCode(decodeLookup[hexString.charCodeAt(i2++)]<<4|decodeLookup[hexString.charCodeAt(i2++)])}return new ObjectID2(data)};ObjectID2.isValid=function(id2){if(id2==null)return false;if(typeof id2==="number"){return true}if(typeof id2==="string"){return id2.length===12||id2.length===24&&checkForHexRegExp.test(id2)}if(id2 instanceof ObjectID2){return true}if(isBuffer(id2)){return ObjectID2.isValid(id2.toString("hex"))}if(typeof id2.toHexString==="function"){if(BufferCtr&&(id2.id instanceof BufferCtr||typeof id2.id==="string")){return id2.id.length===12||id2.id.length===24&&checkForHexRegExp.test(id2.id)}}return false};ObjectID2.prototype={constructor:ObjectID2,toHexString:function(){if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id.length===24){return this.id}if(isBuffer(this.id)){return this.id.toString("hex")}var hexString="";for(var i2=0;i2>24&255,time>>16&255,time>>8&255,time&255,MACHINE_ID>>16&255,MACHINE_ID>>8&255,MACHINE_ID&255,pid>>8&255,pid&255,inc>>16&255,inc>>8&255,inc&255)}};function next(){return index=(index+1)%16777215}function hex(length,n){n=n.toString(16);return n.length===length?n:"00000000".substring(n.length,length)+n}var inspect=Symbol&&Symbol.for&&Symbol.for("nodejs.util.inspect.custom")||"inspect";ObjectID2.prototype[inspect]=function(){return"ObjectID("+this+")"};ObjectID2.prototype.toJSON=ObjectID2.prototype.toHexString;ObjectID2.prototype.toString=ObjectID2.prototype.toHexString}});var props_loader_default=node=>{if(node.__properties.__props)node.____apply(node.__properties.__props,true)};var __defProp2=Object.defineProperty;var __export2=(target,all)=>{for(var name in all)__defProp2(target,name,{get:all[name],enumerable:true})};var moduleStringTag="[object Module]";var esm=object=>{const res=object&&(!!Object.keys(object).reduce((a,b)=>{const desc=Object.getOwnPropertyDescriptor(object,b);const isModule=desc&&desc.get&&!desc.set?1:0;return a+isModule},0)||Object.prototype.toString.call(object)===moduleStringTag);return!!res};var isSame=(a,b)=>{if(a&&typeof a==="object"&&b&&typeof b==="object"){const jA=JSON.stringify(a);const jB=JSON.stringify(b);return jA===jB}else return a===b};var iterateSymbols=(obj,callback)=>{return Promise.all(Object.getOwnPropertySymbols(obj).map(sym=>callback(sym,obj[sym])))};var getPath=(type,info2)=>{const pathType=info2.path[type];if(!pathType)throw new Error("Invalid Path Type");const filtered=pathType.filter(v=>typeof v==="string");return filtered.join(info2.keySeparator)};var getPathInfo=(path,options)=>{let splitPath=path;if(typeof path==="string")splitPath=path.split(options.keySeparator);else if(typeof path==="symbol")splitPath=[path];return{id:splitPath[0],path:splitPath.slice(1)}};var runCallback=(callback,path,info2,output,setGlobal=true)=>{if(callback instanceof Function){if(output&&typeof output==="object"&&typeof output.then==="function")output.then(value=>callback(path,info2,value));else callback(path,info2,output)}if(setGlobal&&globalThis.ESMonitorState){const callback2=globalThis.ESMonitorState.callback;globalThis.ESMonitorState.state[path]={output,value:info2};runCallback(callback2,path,info2,output,false)}};var defaultSamplingRate=60;var _pollingId,_sps,_a;var Poller=(_a=class{constructor(listeners2,sps){__privateAdd(this,_pollingId,void 0);__privateAdd(this,_sps,void 0);this.listeners={};this.setOptions=(opts={})=>{for(let key in opts)this[key]=opts[key]};this.add=info2=>{const sub=info2.sub;this.listeners[sub]=info2;this.start();return true};this.get=sub=>this.listeners[sub];this.remove=sub=>{delete this.listeners[sub];if(!Object.keys(this.listeners).length)this.stop()};this.poll=listeners22=>{iterateSymbols(listeners22,(sym,o)=>{let{callback,current,history}=o;if(!o.path.resolved)o.path.resolved=getPath("output",o);if(!isSame(current,history)){runCallback(callback,o.path.resolved,{},current);if(typeof current==="object"){if(Array.isArray(current))history=[...current];else history={...current}}else listeners22[sym].history=current}})};this.start=(listeners22=this.listeners)=>{if(!this.sps)this.sps=defaultSamplingRate;else if(!__privateGet(this,_pollingId)){console.warn("[escode]: Starting Polling!");__privateSet(this,_pollingId,setInterval(()=>this.poll(listeners22),1e3/this.sps))}};this.stop=()=>{if(__privateGet(this,_pollingId)){console.warn("[escode]: Stopped Polling!");clearInterval(__privateGet(this,_pollingId));__privateSet(this,_pollingId,void 0)}};if(listeners2)this.listeners=listeners2;if(sps)this.sps=sps}get sps(){return __privateGet(this,_sps)}set sps(sps){__privateSet(this,_sps,sps);const listeners2=this.listeners;const nListeners=Object.keys(listeners2).length;if(nListeners){this.stop();this.start()}}},_pollingId=new WeakMap,_sps=new WeakMap,_a);var listeners_exports={};__export2(listeners_exports,{functionExecution:()=>functionExecution,functions:()=>functions2,getProxyFunction:()=>getProxyFunction,info:()=>info,register:()=>register,set:()=>set,setterExecution:()=>setterExecution,setters:()=>setters});globalThis.ESMonitorState={state:{},callback:void 0,info:{}};var global_default=globalThis.ESMonitorState;var performance2=async(callback,args)=>{const tic=globalThis.performance.now();const output=await callback(...args);const toc=globalThis.performance.now();return{output,value:toc-tic}};var infoFunctions={performance:performance2};var get=(func,args,info2)=>{let result={value:{},output:void 0};const infoToGet={...global_default.info,...info2};for(let key in infoToGet){if(infoToGet[key]&&infoFunctions[key]){const ogFunc=func;func=async(...args2)=>{const o=await infoFunctions[key](ogFunc,args2);result.value[key]=o.value;return o.output}}}result.output=func(...args);return result};var isProxy=Symbol("isProxy");var fromInspectable=Symbol("fromInspectable");var fromInspectableHandler=Symbol("fromInspectableHandler");var keySeparator=".";var hasKey=(key,obj)=>key in obj;var getShortcut=(path,shortcuts,keySeparator2)=>{const sc=shortcuts[path[0]];if(sc){const value=sc[path.slice(1).join(keySeparator2)];if(value)return value}};var getFromPath=(baseObject,path,opts={})=>{const fallbackKeys=opts.fallbacks??[];const keySeparator2=opts.keySeparator??keySeparator;if(opts.shortcuts){const shortcut=getShortcut(path,opts.shortcuts,keySeparator2);if(shortcut){if(opts.output==="info")return{value:shortcut,exists:true,shortcut:true};else return shortcut}}if(typeof path==="string")path=path.split(keySeparator2).flat();else if(typeof path=="symbol")path=[path];let exists;path=[...path];path=path.map(o=>typeof o==="string"?o.split(keySeparator2):o).flat();let ref=baseObject;for(let i=0;i{const create=opts?.create??false;const keySeparator2=opts?.keySeparator??keySeparator;if(typeof path==="string")path=path.split(keySeparator2);else if(typeof path=="symbol")path=[path];path=[...path];const copy=[...path];const last=copy.pop();if(ref.__children)ref=ref.__children;for(let i=0;ifunctions,objects:()=>objects});function define2(key,registerAsNewKey){const inspectable=this;const target=this.target;if(!this.parent){let value=target[key];if(typeof value==="function"){target[key]=async(...args)=>await this.proxy[key]({[fromInspectable]:true,value},...args)}else{try{Object.defineProperty(target,key,{get:()=>value,set:function(val){value=val;inspectable.proxy[key]={[isProxy]:this[isProxy],[fromInspectable]:true,value:val}},enumerable:true,configurable:true})}catch(e){console.error(`Could not reassign ${key} to a top-level setter...`)}}}if(registerAsNewKey)this.newKeys.add(key);this.create(key,target,void 0,true)}var define_default=define2;var functions=function(){const inspectable=this;return{apply:async function(target,thisArg,argumentsList){try{let foo=target;const isFromInspectable=argumentsList[0]?.[fromInspectable];if(isFromInspectable){foo=argumentsList[0].value;argumentsList=argumentsList.slice(1)}let listeners2=inspectable.listeners.functions;const pathStr=inspectable.path.join(inspectable.options.keySeparator);const toActivate=listeners2?listeners2[pathStr]:void 0;let output,executionInfo={};if(toActivate){executionInfo=functionExecution(thisArg,toActivate,foo,argumentsList);output=executionInfo.output}else{output=foo.apply(thisArg,argumentsList);executionInfo=inspectable?.state?.[pathStr]?.value??{}}const callback=inspectable.options.callback;runCallback(callback,pathStr,executionInfo,output);return output}catch(e){console.warn(`Function failed:`,e,inspectable.path)}}}};var objects=function(){const inspectable=this;return{get(target,prop,receiver){if(prop===isProxy)return true;return Reflect.get(target,prop,receiver)},set(target,prop,newVal,receiver){if(prop===isProxy)return true;const pathStr=[...inspectable.path,prop].join(inspectable.options.keySeparator);const isFromProxy=newVal?.[isProxy];const isFromInspectable=newVal?.[fromInspectable];if(isFromInspectable)newVal=newVal.value;const listeners2=inspectable.listeners.setters;const desc=Object.getOwnPropertyDescriptor(target,prop);const createListener=desc&&!desc.get&&!desc.set;if(createListener){if(typeof inspectable.options.globalCallback==="function"){const id2=inspectable.path[0];define_default.call(inspectable,prop,true);set("setters",pathStr,newVal,inspectable.options.globalCallback,{[id2]:inspectable.root},inspectable.listeners,inspectable.options)}}if(newVal){const newProxy=inspectable.create(prop,target,newVal);if(newProxy)newVal=newProxy}const toActivate=!isFromProxy;if(listeners2&&toActivate&&!inspectable.newKeys.has(prop)){const toActivate2=listeners2[pathStr];if(toActivate2)setterExecution(toActivate2,newVal)}const callback=inspectable.options.callback;const info2=inspectable?.state?.[pathStr]?.value??{};runCallback(callback,pathStr,info2,newVal);if(isFromInspectable||!toActivate)return true;else return Reflect.set(target,prop,newVal,receiver)}}};var canCreate=(parent,key,val)=>{try{if(val===void 0)val=parent[key]}catch(e){return e}const alreadyIs=parent[key]&&parent[key][isProxy];if(alreadyIs)return false;const type=typeof val;const isObject=type==="object";const isFunction=type=="function";const notObjOrFunc=!val||!(isObject||isFunction);if(notObjOrFunc)return false;if(val instanceof Element)return false;if(val instanceof EventTarget)return false;const isESM=isObject&&esm(val);if(isFunction)return true;else{const desc=Object.getOwnPropertyDescriptor(parent,key);if(desc&&(desc.value&&desc.writable||desc.set)){if(!isESM)return true}else if(!parent.hasOwnProperty(key))return true}return false};var Inspectable=class{constructor(target={},opts={},name,parent){this.path=[];this.listeners={};this.newKeys=new Set;this.state={};this.set=(path,info2,update)=>{this.state[path]={output:update,value:info2};setFromPath(path,update,this.proxy,{create:true})};this.check=canCreate;this.create=(key,parent2,val,set2=false)=>{const create=this.check(parent2,key,val);if(val===void 0)val=parent2[key];if(create&&!(create instanceof Error)){parent2[key]=new Inspectable(val,this.options,key,this);return parent2[key]}if(set2){try{this.proxy[key]=val??parent2[key]}catch(e){const isESM=esm(parent2);const path=[...this.path,key];console.error(`Could not set value (${path.join(this.options.keySeparator)})${isESM?" because the parent is an ESM.":""}`,isESM?"":e)}}return};if(!opts.pathFormat)opts.pathFormat="relative";if(!opts.keySeparator)opts.keySeparator=keySeparator;if(target.__proxy)this.proxy=target.__proxy;else if(target[isProxy])this.proxy=target;else{this.target=target;this.options=opts;this.parent=parent;if(this.parent){this.root=this.parent.root;this.path=[...this.parent.path];this.state=this.parent.state??{}}else this.root=target;if(name)this.path.push(name);if(this.options.listeners)this.listeners=this.options.listeners;if(this.options.path){if(this.options.path instanceof Function)this.path=this.options.path(this.path);else if(Array.isArray(this.options.path))this.path=this.options.path;else console.log("Invalid path",this.options.path)}if(this.path)this.path=this.path.filter(str2=>typeof str2==="string");if(!this.options.keySeparator)this.options.keySeparator=keySeparator;let type=this.options.type;if(type!="object")type=typeof target==="function"?"function":"object";const handler2=handlers_exports[`${type}s`].call(this);this.proxy=new Proxy(target,handler2);Object.defineProperty(target,"__proxy",{value:this.proxy,enumerable:false});Object.defineProperty(target,"__esInspectable",{value:this,enumerable:false});for(let key in target)define_default.call(this,key)}return this.proxy}};var setFromOptions=(path,value,baseOptions,opts)=>{const ref=opts.reference;const id2=Array.isArray(path)?path[0]:typeof path==="string"?path.split(baseOptions.keySeparator)[0]:path;let isDynamic=opts.hasOwnProperty("static")?!opts.static:false;if(isDynamic&&!globalThis.Proxy){isDynamic=false;console.warn("Falling back to using function interception and setters...")}if(isDynamic){value=new Inspectable(value,{pathFormat:baseOptions.pathFormat,keySeparator:baseOptions.keySeparator,listeners:opts.listeners,path:path2=>path2.filter(str2=>!baseOptions.fallbacks||!baseOptions.fallbacks.includes(str2))},id2)}let options={keySeparator:baseOptions.keySeparator,...opts};setFromPath(path,value,ref,options);return value};var info=(id2,callback,path,originalValue,base,listeners2,options,refShortcut={})=>{if(typeof path==="string")path=path.split(options.keySeparator);const relativePath=path.join(options.keySeparator);const refs=base;const shortcutRef=refShortcut.ref;const shortcutPath=refShortcut.path;const get3=path2=>{const thisBase=shortcutRef??base;const res=getFromPath(thisBase,path2,{keySeparator:options.keySeparator,fallbacks:options.fallbacks});return res};const set2=(path2,value)=>{const thisBase=shortcutRef??base;setFromOptions(path2,value,options,{reference:thisBase,listeners:listeners2})};let onUpdate=options.onUpdate;let infoToOutput={};if(onUpdate&&typeof onUpdate==="object"&&onUpdate.callback instanceof Function){infoToOutput=onUpdate.info??{};onUpdate=onUpdate.callback}const absolute=[id2,...path];let pathInfo={absolute,relative:relativePath.split(options.keySeparator),parent:absolute.slice(0,-1)};pathInfo.output=pathInfo[options.pathFormat];const completePathInfo=pathInfo;const info2={id:id2,path:completePathInfo,keySeparator:options.keySeparator,infoToOutput,callback:(...args)=>{const output=callback(...args);if(onUpdate instanceof Function)onUpdate(...args);return output},get current(){return get3(shortcutPath??info2.path.absolute)},set current(val){set2(shortcutPath??info2.path.absolute,val)},get parent(){return get3(shortcutPath?shortcutPath?.slice(0,-1):info2.path.parent)},get reference(){return refs[id2]},set reference(val){refs[id2]=val},original:originalValue,history:typeof originalValue==="object"?Object.assign({},originalValue):originalValue,sub:Symbol("subscription"),last:path.slice(-1)[0]};return info2};var registerInLookup=(name,sub,lookups)=>{if(lookups){const id2=Math.random();lookups.symbol[sub]={name,id:id2};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id2]=sub}};var register=(info2,collection,lookups)=>{const absolute=getPath("absolute",info2);if(!collection[absolute])collection[absolute]={};collection[absolute][info2.sub]=info2;registerInLookup(absolute,info2.sub,lookups);return true};var listeners={functions:functions2,setters};var set=(type,absPath,value,callback,base,allListeners,options)=>{const{id:id2,path}=getPathInfo(absPath,options);const fullInfo=info(id2,callback,path,value,base,listeners,options);if(listeners[type])listeners[type](fullInfo,allListeners[type],allListeners.lookup);else{const path2=getPath("absolute",fullInfo);allListeners[type][path2][fullInfo.sub]=fullInfo;if(allListeners.lookup)registerInLookup(path2,fullInfo.sub,allListeners.lookup)}};var get2=(info2,collection)=>collection[getPath("absolute",info2)];var handler=(info2,collection,subscribeCallback,lookups)=>{let success=!!get2(info2,collection);if(!success){let parent=info2.parent;let val=parent?.[info2.last];success=subscribeCallback(val,parent)}return register(info2,collection,lookups)};var setterExecution=(listeners2,value)=>{return iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,{},value)})};function setters(info2,collection,lookups){const thisValue=this;return handler(info2,collection["setters"],(value,parent)=>{let val=value;if(!parent)return;if(!parent[isProxy]){let redefine=true;try{delete parent[info2.last]}catch(e){console.error("Unable to redeclare setters. May already be a dynamic object...");redefine=false}if(redefine){try{Object.defineProperty(parent,info2.last,{get:()=>val,set:async v=>{const isFunction=typeof val==="function";val=v;if(!isFunction){const listeners2=Object.assign({},collection["setters"][getPath("absolute",info2)]);setterExecution(listeners2,v)}else val=getProxyFunction.call(thisValue,info2,collection,val)},enumerable:true,configurable:true})}catch(e){throw e}}}},lookups)}function getProxyFunction(info2,collection,fn){return function(...args){const listeners2=collection["functions"][getPath("absolute",info2)];return functionExecution(this,listeners2,fn??info2.original,args)}}var functionExecution=(context,listeners2,func,args)=>{listeners2=Object.assign({},listeners2);const keys=Object.getOwnPropertySymbols(listeners2);const infoTemplate=listeners2[keys[0]]??{};const executionInfo=get((...args2)=>func.call(context,...args2),args,infoTemplate.infoToOutput);iterateSymbols(listeners2,(_,o)=>{const path=getPath("output",o);runCallback(o.callback,path,executionInfo.value,executionInfo.output)});return executionInfo};function functions2(info2,collection,lookups){return handler(info2,collection["functions"],(_,parent)=>{if(!parent[isProxy]){parent[info2.last]=getProxyFunction.call(this,info2,collection);return setters(info2,collection,lookups)}},lookups)}var drillSimple=(obj,callback,options)=>{let accumulator=options.accumulator;if(!accumulator)accumulator=options.accumulator={};const ignore=options.ignore||[];const path=options.path||[];const condition=options.condition||true;const seen=[];const fromSeen=[];let drill=(obj2,acc={},globalInfo)=>{for(let key in obj2){if(ignore.includes(key))continue;const val=obj2[key];const newPath=[...globalInfo.path,key];const info2={typeof:typeof val,name:val?.constructor?.name,simple:true,object:val&&typeof val==="object",path:newPath};if(info2.object){const name=info2.name;const isESM=esm(val);if(isESM||name==="Object"||name==="Array"){info2.simple=true;const idx=seen.indexOf(val);if(idx!==-1)acc[key]=fromSeen[idx];else{seen.push(val);const pass=condition instanceof Function?condition(key,val,info2):condition;info2.pass=pass;acc[key]=callback(key,val,info2);if(pass){fromSeen.push(acc[key]);acc[key]=drill(val,acc[key],{...globalInfo,path:newPath})}}}else{info2.simple=false;acc[key]=callback(key,val,info2)}}else acc[key]=callback(key,val,info2)}return acc};return drill(obj,accumulator,{path})};var createLookup=()=>{return{symbol:{},name:{}}};var Monitor=class{constructor(opts={}){this.poller=new Poller;this.options={pathFormat:"relative",keySeparator};this.listeners={polling:this.poller.listeners,functions:{},setters:{},lookup:createLookup()};this.references={};this.get=(path,output,reference=this.references,throwError=true)=>{return getFromPath(reference,path,{keySeparator:this.options.keySeparator,fallbacks:this.options.fallbacks,output},throwError)};this.set=(path,value,opts2={})=>{const optsCopy={...opts2};if(!optsCopy.reference)optsCopy.reference=this.references;if(!optsCopy.listeners)optsCopy.listeners=this.listeners;return setFromOptions(path,value,this.options,optsCopy)};this.on=(absPath,callback)=>{const info2=getPathInfo(absPath,this.options);return this.listen(info2.id,callback,info2.path)};this.getInfo=(label,callback,path,original)=>{const info2=info(label,callback,path,original,this.references,this.listeners,this.options);const id2=Math.random();const lookups=this.listeners.lookup;const name=getPath("absolute",info2);lookups.symbol[info2.sub]={name,id:id2};if(!lookups.name[name])lookups.name[name]={};lookups.name[name][id2]=info2.sub;return info2};this.listen=(id2,callback,path=[],__internal={})=>{if(typeof path==="string")path=path.split(this.options.keySeparator);else if(typeof path==="symbol")path=[path];const arrayPath=path;let baseRef=this.get(id2);if(!baseRef){console.error(`Reference does not exist.`,id2);return}if(!__internal.poll)__internal.poll=esm(baseRef);if(!__internal.seen)__internal.seen=[];const __internalComplete=__internal;const thisPath=[id2,...arrayPath];const ref=this.get(thisPath);const toMonitorInternally=(val,allowArrays=false)=>{const first=val&&typeof val==="object";if(!first)return false;const isEl=val instanceof Element;if(isEl)return false;if(allowArrays)return true;else return!Array.isArray(val)};let subs={};const subscribeAll=toMonitorInternally(ref,true);if(subscribeAll){if(ref.__esInspectable)ref.__esInspectable.options.globalCallback=callback;drillSimple(ref,(_,__,drillInfo)=>{if(drillInfo.pass)return;else{const fullPath=[...arrayPath,...drillInfo.path];const internalSubs=this.listen(id2,callback,fullPath,__internalComplete);Object.assign(subs,internalSubs)}},{condition:(_,val)=>toMonitorInternally(val)})}let info2;let success=false;try{info2=this.getInfo(id2,callback,arrayPath,ref);if(info2){if(__internalComplete.poll)success=this.poller.add(info2);else{let type="setters";if(typeof ref==="function")type="functions";success=this.add(type,info2)}}}catch(e){console.error("Fallback to polling:",path,e);success=this.poller.add(info2)}if(success){subs[getPath("absolute",info2)]=info2.sub;if(this.options.onInit instanceof Function){const executionInfo={};for(let key in info2.infoToOutput)executionInfo[key]=void 0;this.options.onInit(getPath("output",info2),executionInfo)}return subs}else{console.error("Failed to subscribe to:",path);return}};this.add=(type,info2)=>{if(listeners_exports[type])return listeners_exports[type](info2,this.listeners,this.listeners.lookup);else{this.listeners[type][getPath("absolute",info2)][info2.sub]=info2;return true}};this.remove=subs=>{if(!subs){subs={...this.listeners.functions,...this.listeners.setters,...this.listeners.polling}}if(typeof subs!=="object")subs={sub:subs};for(let key in subs){let innerSub=subs[key];const handleUnsubscribe=sub=>{const res=this.unsubscribe(sub);if(res===false)console.warn(`Subscription for ${key} does not exist.`,sub)};if(typeof innerSub!=="symbol")iterateSymbols(innerSub,handleUnsubscribe);else handleUnsubscribe(innerSub)}return true};this.unsubscribe=sub=>{const info2=this.listeners.lookup.symbol[sub];const absPath=info2.name;const polling=this.poller.get(sub);const funcs=this.listeners.functions[absPath];const func=funcs?.[sub];const setters2=this.listeners.setters[absPath];const setter=setters2?.[sub];if(polling)this.poller.remove(sub);else if(func){delete funcs[sub];if(!Object.getOwnPropertySymbols(funcs).length){Object.defineProperty(func.parent,func.last,{value:func.original,writable:true});delete this.listeners.functions[absPath]}}else if(setter){delete setters2[sub];if(!Object.getOwnPropertySymbols(setters2).length){const parent=setter.parent;if(parent){const last=setter.last;const value=parent[last];Object.defineProperty(parent,last,{value,writable:true})}delete this.listeners.setters[absPath]}}else return false;delete this.listeners.lookup.symbol[sub];const nameLookup=this.listeners.lookup.name[info2.name];delete nameLookup[info2.id];if(!Object.getOwnPropertyNames(nameLookup).length)delete this.listeners.lookup.name[info2.name]};Object.defineProperty(this.listeners,"lookup",{value:createLookup(),enumerable:false,configurable:false});Object.assign(this.options,opts);this.poller.setOptions(opts.polling)}};var src_default=Monitor;var defaultPath="default";var operatorPath="__operator";var specialKeys={path:"__path",isGraphScript:"__",listeners:{value:"__listeners",branch:"__branch",bind:"__bind",trigger:"__trigger",format:"__format"}};var listenerObject=Symbol("listenerObject");var toSet=Symbol("toSet");var subscriptionKey=Symbol("subscriptionKey");var configKey=Symbol("configKey");var toResolveWithKey=Symbol("toResolveWithKey");var isConfigObject=o=>specialKeys.listeners.format in o||specialKeys.listeners.branch in o||specialKeys.listeners.trigger in o||specialKeys.listeners.bind in o;var initializedStatus="INITIALIZED";var registeredStatus="REGISTERED";var globalFrom={};var globalTo={};var globalActive={};var _triggers,_queue,_toResolveWith,_initialize,_getAbsolutePath,_getPathInfo;var Edgelord=class{constructor(listeners2,root,context){this.original={};this.active={};this.globals={};this.context={options:{}};this.rootPath="";this.status="";__privateAdd(this,_triggers,[]);__privateAdd(this,_queue,[]);__privateAdd(this,_toResolveWith,void 0);this.setInitialProperties=(listeners2={},root,context={})=>{Object.assign(this.context,context);if(root)this.rootPath=root;if(!this.context.options.keySeparator)this.context.options.keySeparator=this.context.monitor.options.keySeparator;this.original=listeners2;const globals=[{name:"active",ref:globalActive},{name:"from",ref:globalFrom},{name:"to",ref:globalTo}];globals.forEach(o=>{if(!o.ref[this.context.id])o.ref[this.context.id]={};this.globals[o.name]=o.ref[this.context.id]});__privateSet(this,_toResolveWith,this.getManager());this.runEachListener(listeners2,this.addToGlobalLog)};this.getManager=(mode="from")=>{let target=mode==="to"?this.globals.to:this.globals.from;this.rootPath.split(this.context.options.keySeparator).forEach(key=>{if(!target[key])target[key]={};target=target[key]});return target[toResolveWithKey]??this};this.onStart=f=>{const res=__privateGet(this,_toResolveWith);const isSame2=res===this;if(isSame2){if(this.status===initializedStatus)f();else __privateGet(this,_queue).push(f)}else res.onStart(f)};this.runEachListener=(listeners2,callback)=>{if(!callback)return;for(const first in listeners2){const second=listeners2[first];if(!second){console.warn("Skipping empty listener:",first);continue}if(second&&typeof second==="object"){const from=second;const to=first;for(let fromPath in from){callback(fromPath,to,from[fromPath])}}else{const from=first;const to=second;const typeOf=typeof to;if(typeOf==="function")callback(from,"",to);else if(typeOf==="string")callback(from,to,to);else console.error("Improperly Formatted Listener",to)}}};this.register=(listeners2=this.original)=>{this.runEachListener(listeners2,this.add);this.status=registeredStatus};__privateAdd(this,_initialize,o=>{const res=this.context.monitor.get(o.path,"info");if(typeof res.value==="function"){const args=Array.isArray(o.args)?o.args:[o.args];res.value(...args)}else console.error("Cannot yet trigger values...",o)});this.initialize=o=>{if(!this.status)__privateGet(this,_triggers).push(o);else if(this.status===registeredStatus){this.status=initializedStatus;__privateGet(this,_triggers).forEach(__privateGet(this,_initialize));__privateGet(this,_queue).forEach(f=>f());__privateSet(this,_queue,[]);__privateSet(this,_triggers,[])}else __privateGet(this,_initialize).call(this,o)};this.start=()=>{this.register();this.initialize()};__privateAdd(this,_getAbsolutePath,name=>{const sep=this.context.monitor.options.keySeparator;return!name||!this.rootPath||this.rootPath===name.slice(0,this.rootPath.length)&&name[this.rootPath.length]===sep?name:[this.rootPath,name].join(sep)});__privateAdd(this,_getPathInfo,path=>{const output={absolute:{},relative:{}};path=__privateGet(this,_getAbsolutePath).call(this,path);let rel=this.rootPath?path.replace(`${this.rootPath}.`,""):path;const baseArr=path.split(this.context.options.keySeparator);output.absolute.array=[this.context.id,...baseArr];output.relative.array=rel.split(this.context.options.keySeparator);let obj=this.context.monitor.get(output.relative.array,void 0,this.context.instance,false);if(this.context.graph){if(obj&&this.context.bound){output.absolute.array=[this.context.id,this.context.bound,...output.absolute.array.slice(1)];output.relative.array.unshift(this.context.bound)}else if(!obj){const rel2=output.relative.array.join(this.context.options.keySeparator);obj=this.context.graph.get(rel2)}}const isGraphScript=obj&&typeof obj==="object"&&specialKeys.isGraphScript in obj;if(isGraphScript){if(obj[operatorPath]){output.absolute.array.push(operatorPath);output.relative.array.push(operatorPath)}else if(obj[defaultPath]){output.absolute.array.push(defaultPath);output.relative.array.push(defaultPath)}}output.absolute.value=output.absolute.array.slice(1).join(this.context.options.keySeparator);output.relative.value=output.relative.array.join(this.context.options.keySeparator);return output});this.add=(from,to,value=true,subscription)=>{if(typeof to=="function"){value=to;to=""}else if(typeof to!=="string"){console.error("Improperly Formatted Listener",from,to,value);return}if(!value)return;const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const absPath=fromInfo.absolute.value;if(!subscription)subscription=this.globals.active[absPath]?.[subscriptionKey];if(!subscription){subscription=this.context.monitor.on(fromInfo.absolute.array,(path,_,update)=>this.activate(path,update),{ref:this.context.instance,path:fromInfo.relative.array})}if(typeof value=="string")value=toInfo.absolute.array.slice(1).join(this.context.options.keySeparator);const info2={value,[listenerObject]:true};const refs=[this.active,this.globals.active];refs.forEach(ref=>{if(!ref[absPath])ref[absPath]={};const base=ref[absPath];if(!base[subscriptionKey]){Object.defineProperty(base,subscriptionKey,{value:subscription,configurable:true})}base[toInfo.absolute.value]=info2});const args=value[specialKeys.listeners.trigger];if(args)__privateGet(this,_toResolveWith).initialize({path:fromInfo.absolute.array,args});this.addToGlobalLog(absPath);return info2};this.addToGlobalLog=(path,mode="from")=>{const absolutePath=__privateGet(this,_getAbsolutePath).call(this,path);let target=mode==="to"?this.globals.to:this.globals.from;const globalPath=absolutePath.split(this.context.options.keySeparator);globalPath.forEach(key=>{if(!target[key])target[key]={};target=target[key];if(!target[toResolveWithKey])target[toResolveWithKey]=this})};this.remove=(from,to)=>{const fromInfo=__privateGet(this,_getPathInfo).call(this,from);const toInfo=__privateGet(this,_getPathInfo).call(this,to);const path=[fromInfo.absolute.value,toInfo.absolute.value];const toRemove=[{ref:this.active,path},{ref:this.globals.active,path,unlisten:true}];toRemove.forEach(o=>{const{ref,path:path2,unlisten}=o;let base=ref[path2[0]];if(typeof base==="object"){delete base[path2[1]];if(Object.keys(base).length===0){delete ref[path2[0]];const sub=base[subscriptionKey];if(unlisten&&sub){this.context.monitor.remove(sub)}delete base[subscriptionKey]}}else delete ref[path2[0]]})};this.clear=name=>{const value=__privateGet(this,_getAbsolutePath).call(this,name);Object.keys(this.active).forEach(from=>{Object.keys(this.active[from]).forEach(to=>{if(!value||from.slice(0,value.length)===value||to.slice(0,value.length)===value)this.remove(from,to)})})};this.has=(from,ref=this.active)=>!!ref[from];this.get=(from,ref=this.active)=>ref[from];this.activate=(from,update)=>{const listenerGroups=[{info:this.get(from,this.globals.active),name:from}];listenerGroups.forEach(group=>{const info2=group.info;if(info2){if(info2[listenerObject]){this.pass(from,{value:info2.value,parent:this.active,key:group.name,subscription:info2.subscription,__value:true},update)}else if(typeof info2==="object"){for(let key in info2){this.pass(from,{parent:info2,key,subscription:info2[key].subscription,value:info2[key].value},update)}}else console.error("Improperly Formatted Listener",info2)}})};this.pass=(from,target,update)=>{const id2=this.context.id;const isValue=target?.__value;let parent=target.parent;let to=target.key;const info2=target.parent[to];target=info2.value;let config=info2?.[configKey];let ogValue=target;const type=typeof target;const checkIfSetter=(path,willSet)=>{const info3=this.context.monitor.get(path,"info");if(info3.exists){const val=info3.value;const noDefault=typeof val!=="function"&&!val?.default;const value=noDefault?toSet:val;const res={value};if(willSet){target=res.value;parent[to]=res}return res}else return{value:void 0}};const transform=willSet=>{const fullPath=[id2];fullPath.push(...to.split(this.context.options.keySeparator));return checkIfSetter(fullPath,willSet)};const getPathArray=latest=>{const path=[id2];const topPath=[];if(this.rootPath)topPath.push(...this.rootPath.split(this.context.options.keySeparator));topPath.push(...latest.split(this.context.options.keySeparator));path.push(...topPath);return path};if(typeof target==="boolean"){if(!isValue)transform(true);else console.error(`Cannot use a boolean for ${specialKeys.listeners.value}...`)}else if(type==="string"){const path=getPathArray(ogValue);checkIfSetter(path,true);if(isValue){parent[to]={[ogValue]:parent[to]};to=ogValue}}else if(target&&type==="object"){const isConfig=isConfigObject(ogValue);if(isConfig){if("value"in ogValue){if(isValue){target=parent[to]=ogValue.value}else{target=parent[to].value=ogValue.value}}else transform(true);if(ogValue){if(ogValue)config=ogValue}Object.defineProperty(parent[to],configKey,{value:config})}}let isValidInput=true;if(config){const bindKey=specialKeys.listeners.value;if(bindKey in config){const path=getPathArray(config[bindKey].original??config[bindKey]);if(typeof config[bindKey]==="string"){const res=this.context.monitor.get(path);if(!res)target=`because ${path.slice(1).join(this.context.options.keySeparator)} does not point correctly to an existing component.`;else{config[bindKey]={value:res,original:config[bindKey]}}}else if(!config[bindKey].value.__parent){target=`because ${config[bindKey].original??id2.toString()} has become unparented.`}}else{const branchKey=specialKeys.listeners.branch;const formatKey=specialKeys.listeners.format;if(branchKey in config){const isValid=config[branchKey].find(o=>{let localValid=[];if("if"in o)localValid.push(o.if(update));if("is"in o)localValid.push(o.is===update);const isValidLocal=localValid.length>0&&localValid.reduce((a,b)=>a&&b,true);if(isValidLocal){if("value"in o)update=o.value}return isValidLocal});if(!isValid)isValidInput=false}if(formatKey in config){try{update=config[formatKey](update);if(update===void 0)isValidInput=false}catch(e){console.error("Failed to format arguments",e)}}}}if(isValidInput&&update!==void 0){const arrayUpdate=Array.isArray(update)?update:[update];if(target===toSet){const parentPath=[id2];parentPath.push(...to.split(this.context.options.keySeparator));const idx=parentPath.pop();const info3=this.context.monitor.get(parentPath,"info");if(info3.value)info3.value[idx]=update;else console.error(`Cannot set value on ${parentPath.filter(str2=>typeof str2!=="symbol").join(this.context.options.keySeparator)} from ${from}`)}else if(target?.default)target.default.call(target,...arrayUpdate);else if(typeof target==="function"){const noContext=parent[to][listenerObject];if(noContext)target.call(config?.[specialKeys.listeners.bind]?.value??this.context.instance,...arrayUpdate);else target(...arrayUpdate)}else{let baseMessage=to?`listener: ${from} \u2014> ${to}`:`listener from ${from}`;if(parent){console.warn(`Deleting ${baseMessage}`,target);delete parent[to]}else console.error(`Failed to add ${baseMessage}`,target)}}};if(listeners2||root||context)this.setInitialProperties(listeners2,root,context)}};_triggers=new WeakMap;_queue=new WeakMap;_toResolveWith=new WeakMap;_initialize=new WeakMap;_getAbsolutePath=new WeakMap;_getPathInfo=new WeakMap;var edgelord_default=Edgelord;function applyLoader(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loader){const args=[node,parent,graph,tree,properties,tag];if(typeof loader==="object"){if(loader.init)loader(...args);if(loader.connected)node.__addOnconnected(loader.connect);if(loader.disconnected)node.__addOndisconnected(loader.disconnect)}else if(typeof loader==="function")loader(...args)}function applyLoaders(node,parent,graph=this,tree=graph.__node.tree,properties,tag=node.__node.tag,loaders2=this.__node.loaders){for(const l in loaders2)applyLoader(node,parent,graph,tree,properties,tag,loaders2[l])}var _parent,_graph,_properties,_options,_applied,_applySetters;var GraphNode=class{constructor(properties,parent,graph,options){this.__=Symbol("graphscript");this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,ref:this,flow:new edgelord_default};__privateAdd(this,_parent,void 0);__privateAdd(this,_graph,void 0);__privateAdd(this,_properties,{});__privateAdd(this,_options,{});__privateAdd(this,_applied,[]);__privateAdd(this,_applySetters,(properties=__privateGet(this,_properties),proxy=__privateGet(this,_properties),ignore=[])=>{const isProxy2=proxy===true;let keys=Object.getOwnPropertyNames(properties);if(isProxy2){proxy=properties;keys=getAllPropertyNames(properties)}for(const key of keys){if(ignore.includes(key))continue;if(__privateGet(this,_applied).includes(key))continue;__privateGet(this,_applied).push(key);if(key==="__properties")Object.defineProperty(this,key,{get:()=>__privateGet(this,_properties),enumerable:true});else if(key==="__props"){Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>{proxy[key]=value;__privateGet(this,_applySetters).call(this,value,true)},enumerable:true,configurable:true})}else{Object.defineProperty(this,key,{get:()=>proxy[key],set:value=>proxy[key]=value,enumerable:true,configurable:false})}}});this.____apply=__privateGet(this,_applySetters);this.__init=(properties,parent=__privateGet(this,_parent),graph=__privateGet(this,_graph),options=__privateGet(this,_options))=>{__privateSet(this,_parent,parent);__privateSet(this,_graph,graph);__privateSet(this,_options,options);if(properties){let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(typeof properties==="object"){if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}properties=properties.__node.tree}__privateSet(this,_properties,properties);if(!properties.__node)properties.__node={};if(!properties.__node.initial)this.__node.initial=orig;if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph)properties.__node.graph=graph;if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;properties.__node=Object.assign(this.__node,properties.__node);const ogProperties=properties;__privateGet(this,_applySetters).call(this);applyLoaders.call(graph,this,parent,graph,graph?.__node?.tree,properties);__privateGet(this,_applySetters).call(this,void 0,void 0,["__props"]);if(properties instanceof Graph)this.__node.source=properties;if(typeof options.onInit==="function")options.onInit();if(graph){const symbol=(graph.__node.ref??this).__;const monitor=graph.monitor;this.__node.flow.setInitialProperties(this.__listeners,void 0,{id:symbol,instance:this,monitor,graph,bound:this.__node.tag})}else console.error("No flow manager created for "+this.__node.tag)}}};this.__init(properties,parent,graph,options)}get __properties(){return __privateGet(this,_properties)}__addOnconnected(callback){if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o.call(this,this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o.call(this,this)})}}};_parent=new WeakMap;_graph=new WeakMap;_properties=new WeakMap;_options=new WeakMap;_applied=new WeakMap;_applySetters=new WeakMap;var _init;var _Graph=class{constructor(options){this.monitor=new src_default({keySeparator:".",fallbacks:["__children"]});this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,ref:new GraphNode,loaders:[props_loader_default]};this.init=options=>{if(options){if(options.loaders){this.setLoaders(options.loaders);delete options.loaders}recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};__privateAdd(this,_init,properties=>{const node=this.__node.ref;node.__init(properties,this,this,{onInit:()=>{this.monitor.set(node.__,node.__properties)}});return node});this.setTree=tree=>{const hasGraphscriptProperties=Object.keys(tree).find(str2=>{const slice=str2.slice(0,2);return slice==="__"&&str2!=="__node"});if(!hasGraphscriptProperties)tree={__children:tree};if(!tree.__node)tree.__node={};this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners2=this.recursiveSet(cpy,this,void 0,tree);if(!tree.__node.tag)tree.__node.tag=this.__node.tag;const node=__privateGet(this,_init).call(this,tree);const children=node.__children;const copy=Object.assign({},children);if(children)listeners2=this.recursiveSet(copy,this,void 0,children);if(node.__listeners)listeners2[node.__node.tag]=node.__listeners;this.__node.nodes.forEach(n=>n.__node.flow.start());node.__callConnected();return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else{if(Array.isArray(this.__node.loaders)){if(Array.isArray(loaders2))this.__node.loaders=[...this.__node.loaders,...loaders2];else this.__node.loaders=[...this.__node.loaders,...Object.values(loaders2)]}else Object.assign(this.__node.loaders,loaders2)}return this.__node.loaders};this.add=(properties,parent)=>{let listeners2={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}node.__callConnected();return node}return};this.recursiveSet=(t,parent,listeners2={},origin=t)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent,this);this.set(node.__node.tag,node);t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners2[node.__node.tag]=node.__listeners}if(node.__children){const children=node.__children;const copy=Object.assign({},children);this.recursiveSet(copy,node,listeners2,children)}let parentNode=parent instanceof _Graph?parent.__node.ref:parent;parentNode.__addOnconnected(()=>node.__callConnected())}}return listeners2};this.remove=node=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];this.clearListeners(node);node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){const node2=t[key].__node.ref;this.clearListeners(node2);this.delete(node2.__node.tag);delete this.__node.tree[node2.__node.tag];this.delete(key);delete this.__node.tree[key];node2.__node.tag=node2.__node.tag.substring(node2.__node.tag.lastIndexOf(".")+1);this.clearListeners(node2);node2.__callDisconnected();if(node2.__children)recursiveRemove(node2.__children)}};if(node.__children)recursiveRemove(node.__children)}if(node?.__node.tag&&node?.__parent){node.__parent=void 0;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.clearListeners=node=>{this.unsubscribe(node);this.clear(node)};this.get=(tag,base)=>{if(base instanceof GraphNode)base=base.__node.tag;if(tag===this.__node.tag)return this.__node.ref;if(base){const relFrom=[base,tag].join(".");const got=this.get(relFrom);if(got)return got}return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(from,to,value=true,bound=this.__node.ref)=>{if(typeof from!=="string")from=from.__node.tag;if(typeof bound==="string")bound=this.get(bound);if(bound)bound.__node.flow.add(from,to,value)};this.unsubscribe=(node,from,to)=>this.clear(from,to,node);this.clear=(from,to,bound)=>{const nd=typeof bound==="string"?this.get(bound):bound;if(typeof from==="symbol")return this.__node.flow.remove(from);let fromString=from instanceof GraphNode?from.__node.tag:from;let toString=to instanceof GraphNode?to.__node.tag:to;const remove=n=>{const flow=n.__node.flow;toString?flow.remove(fromString,toString):flow.clear(fromString)};if(nd)remove(nd);else{remove(this.__node.ref);this.__node.nodes.forEach(remove)}};this.activate=(from,value)=>this.__node.ref.__node.flow.activate(from,value);this.setState=update=>{for(let key in update)this.activate(key,update)};this.init(options)}};var Graph=_Graph;_init=new WeakMap;function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllPropertyNames(obj){var props=[];do{if(obj.constructor.name==="Object")props.push(...Object.keys(obj));else Object.getOwnPropertyNames(obj).forEach(function(prop){if(props.indexOf(prop)===-1)props.push(prop)})}while(obj=Object.getPrototypeOf(obj));return props}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode)graph.subscribe(parent.__node.tag,node.__node.tag)};var loop=(node,parent,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;const delay=(...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})};node.__operator=delay}else if(node.__node.frame===true){let fn=node.__operator;const frame=(...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})};node.__operator=frame}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;const repeat=async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result};node.__operator=repeat}if(node.__node.loop&&typeof node.__node.loop==="number"){let ogFunction=node.__operator;const looper=function(...args){if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){const res=ogFunction.call(node,...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop);return res}};node.__operator=looper;node.__addOnconnected(node2=>{if(node2.__node.looping)node2.__operator()});let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;const animate2=(...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn.call(node,...args);requestAnimationFrame(()=>{node.__operator(...args)})}return true};node.__operator=animate2;node.__addOnconnected(node2=>{if(node2.__node.animating||(!("animating"in node2.__node)||node2.__node.animating)&&node2.__animation)setTimeout(()=>{requestAnimationFrame(node2.__operator)},10)});node.__addOndisconnected(node2=>{if(node2.__node.animating)node2.__node.animating=false})}};var branching=(node,parent,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__operator=node.post}else if(!node.__operator&&typeof node.get=="function"){node.__operator=node.get}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set2=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set2(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str2=classObj.toString();let message={route:"receiveClass",args:[str2,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var ECSService=class extends Service{constructor(options){super(options);this.entities={};this.systems={};this.entityMap=new Map;this.entityKeyMap=new Map;this.order=[];this.animating=false;this.entityCt=0;this.systemCt=0;this.updateEntities=(order=this.order,filter,debug=false)=>{order.forEach(k=>{if(this.systems[k]){if(filter){if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entityMap.get(k));if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entityMap.get(k)).length,"entities")}else{if(debug)debug=performance.now();if(this.entityKeyMap.get(k).length>0)this.systems[k].__operator(this.entities);if(debug)console.log("system",k,"took",performance.now()-debug,"ms for",Object.keys(this.entities).length,"entities")}}})};this.animateEntities=(filter=true,order)=>{if(!this.animating){this.animating=true;if(typeof requestAnimationFrame!=="undefined"){let anim=()=>{requestAnimationFrame(()=>{if(this.animating){this.updateEntities(order,filter);anim()}})};anim()}else{let looper=()=>{setTimeout(async()=>{if(this.animating){this.updateEntities(order,filter);looper()}},10)};looper()}}};this.stop=()=>{this.animating=false};this.start=filter=>{this.animateEntities(filter)};this.addEntities=(prototype,components={},count=1)=>{let i=0;let newEntities={};while(i{if(!prototype)return;const entity=this.recursivelyAssign({},prototype);entity.components=components;if(Object.keys(components).length===0){Object.keys(this.systems).forEach(k=>{components[k]=true})}if(!entity.__node)entity.__node={};if(entity.__node.tag&&this.entities[entity.__node.tag]){this.entityCt++;let tag=entity.__node.tag+this.entityCt;while(this.entities[entity.__node.tag]){this.entityCt++;entity.__node.tag=`${tag}${this.entityCt}`}}else if(!entity.__node.tag)entity.__node.tag=`entity${Math.floor(Math.random()*1e15)}`;this.add(entity);this.entities[entity.__node.tag]=this.__node.nodes.get(entity.__node.tag);this.setupEntity(this.entities[entity.__node.tag]);return this.entities[entity.__node.tag]};this.addSystems=(systems={},order)=>{for(const key in systems){systems[key].__node.tag=key;this.addSystem(systems[key],void 0,void 0,void 0,void 0,order)}return this.systems};this.addSystem=(prototype,setupEntities,setupEntity,operator,remove,order)=>{if(!prototype)return;const system=this.recursivelyAssign({},prototype);if(setupEntities)system.setupEntities=setupEntities;if(setupEntity)system.setupEntity=setupEntity;if(operator)system.__operator=operator;if(remove)system.remove=remove;if(system.__node.tag&&this.systems[system.__node.tag]){this.systemCt++;let tag=system.__node.tag+this.systemCt;while(this.systems[system.__node.tag]){this.systemCt++;system.__node.tag=`${tag}${this.systemCt}`}}else if(!system.__node.tag)system.__node.tag=`system${Math.floor(Math.random()*1e15)}`;this.add(system);this.systems[system.__node.tag]=this.__node.nodes.get(system.__node.tag);if(!this.entityMap.get(system.__node.tag))this.entityMap.set(system.__node.tag,{});if(!this.entityKeyMap.get(system.__node.tag))this.entityKeyMap.set(system.__node.tag,[]);this.systems[system.__node.tag].entities=this.entityMap.get(system.__node.tag);this.systems[system.__node.tag].entityKeys=this.entityKeyMap.get(system.__node.tag);if(this.systems[system.__node.tag]?.setupEntities&&Object.keys(this.entities).length>1){let filtered=this.filterObject(this.entities,(key,v)=>{if(v.components[system.__node.tag])return true});this.systems[system.__node.tag].setupEntities(filtered);Object.assign(this.entityMap.get(system.__node.tag),filtered)}if(!order)this.order.push(system.__node.tag);else this.order=order;return this.systems[system.__node.tag]};this.setupEntity=entity=>{if(entity?.components){for(const key in entity.components){if(this.systems[key]){this.systems[key].setupEntity(entity);this.entityMap.get(key)[entity.__node.tag]=entity;this.entityKeyMap.get(key).push(entity.__node.tag)}}}};this.removeEntity=tag=>{const entity=this.entities[tag];for(const key in entity.components){if(this.entityMap.get(key)){delete this.entityMap.get(key)[entity.__node.tag];this.entityKeyMap.get(key).splice(this.entityKeyMap.get(key).indexOf(entity.__node.tag),1)}if(this.systems[key]?.remove){this.systems[key].remove(entity,this.entityMap.get(key))}}delete this.entities[tag];return this.remove(tag)};this.removeSystem=tag=>{if(this.systems[tag]?.remove){for(const e in this.entityKeyMap.get(tag)){this.systems[tag].remove(this.entityMap.get(tag)[e],this.entityMap.get(tag))}}delete this.systems[tag];this.entityMap.delete(tag);this.entityKeyMap.delete(tag);this.order.splice(this.order.indexOf(tag),1);return this.remove(tag)};this.setEntities=(entities,props)=>{if(Array.isArray(entities)){entities.forEach(k=>{if(this.entities[k])this.recursivelyAssign(this.entities[k],props)})}else{for(const key in this.entities){this.setEntity(this.entities[key],props)}}return true};this.setEntity=(entity,props)=>{return this.recursivelyAssign(entity,props)};this.bufferValues=(entities,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let entkeys=Object.keys(entities);if(keys)buffer=new Float32Array(entkeys.length*keys.length);else{if(typeof entities[entkeys[0]][property]==="object"){keys=Object.keys(entities[entkeys[0]][property]);buffer=new Float32Array(entkeys.length*keys.length)}else buffer=new Float32Array(entkeys.length)}}let i=0;for(const key in entities){if(entities[key][property]){if(keys){for(let j=0;j{this.removeEntity(t)})}filterObject(o,filter){return Object.fromEntries(Object.entries(o).filter(([key,value])=>{filter(key,value)}))}};var import_sjcl=__toESM(require_sjcl());var _HTTPfrontend=class extends Service{constructor(options,path,fetched){super(options);this.name="http";this.fetchProxied=false;this.listening={};this.GET=(url="http://localhost:8080/ping",type="",mimeType)=>{if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"GET",url,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.POST=(message,url="http://localhost:8080/echo",type="",mimeType)=>{if(typeof message==="object"&&(type==="json"||type==="text"||!type)){message=JSON.stringify(message)}if(type==="json")mimeType="application/json";return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method:"POST",url,data:message,responseType:type,mimeType,onload:ev2=>{let data;if(xhr.responseType===""||xhr.responseType==="text")data=xhr.responseText;else data=xhr.response;if(url instanceof URL)url=url.toString();this.setState({[url]:data});resolve(data)},onabort:er=>{reject(er)}})}).catch(console.error)};this.transmit=(message,url)=>{let obj=message;if(typeof obj==="object"){message=JSON.stringify(obj)}if(obj?.method?.toLowerCase()=="get"||message?.toLowerCase()==="get")return this.GET(url);return this.POST(message,url)};this.transponder=(url,message,type="",mimeType)=>{if(typeof message==="object")message=JSON.stringify(message);let method="GET";if(message){method="POST"}if(type==="json")mimeType="application/json";else return new Promise((resolve,reject)=>{let xhr=_HTTPfrontend.request({method,url,data:message,responseType:type,onload:ev2=>{let body=xhr.response;if(typeof body==="string"){let substr=body.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))body=body.replace(/\\/g,"");if(body[0]==='"'){body=body.substring(1,body.length-1)};body=JSON.parse(body)}}if(typeof body?.method==="string"){return resolve(this.handleMethod(body.route,body.method,body.args))}else if(typeof body?.route==="string"){return resolve(this.handleServiceMessage(body))}else if(typeof body?.node==="string"||body.node instanceof GraphNode){return resolve(this.handleGraphNodeCall(body.node,body.args))}else return resolve(body)},onabort:er=>{reject(er)}})}).catch(console.error)};this.listen=(path="0",fetched=async(clone,args,response)=>{const result=await clone.text();const returned=this.receive(result);this.setState({[response.url]:returned})})=>{this.listening[path]={};let listenerId=`${path}${Math.floor(Math.random()*1e15)}`;this.listening[path][listenerId]=fetched;if(!this.fetchProxied){globalThis.fetch=new Proxy(globalThis.fetch,{apply(fetch2,that,args){const result=fetch2.apply(that,args);result.then(response=>{if(!response.ok)return;if(this.listening["0"]){for(const key in this.listeners){const clone=response.clone();this.listening["0"][key](clone,args,response)}}else{for(const key in this.listening){if(response.url.includes(key)){for(const key2 in this.listening[path]){const clone=response.clone();this.listening[path][key2](clone,args,response)}break}}}}).catch(er=>{console.error(er)});return result}});this.fetchProxied=true}return listenerId};this.stopListening=(path,listener)=>{if(!path&&path!==0){for(const key in this.listening)delete this.listening[key]}else{if(!listener)delete this.listening[path];else delete this.listening[listener]}};this.setTree(this);this.listen(path,fetched)}};var HTTPfrontend=_HTTPfrontend;HTTPfrontend.request=options=>{const xhr=new XMLHttpRequest;if(options.responseType)xhr.responseType=options.responseType;else options.responseType="json";if(options.mimeType){xhr.overrideMimeType(options.mimeType)}if(options.onload)xhr.addEventListener("load",options.onload,false);if(options.onprogress)xhr.addEventListener("progress",options.onprogress,false);if(options.onabort)xhr.addEventListener("abort",options.onabort,false);if(options.onloadend)xhr.addEventListener("loadend",options.onloadend,false);if(options.onerror)xhr.addEventListener("error",options.onerror,false);xhr.open(options.method,options.url,true,options.user,options.pass);if(!options.onerror)xhr.onerror=function(){xhr.abort()};xhr.send(options.data);return xhr};var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent?.callback&&parent?.worker))node.parentRoute=parent?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id2)}else worker.postMessage({route:"handleProxyEvent",args:[data,id2]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler2]of entries){element.addEventListener(eventName,function(event){handler2(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id2}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners2=this.__listeners;if(listeners2[type]===void 0){listeners2[type]=[]}if(listeners2[type].indexOf(listener)===-1){listeners2[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners2=this.__listeners;return listeners2[type]!==void 0&&listeners2[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners2=this.__listeners;const listenerArray=listeners2[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id2,addTo=void 0)=>{if(!id2)id2=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id2])proxy=this.targets[id2];else{proxy=new ElementProxyReceiver;this.targets[id2]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id2=>{return this.targets[id2]};this.handleEvent=(data,id2)=>{if(!this.targets[id2])this.makeProxy(id2);if(this.targets[id2]){this.targets[id2].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id2,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id2,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id2,elm)}return id2}function handleProxyEvent(data,id2){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id2))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id2))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id2){let canvasopts;if(this?.__node?.graph){if(_id2)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id2)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText2(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText2(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText2(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText2(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText2(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText2(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText2(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText2(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}}return void 0}function clearCanvas(_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}function initCanvas(_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}function updateCanvas(input,_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id2}return void 0}function setProps(props,_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id2}return void 0}function startAnim(_id2,draw){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText2(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id2}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}function stopAnim(_id2){let canvasopts;if(this?.__node?.graph){if(!_id2)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id2]}else{if(!_id2)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id2]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id2}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var algorithms={};var loadAlgorithms=settings=>{return Object.assign(algorithms,settings)};function createSubprocess(options,inputs){let ctx={_id:options._id?options._id:`algorithm${Math.floor(Math.random()*1e15)}`,ondata:options.ondata,run:data=>{return ctx.ondata(ctx,data)}};if(options.structs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(options.structs)));if(inputs)recursivelyAssign3(ctx,JSON.parse(JSON.stringify(inputs)));if(options.oncreate){ctx.oncreate=options.oncreate}if(ctx.oncreate){ctx.oncreate(ctx)}return ctx}var recursivelyAssign3=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign3(target[key],obj[key]);else target[key]=recursivelyAssign3({},obj[key])}else target[key]=obj[key]}return target};var subprocessRoutes={...unsafeRoutes,loadAlgorithms,"initSubprocesses":async function initSubprocesses(subprocesses,service){if(!service)service=this.__node.graph;if(!service)return void 0;for(const p in subprocesses){let s=subprocesses[p];if(!s.worker&&s.url)s.worker=service.addWorker({url:s.url});if(!s.worker)continue;let w=s.worker;let wpId;wpId=service.establishMessageChannel(w.worker,s.source?.worker);if(!s.source)s.source=service;if(typeof s.subprocess==="object"){const p2=s.subprocess;if(!p2.name)continue;if(typeof p2.oncreate==="function"){p2.oncreate=p2.oncreate.toString()}if(typeof p2.ondata==="function"){p2.ondata=p2.ondata.toString()}s.worker.post("addSubprocessTemplate",[p2.name,p2.structs,p2.oncreate,p2.ondata,p2.props]);s.subprocess=p2.name}if(s.init){let r=await w.run(s.init,s.initArgs);s.otherArgs=r}if(s.otherArgs){w.run("setValue",["otherArgsProxy",Array.isArray(s.otherArgs)?s.otherArgs:[s.otherArgs]])}if(s.pipeTo){w.run("setValue",["routeProxy",s.route]);w.run("setValue",["pipeRoute",s.pipeTo.route]);if(s.url&&!s.pipeTo.worker){let w2=service.addWorker({url:s.url});s.pipeTo.portId=service.establishMessageChannel(w.worker,w2.worker);s.pipeTo.worker=w2}if(s.pipeTo.init){s.pipeTo.otherArgs=await s.pipeTo.worker.run(s.pipeTo.init,s.pipeTo.initArgs)}w.run("setValue",["pipePort",s.pipeTo.portId]);if(s.pipeTo.otherArgs)w.run("setValue",["otherPipeArgs",s.pipeTo.otherArgs]);service.transferFunction(w,function pipeResults(data){let inp=data;if(this.__node.graph.otherArgsProxy)inp=[data,...this.__node.graph.otherArgsProxy];let r=this.__node.graph.run(this.__node.graph.routeProxy,inp);if(!s.blocking)return new Promise(res=>{if(r instanceof Promise){r.then(rr=>{if(rr!==void 0){let args=rr;if(this.__node.graph.otherPipeArgs)args=[rr,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}})}else if(r!==void 0){let args=r;if(this.__node.graph.otherPipeArgs)args=[r,...this.__node.graph.otherPipeArgs];if(this.workers[this.__node.graph.pipePort]){s.blocking=true;this.workers[this.__node.graph.pipePort].run(this.__node.graph.pipeRoute,args).then(result=>{s.blocking=false;res(result)})}}});return void 0},s.route+"_pipeResults");s.route=s.route+"_pipeResults"}else{w.run("setValue",["routeProxy",s.route]);service.transferFunction(w,function routeProxy(data){let r;if(this.__node.graph.otherArgsProxy)r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data,...this.__node.graph.otherArgsProxy);else r=this.__node.graph.nodes.get(this.__node.graph.routeProxy).__operator(data);if(this.__node.graph.state.triggers[this.__node.graph.routeProxy]){if(r instanceof Promise){r.then(rr=>{this.setState({[this.__node.graph.routeProxy]:rr})})}else this.setState({[this.__node.graph.routeProxy]:r})}return r},s.route+"_routeProxy");s.route=s.route+"_routeProxy";if(!s.stopped)w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route]).then(sub=>{s.sub=sub})}s.stop=async()=>{if(s.source&&typeof s.sub==="number"){s.source.unsubscribe(s.subscribeRoute,s.sub);return true}return void 0};s.start=async()=>{if(typeof s.sub!=="number")return w.run("subscribeToWorker",[s.subscribeRoute,wpId,s.route,s.blocking]).then(sub=>{s.sub=sub})};s.setArgs=async args=>{if(Array.isArray(args))await w.run("setValue",["otherArgsProxy",args]);else if(typeof args==="object"){for(const key in args){await w.run("setValue",[key,args[key]])}}return true};s.terminate=()=>{w.terminate();if(s.source?.worker&&typeof s.sub==="number"){s.source.post("unsubscribe",s.sub)}if(s.pipeTo?.worker){s.pipeTo.worker.terminate()}};if(s.callback)w.subscribe(s.route,res=>{if(typeof s.callback==="string")this.__node.graph.run(s.callback,res);else s.callback(res)})}return subprocesses},"addSubprocessTemplate":function subprocesstempalte(name,structs,oncreate,ondata,props){if(typeof oncreate==="string")oncreate=parseFunctionFromText(oncreate);if(typeof ondata==="string")ondata=parseFunctionFromText(ondata);if(typeof ondata==="function"){algorithms[name]={ondata,oncreate:typeof oncreate==="function"?oncreate:null,structs};if(typeof props==="object")Object.assign(algorithms[name],props);return true}},"updateSubprocess":function updatesubprocess(structs,_id2){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id2)_id2=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id2)return;Object.assign(this.__node.graph.ALGORITHMS[_id2],structs)},"createSubprocess":function creatsubprocess(options,inputs){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(typeof options==="string"){options=algorithms[options]}if(typeof options==="object"){if(typeof options.ondata==="string")options.ondata=parseFunctionFromText(options.ondata);let ctx;if(typeof options?.ondata==="function")ctx=createSubprocess(options,inputs);if(ctx)this.__node.graph.ALGORITHMS[ctx._id]=ctx;console.log(ctx,options);if(ctx)return ctx._id}return false},"runSubprocess":function runsubprocess(data,_id2){if(!this.__node.graph.ALGORITHMS)this.__node.graph.ALGORITHMS={};if(!_id2)_id2=Object.keys(this.__node.graph.ALGORITHMS)[0];if(!_id2)return;let res=this.__node.graph.ALGORITHMS[_id2].run(data);if(res!==void 0){if(Array.isArray(res)){let pass=[];res.forEach(r=>{if(r!==void 0){pass.push(r);this.__node.graph.setState({[_id2]:r})}});if(pass.length>0){return pass}}else{this.__node.graph.setState({[_id2]:res});return res}}}};var import_bson_objectid=__toESM(require_objectid());var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp2={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp2);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u=(dot11*dot02-dot01*dot12)*_denom;let v=(dot00*dot12-dot01*dot02)*_denom;if(u>=0&&v>=0&&u+v<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v=>{let magnitude=0;for(const key in v){magnitude+=v[key]*v[key]}return Math.sqrt(magnitude)},normalize:v=>{let magnitude=Systems.collision.magnitude(v);let _mag=magnitude?1/magnitude:0;let vn=Object.assign({},v);for(const key in v){vn[key]=v[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now2=performance.now();let timeStep=now2-this.lastTime;this.lastTime=now2;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var __defProp3=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp3(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField2=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y2)=>{return v+x2+y2}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y2)=>{return[x2*10,y2*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize2=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y2=0;y2{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField2(Math2,"TWO_PI",Math.PI*2);__publicField2(Math2,"C",299792458);__publicField2(Math2,"G",66743e-15);__publicField2(Math2,"h",662607015e-42);__publicField2(Math2,"R",8314.32);__publicField2(Math2,"Ra",287);__publicField2(Math2,"H",69.3);__publicField2(Math2,"kbar",1054571817e-43);__publicField2(Math2,"kB",1380649e-29);__publicField2(Math2,"ke",89875517923e-1);__publicField2(Math2,"me",91093837015e-41);__publicField2(Math2,"mp",167262192369e-38);__publicField2(Math2,"mn",167492749804e-38);__publicField2(Math2,"P0",101325);__publicField2(Math2,"T0",288.15);__publicField2(Math2,"p0",1.225);__publicField2(Math2,"Na",60220978e16);__publicField2(Math2,"y",1.405);__publicField2(Math2,"M0",28.96643);__publicField2(Math2,"g0",9.80665);__publicField2(Math2,"Re",6378100);__publicField2(Math2,"B",1458e-9);__publicField2(Math2,"S",110.4);__publicField2(Math2,"Sigma",365e-12);__publicField2(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField2(Math2,"integral",(func=x2=>{let y2=x2;return y2},range=[],stepx=.01)=>{let area2=0;for(let i=range[0];i{let z=x2+y2;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y2+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x2;return y2},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y2=0;y2{function lerp2(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp2(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField2(Math2,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;ikey in obj?__defProp4(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField3=(obj,key,value)=>{__defNormalProp2(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math22=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y2)=>{return v+x2+y2}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math22.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y2)=>{return[x2*10,y2*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize2=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math22.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y2=0;y2{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math22.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy2*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y2=>2*((y2-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math22=_Math22;__publicField3(Math22,"TWO_PI",Math.PI*2);__publicField3(Math22,"C",299792458);__publicField3(Math22,"G",66743e-15);__publicField3(Math22,"h",662607015e-42);__publicField3(Math22,"R",8314.32);__publicField3(Math22,"Ra",287);__publicField3(Math22,"H",69.3);__publicField3(Math22,"kbar",1054571817e-43);__publicField3(Math22,"kB",1380649e-29);__publicField3(Math22,"ke",89875517923e-1);__publicField3(Math22,"me",91093837015e-41);__publicField3(Math22,"mp",167262192369e-38);__publicField3(Math22,"mn",167492749804e-38);__publicField3(Math22,"P0",101325);__publicField3(Math22,"T0",288.15);__publicField3(Math22,"p0",1.225);__publicField3(Math22,"Na",60220978e16);__publicField3(Math22,"y",1.405);__publicField3(Math22,"M0",28.96643);__publicField3(Math22,"g0",9.80665);__publicField3(Math22,"Re",6378100);__publicField3(Math22,"B",1458e-9);__publicField3(Math22,"S",110.4);__publicField3(Math22,"Sigma",365e-12);__publicField3(Math22,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField3(Math22,"integral",(func=x2=>{let y2=x2;return y2},range=[],stepx=.01)=>{let area2=0;for(let i=range[0];i{let z=x2+y2;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y2+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y2=x2;return y2},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y2=0;y2{function lerp2(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp2(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField3(Math22,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{if(!("ax"in data)&&!("gx"in data))return void 0;if(!data.timestamp){if(data.ax&&Array.isArray(data.ax)||data.gx&&Array.isArray(data.gx)){let len=data.ax?data.ax.length:data.gx.length;let now2=Date.now();let toInterp=[now2-len*ctx.sps*1e3,now2];data.timestamp=Math22.upsample(toInterp,len)}else{data.timestamp=Date.now()}}let result;if(data.ax){let apass=(timestamp,ax,ay,az)=>{ax=ax*ctx.accelConstant;ay=ay*ctx.accelConstant;az=az*ctx.accelConstant;const accelXAngle=Math.atan(ay/Math.sqrt(ax*ax)+az*az*180/Math.PI)+ctx.accelXError;const accelYAngle=Math.atan(-ax/Math.sqrt(ay*ay)+az*az*180/Math.PI)+ctx.accelYError;return{ax,ay,az,roll:accelXAngle,pitch:accelYAngle}};if(Array.isArray(data.timestamp)){result=data.timestamp.map((v,i)=>{return apass(v,data.ax[i],data.ay[i],data.az[i])})}else result=apass(data.timestamp,data.ax,data.ay,data.az)}if(data.gx){let gpass=(timestamp,gx,gy,gz)=>{const elapsed=timestamp-ctx.lastGyroTime;ctx.lastGyroTime=timestamp;gx=gx*ctx.gyroConstant+ctx.gyroXError;gy=gy*ctx.gyroConstant+ctx.gyroYError;gz=gz*ctx.gyroConstant+ctx.gyroZError;ctx.gyroXAngle+=gx*elapsed;ctx.gyroYAngle+=gy*elapsed;ctx.gyroZAngle+=gz*elapsed;return{gx,gy,gz,roll:ctx.gyroXAngle,pitch:ctx.gyroYAngle,yaw:ctx.gyroZAngle}};let res;if(Array.isArray(data.timestamp)){res=data.timestamp.map((v,i)=>{if(result){let r=gpass(v,data.gx[i],data.gy[i],data.gz[i]);result.roll=result.roll*.04+r.roll*.96;result.pitch=result.pitch*.04+r.pitch*.96;result.yaw=res.yaw}else return gpass(v,data.gx[i],data.gy[i],data.gz[i])});if(!result)result=res}else{res=gpass(data.timestamp,data.gx,data.gy,data.gz);if(result){result.roll=result.roll*.04+res.roll*.96;result.pitch=result.pitch*.04+res.pitch*.96;result.yaw=res.yaw}else result=res}}else if(ctx.gyroXAngle||ctx.gyroYAngle||ctx.gyroZAngle){result.roll=result.roll*.04+ctx.gyroXAngle*.96;result.pitch=result.pitch*.04+ctx.gyroYAngle*.96;result.yaw=ctx.gyroXAngle}if(result.ax){const setPositionOffset=(timestamp,result2)=>{const elapsed=timestamp-ctx.lastAccelTime;ctx.lastAccelTime=timestamp;ctx.px+=result2.ax*elapsed*elapsed*Math.cos(ctx.pitch*Math.PI*.005555555555);ctx.py+=result2.ay*elapsed*elapsed*Math.cos(ctx.roll*Math.PI*.005555555555);ctx.pz+=result2.az*elapsed*elapsed*Math.sin(ctx.pitch*Math.PI*.005555555555);result2.px=ctx.px;result2.py=ctx.py;result2.pz=ctx.pz;return result2};if(Array.isArray(data.timestamp)){data.timestamp.map((timestamp,i)=>{setPositionOffset(timestamp,result)})}else{setPositionOffset(data.timestamp,result)}}return result}};var Biquad=class{constructor(type,freq,sps,Q=1/Math.sqrt(2),dbGain=0){this.a0=0;this.a1=0;this.a2=0;this.b0=0;this.b1=0;this.b2=0;this.x1=0;this.x2=0;this.y1=0;this.y2=0;let types=["lowpass","highpass","bandpass","notch","peak","lowshelf","highshelf"];if(types.indexOf(type)<0){console.error("Valid types: 'lowpass','highpass','bandpass','notch','peak','lowshelf','highshelf'");return}this.type=type;this.freq=freq;this.sps=sps;this.Q=Q;this.dbGain=dbGain;let A=Math.pow(10,dbGain/40);let omega=2*Math.PI*freq/sps;let sn=Math.sin(omega);let cs=Math.cos(omega);let alpha=sn/(2*Q);let beta=Math.sqrt(A+A);this[type](A,sn,cs,alpha,beta);this.b0/=this.a0;this.b1/=this.a0;this.b2/=this.a0;this.a1/=this.a0;this.a2/=this.a0}lowpass(A,sn,cs,alpha,beta){this.b0=(1-cs)*.5;this.b1=1-cs;this.b2=(1-cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}highpass(A,sn,cs,alpha,beta){this.b0=(1+cs)*.5;this.b1=-(1+cs);this.b2=(1+cs)*.5;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}bandpass(A,sn,cs,alpha,beta){this.b0=alpha;this.b1=0;this.b2=-alpha;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}notch(A,sn,cs,alpha,beta){this.b0=1;this.b1=-2*cs;this.b2=1;this.a0=1+alpha;this.a1=-2*cs;this.a2=1-alpha}peak(A,sn,cs,alpha,beta){this.b0=1+alpha*A;this.b1=-2*cs;this.b2=1-alpha*A;this.a0=1+alpha/A;this.a1=-2*cs;this.a2=1-alpha/A}lowshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1-(A-1)*cs+beta*sn);this.b1=2*A*(A-1-(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1+(A+1)*cs+beta*sn;this.a1=2*(A-1+(A+1)*cs);this.a2=A+1+(A-1)*cs-beta*sn}highshelf(A,sn,cs,alpha,beta){this.b0=A*(A+1+(A-1)*cs+beta*sn);this.b1=2*A*(A-1+(A+1)*cs);this.b2=A*(A+1-(A-1)*cs-beta*sn);this.a0=A+1-(A+1)*cs-beta*sn;this.a1=2*(A-1-(A+1)*cs);this.a2=A+1-(A-1)*cs-beta*sn}applyFilter(signal_step){let y2=this.b0*signal_step+this.b1*this.x1+this.b2*this.x2-this.a1*this.y1-this.a2*this.y2;this.x2=this.x1;this.x1=signal_step;this.y2=this.y1;this.y1=y2;return y2}zResult(freq){try{let phi=Math.pow(Math.sin(Math.PI*freq*2/(2*this.sps)),2);let result=(Math.pow(this.b0+this.b1+this.b2,2)-4*(this.b0*this.b1+4*this.b0*this.b2+this.b1*this.b2)*phi+16*this.b0*this.b2*phi*phi)/(Math.pow(1+this.a1+this.a2,2)-4*(this.a1+4*this.a2+this.a1*this.a2)*phi+16*this.a2*phi*phi);return result}catch(err){return-200}}static calcCenterFrequency(freqStart,freqEnd){return(freqStart+freqEnd)/2}static calcBandwidth(freqStart,freqEnd){return freqEnd-this.calcCenterFrequency(freqStart,freqEnd)}static calcBandpassQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*Math.sqrt((frequency-bandwidth)*(frequency+bandwidth))/(2*bandwidth);return Q}static calcNotchQ(frequency,bandwidth,resonance=Math.pow(10,Math.floor(Math.log10(frequency)))){let Q=resonance*frequency*bandwidth/Math.sqrt((frequency-bandwidth)*(frequency+bandwidth));return Q}};var beat_detect={structs:{refdata:[],lowpass:void 0,smoothed:[],timestamp:[],peaks:[],valleys:[],peak_distances:[],valley_distances:[],beats:[],lastPeak:0,lastValley:0,sps:100,maxFreq:4,limit:10},oncreate:context=>{if(!context.lowpass){let freq=context.maxFreq;if(!freq)freq=1;if(freq>1)freq*=.5;context.lowpass=new Biquad("lowpass",context.maxFreq,context.sps);context.peakFinderWindow=Math.floor(context.sps/context.maxFreq);if(context.peakFinderWindow%2===0)context.peakFinderWindow+=1;if(context.peakFinderWindow<5)context.peakFinderWindow=5;context.midpoint=Math.round(context.peakFinderWindow*.5)}},ondata:(context,data)=>{if(!("red"in data)&&!("heg"in data)&&!("raw"in data))return void 0;let refdata=data.red?data.red:data.heg?data.heg:data.raw;if(!("timestamp"in data)){if(Array.isArray(refdata)){let now2=Date.now();let len;if(refdata)len=refdata.length;let toInterp=[now2-refdata.length*context.sps*1e3,now2];data.timestamp=Math22.upsample(toInterp,refdata.length)}else{data.timestamp=Date.now()}}let pass=(amplitude,timestamp)=>{if(amplitude){context.refdata.push(amplitude)}context.timestamp.push(timestamp);let beat;if(context.refdata.length>context.peakFinderWindow){context.refdata.shift();context.timestamp.shift()}context.smoothed.push(context.lowpass.applyFilter(context.refdata[context.refdata.length-1]));if(context.smoothed.length>context.peakFinderWindow){context.smoothed.shift()}if(context.smoothed.length===context.peakFinderWindow){if(Math22.isExtrema(context.smoothed,"valley")){context.valleys.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}else if(Math22.isExtrema(context.smoothed,"peak")){context.peaks.push({value:context.smoothed[context.smoothed.length-context.midpoint?context.midpoint:1],timestamp:context.timestamp[context.timestamp.length-context.midpoint?context.midpoint:1]})}if(context.valleys.length>2&&context.peaks.length>2){if(context.valleys[context.valleys.length-1].timestamp1&&context.valley_distances.length>1){if(context.lastPeakcontext.peak_distances[context.peak_distances.length-1].timestamp){let bpm,change=0;if(context.beats.length<1){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].distance+context.valley_distances[context.valley_distances.length-1].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-1].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-1].dt+context.valley_distances[context.valley_distances.length-1].dt));change=Math.abs(bpm-context.beats[context.beats.length-1].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-1].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-1].peak0-context.valley_distances[context.valley_distances.length-1].peak0,height1:context.peak_distances[context.peak_distances.length-1].peak1-context.valley_distances[context.valley_distances.length-1].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}else{let bpm,change=0;if(context.beats.length<2){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance))}else if(context.beats[context.beats.length-1].timestamp!==context.peak_distances[context.peak_distances.length-2].timestamp){bpm=60/(5e-4*(context.peak_distances[context.peak_distances.length-2].distance+context.valley_distances[context.valley_distances.length-2].distance));change=Math.abs(bpm-context.beats[context.beats.length-2].bpm)}beat={timestamp:context.peak_distances[context.peak_distances.length-2].timestamp,change,bpm,height0:context.peak_distances[context.peak_distances.length-2].peak0-context.valley_distances[context.valley_distances.length-2].peak0,height1:context.peak_distances[context.peak_distances.length-2].peak1-context.valley_distances[context.valley_distances.length-2].peak1};context.beats.push(beat);context.lastPeak=context.peaks[context.peaks.length-1].timestamp;context.lastValley=context.peaks[context.peaks.length-1].timestamp}}}if(context.peaks.length>context.limit){context.peaks.shift()}if(context.valleys.length>context.limit){context.valleys.shift()}if(context.peak_distances.length>context.limit){context.peak_distances.shift()}if(context.valley_distances.length>context.limit){context.valley_distances.shift()}if(context.beats.length>context.limit){context.beats.shift()}}}return beat};if(data.red){if("ir"in data&&!Array.isArray(data.red))return pass(data.red+data.ir,data.timestamp);let result;if(data.ir)data.red.map((v,i)=>{return pass(v+data.ir[i],data.timestamp[i])});else data.red.map((v,i)=>{return pass(v,data.timestamp[i])});return result}else if(data.raw){if(!Array.isArray(data.raw))return pass(data.raw,data.timestamp);let result=data.raw.map((v,i)=>{return pass(v,data.timestamp[i])});return result}else if(Array.isArray(data.heg)){if(!Array.isArray(data.heg))return pass(data.heg,data.timestamp);let result=data.heg.map((v,i)=>{return pass(v,data.timestamp[i])});return result}}};var blink_detect={structs:{sps:250,intervals:{},watch:["0"],tolerance:.2},oncreate:ctx=>{ctx.watch.forEach(ch=>ctx.intervals[ch]={lowpass:new Biquad("lowpass",20,ctx.sps),filtered:[],averaged:[]})},ondata:(ctx,data)=>{let checkCt=5;let averageCt=50;let found={};let passed=false;let pass=(key,n)=>{let next=ctx.intervals[key].lowpass.applyFilter(n);ctx.intervals[key].filtered.push(next);ctx.intervals[key].averaged.push(next);if(ctx.intervals[key].filtered.length>checkCt){if(ctx.intervals[key].averaged.length>averageCt){ctx.intervals[key].averaged.splice(0,checkCt);let mean=Math22.mean(ctx.intervals[key].averaged);if(Math.abs(Math.min(...ctx.intervals[key].filtered))>Math.abs(mean)+ctx.tolerance){ctx.intervals[key].filtered.length=0;passed=true;found[key]=true}}else ctx.intervals[key].filtered.shift()}};for(const key in ctx.intervals){if(data[key]){if(Array.isArray(data[key])){data[key].forEach(n=>{pass(key,n)})}else if(typeof data[key]==="number")pass(key,data[key])}}if(passed)return found}};var _ArrayManip=class{constructor(){this.recursivelyAssign=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"){if(typeof target[key]==="object")this.recursivelyAssign(target[key],obj[key]);else target[key]=this.recursivelyAssign({},obj[key])}else target[key]=obj[key]}return target}}static autoscale(array,lineIdx=0,nLines=1,centerZero=false,ymin,ymax,clamp2){if(array?.length===0)return array;let max=ymax?ymax:Math.max(...array);let min=ymin?ymin:Math.min(...array);let _lines=1/nLines;let scalar=1;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));if(absmax!==0)scalar=_lines/absmax;return array.map(y2=>{if(clamp2){if(y2max)y2=max}return y2*scalar+(_lines*(lineIdx+1)*2-1-_lines)})}else{if(max===min){if(max!==0){scalar=_lines/max}else if(min!==0){scalar=_lines/Math.abs(min)}}else scalar=_lines/(max-min);return array.map(y2=>{if(clamp2){if(y2max)y2=max}return 2*((y2-min)*scalar-1/(2*nLines))+(_lines*(lineIdx+1)*2-1-_lines)})}}static genTimestamps(ct,sps){let now2=Date.now();let toInterp=[now2-ct*1e3/sps,now2];return _ArrayManip.upsample(toInterp,ct)}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;jfitCount){return _ArrayManip.downsample(array,fitCount,scalar)}else if(array.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}return arr}static reformatData(data,key){if(Array.isArray(data)){if(Array.isArray(data[0])){let d={};data.forEach((arr,i)=>{d[i]=arr});data=d;if(isNaN(data[0][0]))return void 0}else if(key){data={[key]:data};if(isNaN(data[key][0]))return void 0}else{data={0:data};if(isNaN(data[0][0]))return void 0}}else if(typeof data==="object"){for(const key2 in data){if(typeof data[key2]==="number")data[key2]=[data[key2]];else if(data[key2]?.values){if(typeof data[key2].values==="number")data[key2].values=[data[key2].values]}if(isNaN(data[key2][0]))return void 0}}else if(typeof data==="string"){let split;if(data.includes("\r\n")){let lines=data.split("\r\n");data={};lines.forEach((l,j)=>{if(l.includes(" ")){split=l.split(" ")}else if(l.includes(",")){split=l.split(",")}else if(l.includes("|")){split=l.split("|")}if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}})}else if(data.includes(" ")){split=data.split(" ")}else if(data.includes(",")){split=data.split(",")}else if(data.includes("|")){split=data.split("|")}data={};if(Array.isArray(split)){split.forEach((val,i)=>{if(val.includes(":")){let[key2,v]=val.split(":");let fl=parseFloat(v);if(fl)data[key2]=[fl];else return void 0}else{let fl=parseFloat(val);if(fl)data[i]=[fl];else return void 0}})}}else if(typeof data==="number"){if(key)data={[key]:[data]};else data={0:[data]}}return data}static padTime(data,lastValue,time,targetFit){let slopeIncr=(data[0]-lastValue)/time/targetFit;let padded=[...new Array(targetFit-data.length).map((_,i)=>lastValue+slopeIncr*(i+1)),...data];return padded}static interpolateForTime(data,time,targetSPS){return _ArrayManip.interpolate(data,Math.ceil(targetSPS*time))}isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let n;if(s.length>0||e?.length>0)n=new arr.constructor(s.length+e.length);if(s.length>0)n.set(s);if(e&&e.length>0)n.set(e,s.length);return n}};var ArrayManip=_ArrayManip;ArrayManip.bufferValues=(objects2,property,keys,buffer)=>{if(!Array.isArray(keys)&&typeof keys==="object")keys=Object.keys(keys);if(!buffer){let object_keys=Object.keys(objects2);if(keys)buffer=new Float32Array(object_keys.length*keys.length);else{if(typeof objects2[object_keys[0]][property]==="object"){keys=Object.keys(objects2[object_keys[0]][property]);buffer=new Float32Array(object_keys.length*keys.length)}else buffer=new Float32Array(object_keys.length)}}let i=0;for(const key in objects2){if(objects2[key][property]){if(keys){for(let j=0;j])?(([1-9]\d*)?([xcbB?hHiIfdsp]))*$/;var refmt=/([1-9]\d*)?([xcbB?hHiIfdsp])/g;var str=(v,o,c)=>String.fromCharCode(...new Uint8Array(v.buffer,v.byteOffset+o,c));var rts=(v,o,c,s)=>new Uint8Array(v.buffer,v.byteOffset+o,c).set(s.split("").map(str2=>str2.charCodeAt(0)));var pst=(v,o,c)=>str(v,o+1,Math.min(v.getUint8(o),c-1));var tsp=(v,o,c,s)=>{v.setUint8(o,s.length);rts(v,o+1,c-1,s)};var lut=le=>({x:c=>[1,c,0],c:c=>[c,1,o=>({u:v=>str(v,o,1),p:(v,c2)=>rts(v,o,1,c2)})],"?":c=>[c,1,o=>({u:v=>Boolean(v.getUint8(o)),p:(v,B)=>v.setUint8(o,B)})],b:c=>[c,1,o=>({u:v=>v.getInt8(o),p:(v,b)=>v.setInt8(o,b)})],B:c=>[c,1,o=>({u:v=>v.getUint8(o),p:(v,B)=>v.setUint8(o,B)})],h:c=>[c,2,o=>({u:v=>v.getInt16(o,le),p:(v,h)=>v.setInt16(o,h,le)})],H:c=>[c,2,o=>({u:v=>v.getUint16(o,le),p:(v,H)=>v.setUint16(o,H,le)})],i:c=>[c,4,o=>({u:v=>v.getInt32(o,le),p:(v,i)=>v.setInt32(o,i,le)})],I:c=>[c,4,o=>({u:v=>v.getUint32(o,le),p:(v,I)=>v.setUint32(o,I,le)})],f:c=>[c,4,o=>({u:v=>v.getFloat32(o,le),p:(v,f)=>v.setFloat32(o,f,le)})],d:c=>[c,8,o=>({u:v=>v.getFloat64(o,le),p:(v,d)=>v.setFloat64(o,d,le)})],s:c=>[1,c,o=>({u:v=>str(v,o,c),p:(v,s)=>rts(v,o,c,s.slice(0,c))})],p:c=>[1,c,o=>({u:v=>pst(v,o,c),p:(v,s)=>tsp(v,o,c,s.slice(0,c-1))})]});var errbuf=new RangeError("Structure larger than remaining buffer");var errval=new RangeError("Not enough values for structure");var _ByteParser=class extends ArrayManip{static toDataView(value){if(!(value instanceof DataView)){if(typeof value==="string"&&parseInt(value))value=parseInt(value);if(typeof value==="string"){let enc=new TextEncoder;let hascodes={};for(const code in _ByteParser.codes){while(value.indexOf(code)>-1){let idx=value.indexOf(code);value=value.replace(code,"");hascodes[idx]=code}}let encoded=Array.from(enc.encode(value));for(const key in hascodes){encoded.splice(parseInt(key),0,_ByteParser.codes[hascodes[key]])}value=new DataView(new Uint8Array(encoded).buffer)}else if(typeof value==="number"){let tmp2=value;if(value<256){value=new DataView(new ArrayBuffer(1));value.setUint8(0,tmp2)}else if(value<65536){value=new DataView(new ArrayBuffer(2));value.setInt16(0,tmp2)}else{value=new DataView(new ArrayBuffer(4));value.setUint32(0,tmp2)}}else if(value instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&value instanceof SharedArrayBuffer){value=new DataView(value)}else if(Array.isArray(value)){value=new DataView(Uint8Array.from(value).buffer)}else if(typeof value==="object"){value=new TextEncoder().encode(JSON.stringify(value))}}return value}static searchBuffer(buffer,searchString,limit){var needle=searchString;var haystack=buffer;var search=_ByteParser.boyerMoore(needle);var skip=search.byteLength;var indices=[];for(var i=search(haystack);i!==-1;i=search(haystack,i+skip)){indices.push(i);if(limit){if(indices.length>=limit)break}}return indices}static bytesToInt16(x0,x1){let int16=(255&x0)<<8|255&x1;if((int16&32768)>0){int16|=4294901760}else{int16&=65535}return int16}static bytesToUInt16(x0,x1){return x0*256+x1}static Uint16ToBytes(y2){return[y2&255,y2>>8&255]}static bytesToInt24(x0,x1,x2){let int24=(255&x0)<<16|(255&x1)<<8|255&x2;if((int24&8388608)>0){int24|=4278190080}else{int24&=16777215}return int24}static bytesToUInt24(x0,x1,x2){return x0*65536+x1*256+x2}static Uint24ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255]}static bytesToInt32(x0,x1,x2,x3){let int32=(255&x0)<<24|(255&x1)<<16|(255&x2)<<8|255&x3;if((int32&2147483648)>0){int32|=0}else{int32&=4294967295}return int32}static bytesToUInt32(x0,x1,x2,x3){return x0*16777216+x1*65536+x2*256+x3}static Uint32ToBytes(y2){return[y2&255,y2>>8&255,y2>>16&255,y2>>24&255]}static get2sCompliment(val,nbits){if(val>4294967296)return null;return val<<32-nbits>>32-nbits}static getSignedInt(...args){let pos=0;function getInt(size){var value=0;var first=true;while(size--){if(first){let byte=args[pos++];value+=byte&127;if(byte&128){value-=128}first=false}else{value*=256;value+=args[pos++]}}return value}return getInt(args.length)}static asUint8Array(input){if(input instanceof Uint8Array){return input}else if(typeof input==="string"){var arr=new Uint8Array(input.length);for(var i=0;i127){throw new TypeError("Only ASCII patterns are supported")}arr[i]=c}return arr}else{return new Uint8Array(input)}}static boyerMoore(patternBuffer){var pattern=_ByteParser.asUint8Array(patternBuffer);var M=pattern.length;if(M===0){throw new TypeError("patternBuffer must be at least 1 byte long")}var R=256;var rightmost_positions=new Int32Array(R);for(var c=0;c{var txt=_ByteParser.asUint8Array(txtBuffer);if(start===void 0)start=0;if(end===void 0)end=txt.length;var pat=pattern;var right=rightmost_positions;var lastIndex=end-pat.length;var lastPatIndex=pat.length-1;var skip;for(var i=start;i<=lastIndex;i+=skip){skip=0;for(var j2=lastPatIndex;j2>=0;j2--){var c2=txt[i+j2];if(pat[j2]!==c2){skip=Math.max(1,j2-right[c2]);break}}if(skip===0){return i}}return-1};boyerMooreSearch.byteLength=pattern.byteLength;return boyerMooreSearch}static struct(format){let fns=[],size=0,m=rechk.exec(format);if(!m){throw new RangeError("Invalid format string")}const t=lut("<"===m[1]),lu=(n,c)=>t[c](n?parseInt(n,10):1);while(m=refmt.exec(format)){((r,s,f)=>{for(let i=0;i{if(arrb.byteLength<(offs|0)+size){throw errbuf}let v=new DataView(arrb,offs|0);return fns.map(f=>f.u(v))};const pack_into=(arrb,offs,...values)=>{if(values.lengthf.p(v,values[i]))};const pack=(...values)=>{let b=new ArrayBuffer(size);pack_into(b,0,...values);return b};const unpack=arrb=>unpack_from(arrb,0);function*iter_unpack(arrb){for(let offs=0;offs+size<=arrb.byteLength;offs+=size){yield unpack_from(arrb,offs)}}return Object.freeze({unpack,pack,unpack_from,pack_into,iter_unpack,format,size})}};var ByteParser=_ByteParser;ByteParser.codes={"\\n":10,"\\r":13,"\\t":9,"\\s":32,"\\b":8,"\\f":12,"\\":92};var rms={structs:{sps:250,nSec:1,watch:["0","1","2","3"],data:{},rms:{}},ondata:(ctx,data)=>{ctx.watch.forEach(key=>{if(data[key]){if(!ctx.data[key]){if(Array.isArray(data[key])){ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key][0])}else ctx.data[key]=new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key])}ByteParser.circularBuffer(ctx.data[key],data[key])}});if(data.timestamp){if(Array.isArray(data.timestamp)){ctx.rms.timestamp=data.timestamp[data.timestamp.length-1]}else ctx.rms.timestamp=data.timestamp}else ctx.rms.timestamp=Date.now();return new Promise(async res=>{await Promise.all(ctx.watch.map(async key=>{if(ctx.data[key])ctx.rms[key]=Math.sqrt(Math.abs(ctx.data[key].reduce((p,v,i)=>p+v*v)/ctx.data[key].length));else delete ctx.rms[key]}));res(ctx.rms)})}};var circularBuffer2d={structs:{bufferSize:250,watch:["0","1","2","3"],data:{},blocking:false},oncreate:ctx=>{for(const key in ctx.watch){ctx.data[key]=new Array(ctx.bufferSize).fill(0)}},ondata:(ctx,data)=>{let buffer2d=[];ctx.watch.forEach(key=>{if(data[key]){ByteParser.circularBuffer(ctx.data[key],data[key]);buffer2d.push(ctx.data[key])}});return buffer2d}};Object.assign(algorithms,{beat_detect,accel_gyro,heartrate:beat_detect,breath:Object.assign({},beat_detect),blink_detect,rms,circularBuffer2d});algorithms["breath"].structs=JSON.parse(JSON.stringify(algorithms["breath"].structs));algorithms["breath"].structs.maxFreq=.2;var three_module_exports={};__export(three_module_exports,{ACESFilmicToneMapping:()=>ACESFilmicToneMapping,AddEquation:()=>AddEquation,AddOperation:()=>AddOperation,AdditiveAnimationBlendMode:()=>AdditiveAnimationBlendMode,AdditiveBlending:()=>AdditiveBlending,AlphaFormat:()=>AlphaFormat,AlwaysDepth:()=>AlwaysDepth,AlwaysStencilFunc:()=>AlwaysStencilFunc,AmbientLight:()=>AmbientLight,AmbientLightProbe:()=>AmbientLightProbe,AnimationClip:()=>AnimationClip,AnimationLoader:()=>AnimationLoader,AnimationMixer:()=>AnimationMixer,AnimationObjectGroup:()=>AnimationObjectGroup,AnimationUtils:()=>AnimationUtils,ArcCurve:()=>ArcCurve,ArrayCamera:()=>ArrayCamera,ArrowHelper:()=>ArrowHelper,Audio:()=>Audio,AudioAnalyser:()=>AudioAnalyser,AudioContext:()=>AudioContext,AudioListener:()=>AudioListener,AudioLoader:()=>AudioLoader,AxesHelper:()=>AxesHelper,BackSide:()=>BackSide,BasicDepthPacking:()=>BasicDepthPacking,BasicShadowMap:()=>BasicShadowMap,Bone:()=>Bone,BooleanKeyframeTrack:()=>BooleanKeyframeTrack,Box2:()=>Box2,Box3:()=>Box3,Box3Helper:()=>Box3Helper,BoxBufferGeometry:()=>BoxGeometry,BoxGeometry:()=>BoxGeometry,BoxHelper:()=>BoxHelper,BufferAttribute:()=>BufferAttribute,BufferGeometry:()=>BufferGeometry,BufferGeometryLoader:()=>BufferGeometryLoader,ByteType:()=>ByteType,Cache:()=>Cache,Camera:()=>Camera,CameraHelper:()=>CameraHelper,CanvasTexture:()=>CanvasTexture,CapsuleBufferGeometry:()=>CapsuleGeometry,CapsuleGeometry:()=>CapsuleGeometry,CatmullRomCurve3:()=>CatmullRomCurve3,CineonToneMapping:()=>CineonToneMapping,CircleBufferGeometry:()=>CircleGeometry,CircleGeometry:()=>CircleGeometry,ClampToEdgeWrapping:()=>ClampToEdgeWrapping,Clock:()=>Clock,Color:()=>Color,ColorKeyframeTrack:()=>ColorKeyframeTrack,ColorManagement:()=>ColorManagement,CompressedTexture:()=>CompressedTexture,CompressedTextureLoader:()=>CompressedTextureLoader,ConeBufferGeometry:()=>ConeGeometry,ConeGeometry:()=>ConeGeometry,CubeCamera:()=>CubeCamera,CubeReflectionMapping:()=>CubeReflectionMapping,CubeRefractionMapping:()=>CubeRefractionMapping,CubeTexture:()=>CubeTexture,CubeTextureLoader:()=>CubeTextureLoader,CubeUVReflectionMapping:()=>CubeUVReflectionMapping,CubicBezierCurve:()=>CubicBezierCurve,CubicBezierCurve3:()=>CubicBezierCurve3,CubicInterpolant:()=>CubicInterpolant,CullFaceBack:()=>CullFaceBack,CullFaceFront:()=>CullFaceFront,CullFaceFrontBack:()=>CullFaceFrontBack,CullFaceNone:()=>CullFaceNone,Curve:()=>Curve,CurvePath:()=>CurvePath,CustomBlending:()=>CustomBlending,CustomToneMapping:()=>CustomToneMapping,CylinderBufferGeometry:()=>CylinderGeometry,CylinderGeometry:()=>CylinderGeometry,Cylindrical:()=>Cylindrical,Data3DTexture:()=>Data3DTexture,DataArrayTexture:()=>DataArrayTexture,DataTexture:()=>DataTexture,DataTexture2DArray:()=>DataTexture2DArray,DataTexture3D:()=>DataTexture3D,DataTextureLoader:()=>DataTextureLoader,DataUtils:()=>DataUtils,DecrementStencilOp:()=>DecrementStencilOp,DecrementWrapStencilOp:()=>DecrementWrapStencilOp,DefaultLoadingManager:()=>DefaultLoadingManager,DepthFormat:()=>DepthFormat,DepthStencilFormat:()=>DepthStencilFormat,DepthTexture:()=>DepthTexture,DirectionalLight:()=>DirectionalLight,DirectionalLightHelper:()=>DirectionalLightHelper,DiscreteInterpolant:()=>DiscreteInterpolant,DodecahedronBufferGeometry:()=>DodecahedronGeometry,DodecahedronGeometry:()=>DodecahedronGeometry,DoubleSide:()=>DoubleSide,DstAlphaFactor:()=>DstAlphaFactor,DstColorFactor:()=>DstColorFactor,DynamicCopyUsage:()=>DynamicCopyUsage,DynamicDrawUsage:()=>DynamicDrawUsage,DynamicReadUsage:()=>DynamicReadUsage,EdgesGeometry:()=>EdgesGeometry,EllipseCurve:()=>EllipseCurve,EqualDepth:()=>EqualDepth,EqualStencilFunc:()=>EqualStencilFunc,EquirectangularReflectionMapping:()=>EquirectangularReflectionMapping,EquirectangularRefractionMapping:()=>EquirectangularRefractionMapping,Euler:()=>Euler,EventDispatcher:()=>EventDispatcher2,ExtrudeBufferGeometry:()=>ExtrudeGeometry,ExtrudeGeometry:()=>ExtrudeGeometry,FileLoader:()=>FileLoader,FlatShading:()=>FlatShading,Float16BufferAttribute:()=>Float16BufferAttribute,Float32BufferAttribute:()=>Float32BufferAttribute,Float64BufferAttribute:()=>Float64BufferAttribute,FloatType:()=>FloatType,Fog:()=>Fog,FogExp2:()=>FogExp2,Font:()=>Font,FontLoader:()=>FontLoader,FramebufferTexture:()=>FramebufferTexture,FrontSide:()=>FrontSide,Frustum:()=>Frustum,GLBufferAttribute:()=>GLBufferAttribute,GLSL1:()=>GLSL1,GLSL3:()=>GLSL3,GreaterDepth:()=>GreaterDepth,GreaterEqualDepth:()=>GreaterEqualDepth,GreaterEqualStencilFunc:()=>GreaterEqualStencilFunc,GreaterStencilFunc:()=>GreaterStencilFunc,GridHelper:()=>GridHelper,Group:()=>Group,HalfFloatType:()=>HalfFloatType,HemisphereLight:()=>HemisphereLight,HemisphereLightHelper:()=>HemisphereLightHelper,HemisphereLightProbe:()=>HemisphereLightProbe,IcosahedronBufferGeometry:()=>IcosahedronGeometry,IcosahedronGeometry:()=>IcosahedronGeometry,ImageBitmapLoader:()=>ImageBitmapLoader,ImageLoader:()=>ImageLoader,ImageUtils:()=>ImageUtils,ImmediateRenderObject:()=>ImmediateRenderObject,IncrementStencilOp:()=>IncrementStencilOp,IncrementWrapStencilOp:()=>IncrementWrapStencilOp,InstancedBufferAttribute:()=>InstancedBufferAttribute,InstancedBufferGeometry:()=>InstancedBufferGeometry,InstancedInterleavedBuffer:()=>InstancedInterleavedBuffer,InstancedMesh:()=>InstancedMesh,Int16BufferAttribute:()=>Int16BufferAttribute,Int32BufferAttribute:()=>Int32BufferAttribute,Int8BufferAttribute:()=>Int8BufferAttribute,IntType:()=>IntType,InterleavedBuffer:()=>InterleavedBuffer,InterleavedBufferAttribute:()=>InterleavedBufferAttribute,Interpolant:()=>Interpolant,InterpolateDiscrete:()=>InterpolateDiscrete,InterpolateLinear:()=>InterpolateLinear,InterpolateSmooth:()=>InterpolateSmooth,InvertStencilOp:()=>InvertStencilOp,KeepStencilOp:()=>KeepStencilOp,KeyframeTrack:()=>KeyframeTrack,LOD:()=>LOD,LatheBufferGeometry:()=>LatheGeometry,LatheGeometry:()=>LatheGeometry,Layers:()=>Layers,LessDepth:()=>LessDepth,LessEqualDepth:()=>LessEqualDepth,LessEqualStencilFunc:()=>LessEqualStencilFunc,LessStencilFunc:()=>LessStencilFunc,Light:()=>Light,LightProbe:()=>LightProbe,Line:()=>Line,Line3:()=>Line3,LineBasicMaterial:()=>LineBasicMaterial,LineCurve:()=>LineCurve,LineCurve3:()=>LineCurve3,LineDashedMaterial:()=>LineDashedMaterial,LineLoop:()=>LineLoop,LineSegments:()=>LineSegments,LinearEncoding:()=>LinearEncoding,LinearFilter:()=>LinearFilter,LinearInterpolant:()=>LinearInterpolant,LinearMipMapLinearFilter:()=>LinearMipMapLinearFilter,LinearMipMapNearestFilter:()=>LinearMipMapNearestFilter,LinearMipmapLinearFilter:()=>LinearMipmapLinearFilter,LinearMipmapNearestFilter:()=>LinearMipmapNearestFilter,LinearSRGBColorSpace:()=>LinearSRGBColorSpace,LinearToneMapping:()=>LinearToneMapping,Loader:()=>Loader,LoaderUtils:()=>LoaderUtils,LoadingManager:()=>LoadingManager,LoopOnce:()=>LoopOnce,LoopPingPong:()=>LoopPingPong,LoopRepeat:()=>LoopRepeat,LuminanceAlphaFormat:()=>LuminanceAlphaFormat,LuminanceFormat:()=>LuminanceFormat,MOUSE:()=>MOUSE,Material:()=>Material,MaterialLoader:()=>MaterialLoader,MathUtils:()=>MathUtils,Matrix3:()=>Matrix3,Matrix4:()=>Matrix4,MaxEquation:()=>MaxEquation,Mesh:()=>Mesh,MeshBasicMaterial:()=>MeshBasicMaterial,MeshDepthMaterial:()=>MeshDepthMaterial,MeshDistanceMaterial:()=>MeshDistanceMaterial,MeshLambertMaterial:()=>MeshLambertMaterial,MeshMatcapMaterial:()=>MeshMatcapMaterial,MeshNormalMaterial:()=>MeshNormalMaterial,MeshPhongMaterial:()=>MeshPhongMaterial,MeshPhysicalMaterial:()=>MeshPhysicalMaterial,MeshStandardMaterial:()=>MeshStandardMaterial,MeshToonMaterial:()=>MeshToonMaterial,MinEquation:()=>MinEquation,MirroredRepeatWrapping:()=>MirroredRepeatWrapping,MixOperation:()=>MixOperation,MultiplyBlending:()=>MultiplyBlending,MultiplyOperation:()=>MultiplyOperation,NearestFilter:()=>NearestFilter,NearestMipMapLinearFilter:()=>NearestMipMapLinearFilter,NearestMipMapNearestFilter:()=>NearestMipMapNearestFilter,NearestMipmapLinearFilter:()=>NearestMipmapLinearFilter,NearestMipmapNearestFilter:()=>NearestMipmapNearestFilter,NeverDepth:()=>NeverDepth,NeverStencilFunc:()=>NeverStencilFunc,NoBlending:()=>NoBlending,NoColorSpace:()=>NoColorSpace,NoToneMapping:()=>NoToneMapping,NormalAnimationBlendMode:()=>NormalAnimationBlendMode,NormalBlending:()=>NormalBlending,NotEqualDepth:()=>NotEqualDepth,NotEqualStencilFunc:()=>NotEqualStencilFunc,NumberKeyframeTrack:()=>NumberKeyframeTrack,Object3D:()=>Object3D,ObjectLoader:()=>ObjectLoader,ObjectSpaceNormalMap:()=>ObjectSpaceNormalMap,OctahedronBufferGeometry:()=>OctahedronGeometry,OctahedronGeometry:()=>OctahedronGeometry,OneFactor:()=>OneFactor,OneMinusDstAlphaFactor:()=>OneMinusDstAlphaFactor,OneMinusDstColorFactor:()=>OneMinusDstColorFactor,OneMinusSrcAlphaFactor:()=>OneMinusSrcAlphaFactor,OneMinusSrcColorFactor:()=>OneMinusSrcColorFactor,OrthographicCamera:()=>OrthographicCamera,PCFShadowMap:()=>PCFShadowMap,PCFSoftShadowMap:()=>PCFSoftShadowMap,PMREMGenerator:()=>PMREMGenerator,ParametricGeometry:()=>ParametricGeometry,Path:()=>Path,PerspectiveCamera:()=>PerspectiveCamera,Plane:()=>Plane,PlaneBufferGeometry:()=>PlaneGeometry,PlaneGeometry:()=>PlaneGeometry,PlaneHelper:()=>PlaneHelper,PointLight:()=>PointLight,PointLightHelper:()=>PointLightHelper,Points:()=>Points,PointsMaterial:()=>PointsMaterial,PolarGridHelper:()=>PolarGridHelper,PolyhedronBufferGeometry:()=>PolyhedronGeometry,PolyhedronGeometry:()=>PolyhedronGeometry,PositionalAudio:()=>PositionalAudio,PropertyBinding:()=>PropertyBinding,PropertyMixer:()=>PropertyMixer,QuadraticBezierCurve:()=>QuadraticBezierCurve,QuadraticBezierCurve3:()=>QuadraticBezierCurve3,Quaternion:()=>Quaternion,QuaternionKeyframeTrack:()=>QuaternionKeyframeTrack,QuaternionLinearInterpolant:()=>QuaternionLinearInterpolant,REVISION:()=>REVISION,RGBADepthPacking:()=>RGBADepthPacking,RGBAFormat:()=>RGBAFormat,RGBAIntegerFormat:()=>RGBAIntegerFormat,RGBA_ASTC_10x10_Format:()=>RGBA_ASTC_10x10_Format,RGBA_ASTC_10x5_Format:()=>RGBA_ASTC_10x5_Format,RGBA_ASTC_10x6_Format:()=>RGBA_ASTC_10x6_Format,RGBA_ASTC_10x8_Format:()=>RGBA_ASTC_10x8_Format,RGBA_ASTC_12x10_Format:()=>RGBA_ASTC_12x10_Format,RGBA_ASTC_12x12_Format:()=>RGBA_ASTC_12x12_Format,RGBA_ASTC_4x4_Format:()=>RGBA_ASTC_4x4_Format,RGBA_ASTC_5x4_Format:()=>RGBA_ASTC_5x4_Format,RGBA_ASTC_5x5_Format:()=>RGBA_ASTC_5x5_Format,RGBA_ASTC_6x5_Format:()=>RGBA_ASTC_6x5_Format,RGBA_ASTC_6x6_Format:()=>RGBA_ASTC_6x6_Format,RGBA_ASTC_8x5_Format:()=>RGBA_ASTC_8x5_Format,RGBA_ASTC_8x6_Format:()=>RGBA_ASTC_8x6_Format,RGBA_ASTC_8x8_Format:()=>RGBA_ASTC_8x8_Format,RGBA_BPTC_Format:()=>RGBA_BPTC_Format,RGBA_ETC2_EAC_Format:()=>RGBA_ETC2_EAC_Format,RGBA_PVRTC_2BPPV1_Format:()=>RGBA_PVRTC_2BPPV1_Format,RGBA_PVRTC_4BPPV1_Format:()=>RGBA_PVRTC_4BPPV1_Format,RGBA_S3TC_DXT1_Format:()=>RGBA_S3TC_DXT1_Format,RGBA_S3TC_DXT3_Format:()=>RGBA_S3TC_DXT3_Format,RGBA_S3TC_DXT5_Format:()=>RGBA_S3TC_DXT5_Format,RGBFormat:()=>RGBFormat,RGB_ETC1_Format:()=>RGB_ETC1_Format,RGB_ETC2_Format:()=>RGB_ETC2_Format,RGB_PVRTC_2BPPV1_Format:()=>RGB_PVRTC_2BPPV1_Format,RGB_PVRTC_4BPPV1_Format:()=>RGB_PVRTC_4BPPV1_Format,RGB_S3TC_DXT1_Format:()=>RGB_S3TC_DXT1_Format,RGFormat:()=>RGFormat,RGIntegerFormat:()=>RGIntegerFormat,RawShaderMaterial:()=>RawShaderMaterial,Ray:()=>Ray,Raycaster:()=>Raycaster,RectAreaLight:()=>RectAreaLight,RedFormat:()=>RedFormat,RedIntegerFormat:()=>RedIntegerFormat,ReinhardToneMapping:()=>ReinhardToneMapping,RepeatWrapping:()=>RepeatWrapping,ReplaceStencilOp:()=>ReplaceStencilOp,ReverseSubtractEquation:()=>ReverseSubtractEquation,RingBufferGeometry:()=>RingGeometry,RingGeometry:()=>RingGeometry,SRGBColorSpace:()=>SRGBColorSpace,Scene:()=>Scene,ShaderChunk:()=>ShaderChunk,ShaderLib:()=>ShaderLib,ShaderMaterial:()=>ShaderMaterial,ShadowMaterial:()=>ShadowMaterial,Shape:()=>Shape,ShapeBufferGeometry:()=>ShapeGeometry,ShapeGeometry:()=>ShapeGeometry,ShapePath:()=>ShapePath,ShapeUtils:()=>ShapeUtils,ShortType:()=>ShortType,Skeleton:()=>Skeleton,SkeletonHelper:()=>SkeletonHelper,SkinnedMesh:()=>SkinnedMesh,SmoothShading:()=>SmoothShading,Source:()=>Source,Sphere:()=>Sphere,SphereBufferGeometry:()=>SphereGeometry,SphereGeometry:()=>SphereGeometry,Spherical:()=>Spherical,SphericalHarmonics3:()=>SphericalHarmonics3,SplineCurve:()=>SplineCurve,SpotLight:()=>SpotLight,SpotLightHelper:()=>SpotLightHelper,Sprite:()=>Sprite,SpriteMaterial:()=>SpriteMaterial,SrcAlphaFactor:()=>SrcAlphaFactor,SrcAlphaSaturateFactor:()=>SrcAlphaSaturateFactor,SrcColorFactor:()=>SrcColorFactor,StaticCopyUsage:()=>StaticCopyUsage,StaticDrawUsage:()=>StaticDrawUsage,StaticReadUsage:()=>StaticReadUsage,StereoCamera:()=>StereoCamera,StreamCopyUsage:()=>StreamCopyUsage,StreamDrawUsage:()=>StreamDrawUsage,StreamReadUsage:()=>StreamReadUsage,StringKeyframeTrack:()=>StringKeyframeTrack,SubtractEquation:()=>SubtractEquation,SubtractiveBlending:()=>SubtractiveBlending,TOUCH:()=>TOUCH,TangentSpaceNormalMap:()=>TangentSpaceNormalMap,TetrahedronBufferGeometry:()=>TetrahedronGeometry,TetrahedronGeometry:()=>TetrahedronGeometry,TextGeometry:()=>TextGeometry,Texture:()=>Texture,TextureLoader:()=>TextureLoader,TorusBufferGeometry:()=>TorusGeometry,TorusGeometry:()=>TorusGeometry,TorusKnotBufferGeometry:()=>TorusKnotGeometry,TorusKnotGeometry:()=>TorusKnotGeometry,Triangle:()=>Triangle,TriangleFanDrawMode:()=>TriangleFanDrawMode,TriangleStripDrawMode:()=>TriangleStripDrawMode,TrianglesDrawMode:()=>TrianglesDrawMode,TubeBufferGeometry:()=>TubeGeometry,TubeGeometry:()=>TubeGeometry,UVMapping:()=>UVMapping,Uint16BufferAttribute:()=>Uint16BufferAttribute,Uint32BufferAttribute:()=>Uint32BufferAttribute,Uint8BufferAttribute:()=>Uint8BufferAttribute,Uint8ClampedBufferAttribute:()=>Uint8ClampedBufferAttribute,Uniform:()=>Uniform,UniformsGroup:()=>UniformsGroup,UniformsLib:()=>UniformsLib,UniformsUtils:()=>UniformsUtils,UnsignedByteType:()=>UnsignedByteType,UnsignedInt248Type:()=>UnsignedInt248Type,UnsignedIntType:()=>UnsignedIntType,UnsignedShort4444Type:()=>UnsignedShort4444Type,UnsignedShort5551Type:()=>UnsignedShort5551Type,UnsignedShortType:()=>UnsignedShortType,VSMShadowMap:()=>VSMShadowMap,Vector2:()=>Vector2,Vector3:()=>Vector3,Vector4:()=>Vector4,VectorKeyframeTrack:()=>VectorKeyframeTrack,VideoTexture:()=>VideoTexture,WebGL1Renderer:()=>WebGL1Renderer,WebGL3DRenderTarget:()=>WebGL3DRenderTarget,WebGLArrayRenderTarget:()=>WebGLArrayRenderTarget,WebGLCubeRenderTarget:()=>WebGLCubeRenderTarget,WebGLMultipleRenderTargets:()=>WebGLMultipleRenderTargets,WebGLMultisampleRenderTarget:()=>WebGLMultisampleRenderTarget,WebGLRenderTarget:()=>WebGLRenderTarget,WebGLRenderer:()=>WebGLRenderer,WebGLUtils:()=>WebGLUtils,WireframeGeometry:()=>WireframeGeometry,WrapAroundEnding:()=>WrapAroundEnding,ZeroCurvatureEnding:()=>ZeroCurvatureEnding,ZeroFactor:()=>ZeroFactor,ZeroSlopeEnding:()=>ZeroSlopeEnding,ZeroStencilOp:()=>ZeroStencilOp,_SRGBAFormat:()=>_SRGBAFormat,sRGBEncoding:()=>sRGBEncoding});var REVISION="143";var MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2};var TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3};var CullFaceNone=0;var CullFaceBack=1;var CullFaceFront=2;var CullFaceFrontBack=3;var BasicShadowMap=0;var PCFShadowMap=1;var PCFSoftShadowMap=2;var VSMShadowMap=3;var FrontSide=0;var BackSide=1;var DoubleSide=2;var FlatShading=1;var SmoothShading=2;var NoBlending=0;var NormalBlending=1;var AdditiveBlending=2;var SubtractiveBlending=3;var MultiplyBlending=4;var CustomBlending=5;var AddEquation=100;var SubtractEquation=101;var ReverseSubtractEquation=102;var MinEquation=103;var MaxEquation=104;var ZeroFactor=200;var OneFactor=201;var SrcColorFactor=202;var OneMinusSrcColorFactor=203;var SrcAlphaFactor=204;var OneMinusSrcAlphaFactor=205;var DstAlphaFactor=206;var OneMinusDstAlphaFactor=207;var DstColorFactor=208;var OneMinusDstColorFactor=209;var SrcAlphaSaturateFactor=210;var NeverDepth=0;var AlwaysDepth=1;var LessDepth=2;var LessEqualDepth=3;var EqualDepth=4;var GreaterEqualDepth=5;var GreaterDepth=6;var NotEqualDepth=7;var MultiplyOperation=0;var MixOperation=1;var AddOperation=2;var NoToneMapping=0;var LinearToneMapping=1;var ReinhardToneMapping=2;var CineonToneMapping=3;var ACESFilmicToneMapping=4;var CustomToneMapping=5;var UVMapping=300;var CubeReflectionMapping=301;var CubeRefractionMapping=302;var EquirectangularReflectionMapping=303;var EquirectangularRefractionMapping=304;var CubeUVReflectionMapping=306;var RepeatWrapping=1e3;var ClampToEdgeWrapping=1001;var MirroredRepeatWrapping=1002;var NearestFilter=1003;var NearestMipmapNearestFilter=1004;var NearestMipMapNearestFilter=1004;var NearestMipmapLinearFilter=1005;var NearestMipMapLinearFilter=1005;var LinearFilter=1006;var LinearMipmapNearestFilter=1007;var LinearMipMapNearestFilter=1007;var LinearMipmapLinearFilter=1008;var LinearMipMapLinearFilter=1008;var UnsignedByteType=1009;var ByteType=1010;var ShortType=1011;var UnsignedShortType=1012;var IntType=1013;var UnsignedIntType=1014;var FloatType=1015;var HalfFloatType=1016;var UnsignedShort4444Type=1017;var UnsignedShort5551Type=1018;var UnsignedInt248Type=1020;var AlphaFormat=1021;var RGBFormat=1022;var RGBAFormat=1023;var LuminanceFormat=1024;var LuminanceAlphaFormat=1025;var DepthFormat=1026;var DepthStencilFormat=1027;var RedFormat=1028;var RedIntegerFormat=1029;var RGFormat=1030;var RGIntegerFormat=1031;var RGBAIntegerFormat=1033;var RGB_S3TC_DXT1_Format=33776;var RGBA_S3TC_DXT1_Format=33777;var RGBA_S3TC_DXT3_Format=33778;var RGBA_S3TC_DXT5_Format=33779;var RGB_PVRTC_4BPPV1_Format=35840;var RGB_PVRTC_2BPPV1_Format=35841;var RGBA_PVRTC_4BPPV1_Format=35842;var RGBA_PVRTC_2BPPV1_Format=35843;var RGB_ETC1_Format=36196;var RGB_ETC2_Format=37492;var RGBA_ETC2_EAC_Format=37496;var RGBA_ASTC_4x4_Format=37808;var RGBA_ASTC_5x4_Format=37809;var RGBA_ASTC_5x5_Format=37810;var RGBA_ASTC_6x5_Format=37811;var RGBA_ASTC_6x6_Format=37812;var RGBA_ASTC_8x5_Format=37813;var RGBA_ASTC_8x6_Format=37814;var RGBA_ASTC_8x8_Format=37815;var RGBA_ASTC_10x5_Format=37816;var RGBA_ASTC_10x6_Format=37817;var RGBA_ASTC_10x8_Format=37818;var RGBA_ASTC_10x10_Format=37819;var RGBA_ASTC_12x10_Format=37820;var RGBA_ASTC_12x12_Format=37821;var RGBA_BPTC_Format=36492;var LoopOnce=2200;var LoopRepeat=2201;var LoopPingPong=2202;var InterpolateDiscrete=2300;var InterpolateLinear=2301;var InterpolateSmooth=2302;var ZeroCurvatureEnding=2400;var ZeroSlopeEnding=2401;var WrapAroundEnding=2402;var NormalAnimationBlendMode=2500;var AdditiveAnimationBlendMode=2501;var TrianglesDrawMode=0;var TriangleStripDrawMode=1;var TriangleFanDrawMode=2;var LinearEncoding=3e3;var sRGBEncoding=3001;var BasicDepthPacking=3200;var RGBADepthPacking=3201;var TangentSpaceNormalMap=0;var ObjectSpaceNormalMap=1;var NoColorSpace="";var SRGBColorSpace="srgb";var LinearSRGBColorSpace="srgb-linear";var ZeroStencilOp=0;var KeepStencilOp=7680;var ReplaceStencilOp=7681;var IncrementStencilOp=7682;var DecrementStencilOp=7683;var IncrementWrapStencilOp=34055;var DecrementWrapStencilOp=34056;var InvertStencilOp=5386;var NeverStencilFunc=512;var LessStencilFunc=513;var EqualStencilFunc=514;var LessEqualStencilFunc=515;var GreaterStencilFunc=516;var NotEqualStencilFunc=517;var GreaterEqualStencilFunc=518;var AlwaysStencilFunc=519;var StaticDrawUsage=35044;var DynamicDrawUsage=35048;var StreamDrawUsage=35040;var StaticReadUsage=35045;var DynamicReadUsage=35049;var StreamReadUsage=35041;var StaticCopyUsage=35046;var DynamicCopyUsage=35050;var StreamCopyUsage=35042;var GLSL1="100";var GLSL3="300 es";var _SRGBAFormat=1035;var EventDispatcher2=class{addEventListener(type,listener){if(this._listeners===void 0)this._listeners={};const listeners2=this._listeners;if(listeners2[type]===void 0){listeners2[type]=[]}if(listeners2[type].indexOf(listener)===-1){listeners2[type].push(listener)}}hasEventListener(type,listener){if(this._listeners===void 0)return false;const listeners2=this._listeners;return listeners2[type]!==void 0&&listeners2[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this._listeners===void 0)return;const listeners2=this._listeners;const listenerArray=listeners2[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event){if(this._listeners===void 0)return;const listeners2=this._listeners;const listenerArray=listeners2[event.type];if(listenerArray!==void 0){event.target=this;const array=listenerArray.slice(0);for(let i=0,l=array.length;i>8&255]+_lut[d0>>16&255]+_lut[d0>>24&255]+"-"+_lut[d1&255]+_lut[d1>>8&255]+"-"+_lut[d1>>16&15|64]+_lut[d1>>24&255]+"-"+_lut[d2&63|128]+_lut[d2>>8&255]+"-"+_lut[d2>>16&255]+_lut[d2>>24&255]+_lut[d3&255]+_lut[d3>>8&255]+_lut[d3>>16&255]+_lut[d3>>24&255];return uuid.toLowerCase()}function clamp(value,min,max){return Math.max(min,Math.min(max,value))}function euclideanModulo(n,m){return(n%m+m)%m}function mapLinear(x2,a1,a2,b1,b2){return b1+(x2-a1)*(b2-b1)/(a2-a1)}function inverseLerp(x2,y2,value){if(x2!==y2){return(value-x2)/(y2-x2)}else{return 0}}function lerp(x2,y2,t){return(1-t)*x2+t*y2}function damp(x2,y2,lambda,dt){return lerp(x2,y2,1-Math.exp(-lambda*dt))}function pingpong(x2,length=1){return length-Math.abs(euclideanModulo(x2,length*2)-length)}function smoothstep(x2,min,max){if(x2<=min)return 0;if(x2>=max)return 1;x2=(x2-min)/(max-min);return x2*x2*(3-2*x2)}function smootherstep(x2,min,max){if(x2<=min)return 0;if(x2>=max)return 1;x2=(x2-min)/(max-min);return x2*x2*x2*(x2*(x2*6-15)+10)}function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1))}function randFloat(low,high){return low+Math.random()*(high-low)}function randFloatSpread(range){return range*(.5-Math.random())}function seededRandom(s){if(s!==void 0)_seed=s;let t=_seed+=1831565813;t=Math.imul(t^t>>>15,t|1);t^=t+Math.imul(t^t>>>7,t|61);return((t^t>>>14)>>>0)/4294967296}function degToRad(degrees){return degrees*DEG2RAD}function radToDeg(radians){return radians*RAD2DEG}function isPowerOfTwo(value){return(value&value-1)===0&&value!==0}function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2))}function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2))}function setQuaternionFromProperEuler(q,a,b,c,order){const cos=Math.cos;const sin=Math.sin;const c2=cos(b/2);const s2=sin(b/2);const c13=cos((a+c)/2);const s13=sin((a+c)/2);const c1_3=cos((a-c)/2);const s1_3=sin((a-c)/2);const c3_1=cos((c-a)/2);const s3_1=sin((c-a)/2);switch(order){case"XYX":q.set(c2*s13,s2*c1_3,s2*s1_3,c2*c13);break;case"YZY":q.set(s2*s1_3,c2*s13,s2*c1_3,c2*c13);break;case"ZXZ":q.set(s2*c1_3,s2*s1_3,c2*s13,c2*c13);break;case"XZX":q.set(c2*s13,s2*s3_1,s2*c3_1,c2*c13);break;case"YXY":q.set(s2*c3_1,c2*s13,s2*s3_1,c2*c13);break;case"ZYZ":q.set(s2*s3_1,s2*c3_1,c2*s13,c2*c13);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+order)}}function denormalize$1(value,array){switch(array.constructor){case Float32Array:return value;case Uint16Array:return value/65535;case Uint8Array:return value/255;case Int16Array:return Math.max(value/32767,-1);case Int8Array:return Math.max(value/127,-1);default:throw new Error("Invalid component type.")}}function normalize(value,array){switch(array.constructor){case Float32Array:return value;case Uint16Array:return Math.round(value*65535);case Uint8Array:return Math.round(value*255);case Int16Array:return Math.round(value*32767);case Int8Array:return Math.round(value*127);default:throw new Error("Invalid component type.")}}var MathUtils=Object.freeze({__proto__:null,DEG2RAD,RAD2DEG,generateUUID,clamp,euclideanModulo,mapLinear,inverseLerp,lerp,damp,pingpong,smoothstep,smootherstep,randInt,randFloat,randFloatSpread,seededRandom,degToRad,radToDeg,isPowerOfTwo,ceilPowerOfTwo,floorPowerOfTwo,setQuaternionFromProperEuler,normalize,denormalize:denormalize$1});var Vector2=class{constructor(x2=0,y2=0){Vector2.prototype.isVector2=true;this.x=x2;this.y=y2}get width(){return this.x}set width(value){this.x=value}get height(){return this.y}set height(value){this.y=value}set(x2,y2){this.x=x2;this.y=y2;return this}setScalar(scalar){this.x=scalar;this.y=scalar;return this}setX(x2){this.x=x2;return this}setY(y2){this.y=y2;return this}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;default:throw new Error("index is out of range: "+index)}return this}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+index)}}clone(){return new this.constructor(this.x,this.y)}copy(v){this.x=v.x;this.y=v.y;return this}add(v){this.x+=v.x;this.y+=v.y;return this}addScalar(s){this.x+=s;this.y+=s;return this}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this}sub(v){this.x-=v.x;this.y-=v.y;return this}subScalar(s){this.x-=s;this.y-=s;return this}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this}multiply(v){this.x*=v.x;this.y*=v.y;return this}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this}divide(v){this.x/=v.x;this.y/=v.y;return this}divideScalar(scalar){return this.multiplyScalar(1/scalar)}applyMatrix3(m){const x2=this.x,y2=this.y;const e=m.elements;this.x=e[0]*x2+e[3]*y2+e[6];this.y=e[1]*x2+e[4]*y2+e[7];return this}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this}clamp(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));return this}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));return this}clampLength(min,max){const length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);return this}negate(){this.x=-this.x;this.y=-this.y;return this}dot(v){return this.x*v.x+this.y*v.y}cross(v){return this.x*v.y-this.y*v.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){const angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle}distanceTo(v){return Math.sqrt(this.distanceToSquared(v))}distanceToSquared(v){const dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)}setLength(length){return this.normalize().multiplyScalar(length)}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;return this}equals(v){return v.x===this.x&&v.y===this.y}fromArray(array,offset=0){this.x=array[offset];this.y=array[offset+1];return this}toArray(array=[],offset=0){array[offset]=this.x;array[offset+1]=this.y;return array}fromBufferAttribute(attribute,index){this.x=attribute.getX(index);this.y=attribute.getY(index);return this}rotateAround(center,angle){const c=Math.cos(angle),s=Math.sin(angle);const x2=this.x-center.x;const y2=this.y-center.y;this.x=x2*c-y2*s+center.x;this.y=x2*s+y2*c+center.y;return this}random(){this.x=Math.random();this.y=Math.random();return this}*[Symbol.iterator](){yield this.x;yield this.y}};var Matrix3=class{constructor(){Matrix3.prototype.isMatrix3=true;this.elements=[1,0,0,0,1,0,0,0,1]}set(n11,n12,n13,n21,n22,n23,n31,n32,n33){const te=this.elements;te[0]=n11;te[1]=n21;te[2]=n31;te[3]=n12;te[4]=n22;te[5]=n32;te[6]=n13;te[7]=n23;te[8]=n33;return this}identity(){this.set(1,0,0,0,1,0,0,0,1);return this}copy(m){const te=this.elements;const me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];return this}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this}setFromMatrix4(m){const me=m.elements;this.set(me[0],me[4],me[8],me[1],me[5],me[9],me[2],me[6],me[10]);return this}multiply(m){return this.multiplyMatrices(this,m)}premultiply(m){return this.multiplyMatrices(m,this)}multiplyMatrices(a,b){const ae=a.elements;const be=b.elements;const te=this.elements;const a11=ae[0],a12=ae[3],a13=ae[6];const a21=ae[1],a22=ae[4],a23=ae[7];const a31=ae[2],a32=ae[5],a33=ae[8];const b11=be[0],b12=be[3],b13=be[6];const b21=be[1],b22=be[4],b23=be[7];const b31=be[2],b32=be[5],b33=be[8];te[0]=a11*b11+a12*b21+a13*b31;te[3]=a11*b12+a12*b22+a13*b32;te[6]=a11*b13+a12*b23+a13*b33;te[1]=a21*b11+a22*b21+a23*b31;te[4]=a21*b12+a22*b22+a23*b32;te[7]=a21*b13+a22*b23+a23*b33;te[2]=a31*b11+a32*b21+a33*b31;te[5]=a31*b12+a32*b22+a33*b32;te[8]=a31*b13+a32*b23+a33*b33;return this}multiplyScalar(s){const te=this.elements;te[0]*=s;te[3]*=s;te[6]*=s;te[1]*=s;te[4]*=s;te[7]*=s;te[2]*=s;te[5]*=s;te[8]*=s;return this}determinant(){const te=this.elements;const a=te[0],b=te[1],c=te[2],d=te[3],e=te[4],f=te[5],g=te[6],h=te[7],i=te[8];return a*e*i-a*f*h-b*d*i+b*f*g+c*d*h-c*e*g}invert(){const te=this.elements,n11=te[0],n21=te[1],n31=te[2],n12=te[3],n22=te[4],n32=te[5],n13=te[6],n23=te[7],n33=te[8],t11=n33*n22-n32*n23,t12=n32*n13-n33*n12,t13=n23*n12-n22*n13,det=n11*t11+n21*t12+n31*t13;if(det===0)return this.set(0,0,0,0,0,0,0,0,0);const detInv=1/det;te[0]=t11*detInv;te[1]=(n31*n23-n33*n21)*detInv;te[2]=(n32*n21-n31*n22)*detInv;te[3]=t12*detInv;te[4]=(n33*n11-n31*n13)*detInv;te[5]=(n31*n12-n32*n11)*detInv;te[6]=t13*detInv;te[7]=(n21*n13-n23*n11)*detInv;te[8]=(n22*n11-n21*n12)*detInv;return this}transpose(){let tmp2;const m=this.elements;tmp2=m[1];m[1]=m[3];m[3]=tmp2;tmp2=m[2];m[2]=m[6];m[6]=tmp2;tmp2=m[5];m[5]=m[7];m[7]=tmp2;return this}getNormalMatrix(matrix4){return this.setFromMatrix4(matrix4).invert().transpose()}transposeIntoArray(r){const m=this.elements;r[0]=m[0];r[1]=m[3];r[2]=m[6];r[3]=m[1];r[4]=m[4];r[5]=m[7];r[6]=m[2];r[7]=m[5];r[8]=m[8];return this}setUvTransform(tx,ty,sx,sy,rotation,cx,cy){const c=Math.cos(rotation);const s=Math.sin(rotation);this.set(sx*c,sx*s,-sx*(c*cx+s*cy)+cx+tx,-sy*s,sy*c,-sy*(-s*cx+c*cy)+cy+ty,0,0,1);return this}scale(sx,sy){const te=this.elements;te[0]*=sx;te[3]*=sx;te[6]*=sx;te[1]*=sy;te[4]*=sy;te[7]*=sy;return this}rotate(theta){const c=Math.cos(theta);const s=Math.sin(theta);const te=this.elements;const a11=te[0],a12=te[3],a13=te[6];const a21=te[1],a22=te[4],a23=te[7];te[0]=c*a11+s*a21;te[3]=c*a12+s*a22;te[6]=c*a13+s*a23;te[1]=-s*a11+c*a21;te[4]=-s*a12+c*a22;te[7]=-s*a13+c*a23;return this}translate(tx,ty){const te=this.elements;te[0]+=tx*te[2];te[3]+=tx*te[5];te[6]+=tx*te[8];te[1]+=ty*te[2];te[4]+=ty*te[5];te[7]+=ty*te[8];return this}equals(matrix){const te=this.elements;const me=matrix.elements;for(let i=0;i<9;i++){if(te[i]!==me[i])return false}return true}fromArray(array,offset=0){for(let i=0;i<9;i++){this.elements[i]=array[i+offset]}return this}toArray(array=[],offset=0){const te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];return array}clone(){return new this.constructor().fromArray(this.elements)}};function arrayNeedsUint32(array){for(let i=array.length-1;i>=0;--i){if(array[i]>65535)return true}return false}var TYPED_ARRAYS={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function getTypedArray(type,buffer){return new TYPED_ARRAYS[type](buffer)}function createElementNS(name){return document.createElementNS("http://www.w3.org/1999/xhtml",name)}function SRGBToLinear(c){return c<.04045?c*.0773993808:Math.pow(c*.9478672986+.0521327014,2.4)}function LinearToSRGB(c){return c<.0031308?c*12.92:1.055*Math.pow(c,.41666)-.055}var FN={[SRGBColorSpace]:{[LinearSRGBColorSpace]:SRGBToLinear},[LinearSRGBColorSpace]:{[SRGBColorSpace]:LinearToSRGB}};var ColorManagement={legacyMode:true,get workingColorSpace(){return LinearSRGBColorSpace},set workingColorSpace(colorSpace){console.warn("THREE.ColorManagement: .workingColorSpace is readonly.")},convert:function(color,sourceColorSpace,targetColorSpace){if(this.legacyMode||sourceColorSpace===targetColorSpace||!sourceColorSpace||!targetColorSpace){return color}if(FN[sourceColorSpace]&&FN[sourceColorSpace][targetColorSpace]!==void 0){const fn=FN[sourceColorSpace][targetColorSpace];color.r=fn(color.r);color.g=fn(color.g);color.b=fn(color.b);return color}throw new Error("Unsupported color space conversion.")},fromWorkingColorSpace:function(color,targetColorSpace){return this.convert(color,this.workingColorSpace,targetColorSpace)},toWorkingColorSpace:function(color,sourceColorSpace){return this.convert(color,sourceColorSpace,this.workingColorSpace)}};var _colorKeywords={"aliceblue":15792383,"antiquewhite":16444375,"aqua":65535,"aquamarine":8388564,"azure":15794175,"beige":16119260,"bisque":16770244,"black":0,"blanchedalmond":16772045,"blue":255,"blueviolet":9055202,"brown":10824234,"burlywood":14596231,"cadetblue":6266528,"chartreuse":8388352,"chocolate":13789470,"coral":16744272,"cornflowerblue":6591981,"cornsilk":16775388,"crimson":14423100,"cyan":65535,"darkblue":139,"darkcyan":35723,"darkgoldenrod":12092939,"darkgray":11119017,"darkgreen":25600,"darkgrey":11119017,"darkkhaki":12433259,"darkmagenta":9109643,"darkolivegreen":5597999,"darkorange":16747520,"darkorchid":10040012,"darkred":9109504,"darksalmon":15308410,"darkseagreen":9419919,"darkslateblue":4734347,"darkslategray":3100495,"darkslategrey":3100495,"darkturquoise":52945,"darkviolet":9699539,"deeppink":16716947,"deepskyblue":49151,"dimgray":6908265,"dimgrey":6908265,"dodgerblue":2003199,"firebrick":11674146,"floralwhite":16775920,"forestgreen":2263842,"fuchsia":16711935,"gainsboro":14474460,"ghostwhite":16316671,"gold":16766720,"goldenrod":14329120,"gray":8421504,"green":32768,"greenyellow":11403055,"grey":8421504,"honeydew":15794160,"hotpink":16738740,"indianred":13458524,"indigo":4915330,"ivory":16777200,"khaki":15787660,"lavender":15132410,"lavenderblush":16773365,"lawngreen":8190976,"lemonchiffon":16775885,"lightblue":11393254,"lightcoral":15761536,"lightcyan":14745599,"lightgoldenrodyellow":16448210,"lightgray":13882323,"lightgreen":9498256,"lightgrey":13882323,"lightpink":16758465,"lightsalmon":16752762,"lightseagreen":2142890,"lightskyblue":8900346,"lightslategray":7833753,"lightslategrey":7833753,"lightsteelblue":11584734,"lightyellow":16777184,"lime":65280,"limegreen":3329330,"linen":16445670,"magenta":16711935,"maroon":8388608,"mediumaquamarine":6737322,"mediumblue":205,"mediumorchid":12211667,"mediumpurple":9662683,"mediumseagreen":3978097,"mediumslateblue":8087790,"mediumspringgreen":64154,"mediumturquoise":4772300,"mediumvioletred":13047173,"midnightblue":1644912,"mintcream":16121850,"mistyrose":16770273,"moccasin":16770229,"navajowhite":16768685,"navy":128,"oldlace":16643558,"olive":8421376,"olivedrab":7048739,"orange":16753920,"orangered":16729344,"orchid":14315734,"palegoldenrod":15657130,"palegreen":10025880,"paleturquoise":11529966,"palevioletred":14381203,"papayawhip":16773077,"peachpuff":16767673,"peru":13468991,"pink":16761035,"plum":14524637,"powderblue":11591910,"purple":8388736,"rebeccapurple":6697881,"red":16711680,"rosybrown":12357519,"royalblue":4286945,"saddlebrown":9127187,"salmon":16416882,"sandybrown":16032864,"seagreen":3050327,"seashell":16774638,"sienna":10506797,"silver":12632256,"skyblue":8900331,"slateblue":6970061,"slategray":7372944,"slategrey":7372944,"snow":16775930,"springgreen":65407,"steelblue":4620980,"tan":13808780,"teal":32896,"thistle":14204888,"tomato":16737095,"turquoise":4251856,"violet":15631086,"wheat":16113331,"white":16777215,"whitesmoke":16119285,"yellow":16776960,"yellowgreen":10145074};var _rgb={r:0,g:0,b:0};var _hslA={h:0,s:0,l:0};var _hslB={h:0,s:0,l:0};function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*6*(2/3-t);return p}function toComponents(source,target){target.r=source.r;target.g=source.g;target.b=source.b;return target}var Color=class{constructor(r,g,b){this.isColor=true;this.r=1;this.g=1;this.b=1;if(g===void 0&&b===void 0){return this.set(r)}return this.setRGB(r,g,b)}set(value){if(value&&value.isColor){this.copy(value)}else if(typeof value==="number"){this.setHex(value)}else if(typeof value==="string"){this.setStyle(value)}return this}setScalar(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this}setHex(hex,colorSpace=SRGBColorSpace){hex=Math.floor(hex);this.r=(hex>>16&255)/255;this.g=(hex>>8&255)/255;this.b=(hex&255)/255;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}setRGB(r,g,b,colorSpace=LinearSRGBColorSpace){this.r=r;this.g=g;this.b=b;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}setHSL(h,s,l,colorSpace=LinearSRGBColorSpace){h=euclideanModulo(h,1);s=clamp(s,0,1);l=clamp(l,0,1);if(s===0){this.r=this.g=this.b=l}else{const p=l<=.5?l*(1+s):l+s-l*s;const q=2*l-p;this.r=hue2rgb(q,p,h+1/3);this.g=hue2rgb(q,p,h);this.b=hue2rgb(q,p,h-1/3)}ColorManagement.toWorkingColorSpace(this,colorSpace);return this}setStyle(style,colorSpace=SRGBColorSpace){function handleAlpha(string){if(string===void 0)return;if(parseFloat(string)<1){console.warn("THREE.Color: Alpha component of "+style+" will be ignored.")}}let m;if(m=/^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)){let color;const name=m[1];const components=m[2];switch(name){case"rgb":case"rgba":if(color=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){this.r=Math.min(255,parseInt(color[1],10))/255;this.g=Math.min(255,parseInt(color[2],10))/255;this.b=Math.min(255,parseInt(color[3],10))/255;ColorManagement.toWorkingColorSpace(this,colorSpace);handleAlpha(color[4]);return this}if(color=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){this.r=Math.min(100,parseInt(color[1],10))/100;this.g=Math.min(100,parseInt(color[2],10))/100;this.b=Math.min(100,parseInt(color[3],10))/100;ColorManagement.toWorkingColorSpace(this,colorSpace);handleAlpha(color[4]);return this}break;case"hsl":case"hsla":if(color=/^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){const h=parseFloat(color[1])/360;const s=parseInt(color[2],10)/100;const l=parseInt(color[3],10)/100;handleAlpha(color[4]);return this.setHSL(h,s,l,colorSpace)}break}}else if(m=/^\#([A-Fa-f\d]+)$/.exec(style)){const hex=m[1];const size=hex.length;if(size===3){this.r=parseInt(hex.charAt(0)+hex.charAt(0),16)/255;this.g=parseInt(hex.charAt(1)+hex.charAt(1),16)/255;this.b=parseInt(hex.charAt(2)+hex.charAt(2),16)/255;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}else if(size===6){this.r=parseInt(hex.charAt(0)+hex.charAt(1),16)/255;this.g=parseInt(hex.charAt(2)+hex.charAt(3),16)/255;this.b=parseInt(hex.charAt(4)+hex.charAt(5),16)/255;ColorManagement.toWorkingColorSpace(this,colorSpace);return this}}if(style&&style.length>0){return this.setColorName(style,colorSpace)}return this}setColorName(style,colorSpace=SRGBColorSpace){const hex=_colorKeywords[style.toLowerCase()];if(hex!==void 0){this.setHex(hex,colorSpace)}else{console.warn("THREE.Color: Unknown color "+style)}return this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this}copySRGBToLinear(color){this.r=SRGBToLinear(color.r);this.g=SRGBToLinear(color.g);this.b=SRGBToLinear(color.b);return this}copyLinearToSRGB(color){this.r=LinearToSRGB(color.r);this.g=LinearToSRGB(color.g);this.b=LinearToSRGB(color.b);return this}convertSRGBToLinear(){this.copySRGBToLinear(this);return this}convertLinearToSRGB(){this.copyLinearToSRGB(this);return this}getHex(colorSpace=SRGBColorSpace){ColorManagement.fromWorkingColorSpace(toComponents(this,_rgb),colorSpace);return clamp(_rgb.r*255,0,255)<<16^clamp(_rgb.g*255,0,255)<<8^clamp(_rgb.b*255,0,255)<<0}getHexString(colorSpace=SRGBColorSpace){return("000000"+this.getHex(colorSpace).toString(16)).slice(-6)}getHSL(target,colorSpace=LinearSRGBColorSpace){ColorManagement.fromWorkingColorSpace(toComponents(this,_rgb),colorSpace);const r=_rgb.r,g=_rgb.g,b=_rgb.b;const max=Math.max(r,g,b);const min=Math.min(r,g,b);let hue,saturation;const lightness=(min+max)/2;if(min===max){hue=0;saturation=0}else{const delta=max-min;saturation=lightness<=.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g2048||canvas.height>2048){console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",image);return canvas.toDataURL("image/jpeg",.6)}else{return canvas.toDataURL("image/png")}}static sRGBToLinear(image){if(typeof HTMLImageElement!=="undefined"&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&image instanceof ImageBitmap){const canvas=createElementNS("canvas");canvas.width=image.width;canvas.height=image.height;const context=canvas.getContext("2d");context.drawImage(image,0,0,image.width,image.height);const imageData=context.getImageData(0,0,image.width,image.height);const data=imageData.data;for(let i=0;i1){switch(this.wrapS){case RepeatWrapping:uv.x=uv.x-Math.floor(uv.x);break;case ClampToEdgeWrapping:uv.x=uv.x<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.x)%2)===1){uv.x=Math.ceil(uv.x)-uv.x}else{uv.x=uv.x-Math.floor(uv.x)}break}}if(uv.y<0||uv.y>1){switch(this.wrapT){case RepeatWrapping:uv.y=uv.y-Math.floor(uv.y);break;case ClampToEdgeWrapping:uv.y=uv.y<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.y)%2)===1){uv.y=Math.ceil(uv.y)-uv.y}else{uv.y=uv.y-Math.floor(uv.y)}break}}if(this.flipY){uv.y=1-uv.y}return uv}set needsUpdate(value){if(value===true){this.version++;this.source.needsUpdate=true}}};Texture.DEFAULT_IMAGE=null;Texture.DEFAULT_MAPPING=UVMapping;var Vector4=class{constructor(x2=0,y2=0,z=0,w=1){Vector4.prototype.isVector4=true;this.x=x2;this.y=y2;this.z=z;this.w=w}get width(){return this.z}set width(value){this.z=value}get height(){return this.w}set height(value){this.w=value}set(x2,y2,z,w){this.x=x2;this.y=y2;this.z=z;this.w=w;return this}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this}setX(x2){this.x=x2;return this}setY(y2){this.y=y2;return this}setZ(z){this.z=z;return this}setW(w){this.w=w;return this}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;case 3:this.w=value;break;default:throw new Error("index is out of range: "+index)}return this}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+index)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;this.w=v.w!==void 0?v.w:1;return this}add(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;this.w+=v.w;return this}addScalar(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;this.w+=v.w*s;return this}sub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;this.w-=v.w;return this}subScalar(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this}multiply(v){this.x*=v.x;this.y*=v.y;this.z*=v.z;this.w*=v.w;return this}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this}applyMatrix4(m){const x2=this.x,y2=this.y,z=this.z,w=this.w;const e=m.elements;this.x=e[0]*x2+e[4]*y2+e[8]*z+e[12]*w;this.y=e[1]*x2+e[5]*y2+e[9]*z+e[13]*w;this.z=e[2]*x2+e[6]*y2+e[10]*z+e[14]*w;this.w=e[3]*x2+e[7]*y2+e[11]*z+e[15]*w;return this}divideScalar(scalar){return this.multiplyScalar(1/scalar)}setAxisAngleFromQuaternion(q){this.w=2*Math.acos(q.w);const s=Math.sqrt(1-q.w*q.w);if(s<1e-4){this.x=1;this.y=0;this.z=0}else{this.x=q.x/s;this.y=q.y/s;this.z=q.z/s}return this}setAxisAngleFromRotationMatrix(m){let angle,x2,y2,z;const epsilon=.01,epsilon2=.1,te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10];if(Math.abs(m12-m21)yy&&xx>zz){if(xxzz){if(yy=0?1:-1,sqrSin=1-cos*cos;if(sqrSin>Number.EPSILON){const sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin}const tDir=t*dir;x0=x0*s+x1*tDir;y0=y0*s+y1*tDir;z0=z0*s+z1*tDir;w0=w0*s+w1*tDir;if(s===1-t){const f=1/Math.sqrt(x0*x0+y0*y0+z0*z0+w0*w0);x0*=f;y0*=f;z0*=f;w0*=f}}dst[dstOffset]=x0;dst[dstOffset+1]=y0;dst[dstOffset+2]=z0;dst[dstOffset+3]=w0}static multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){const x0=src0[srcOffset0];const y0=src0[srcOffset0+1];const z0=src0[srcOffset0+2];const w0=src0[srcOffset0+3];const x1=src1[srcOffset1];const y1=src1[srcOffset1+1];const z1=src1[srcOffset1+2];const w1=src1[srcOffset1+3];dst[dstOffset]=x0*w1+w0*x1+y0*z1-z0*y1;dst[dstOffset+1]=y0*w1+w0*y1+z0*x1-x0*z1;dst[dstOffset+2]=z0*w1+w0*z1+x0*y1-y0*x1;dst[dstOffset+3]=w0*w1-x0*x1-y0*y1-z0*z1;return dst}get x(){return this._x}set x(value){this._x=value;this._onChangeCallback()}get y(){return this._y}set y(value){this._y=value;this._onChangeCallback()}get z(){return this._z}set z(value){this._z=value;this._onChangeCallback()}get w(){return this._w}set w(value){this._w=value;this._onChangeCallback()}set(x2,y2,z,w){this._x=x2;this._y=y2;this._z=z;this._w=w;this._onChangeCallback();return this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this}setFromEuler(euler,update){if(!(euler&&euler.isEuler)){throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.")}const x2=euler._x,y2=euler._y,z=euler._z,order=euler._order;const cos=Math.cos;const sin=Math.sin;const c1=cos(x2/2);const c2=cos(y2/2);const c3=cos(z/2);const s1=sin(x2/2);const s2=sin(y2/2);const s3=sin(z/2);switch(order){case"XYZ":this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case"YXZ":this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case"ZXY":this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case"ZYX":this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case"YZX":this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case"XZY":this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+order)}if(update!==false)this._onChangeCallback();return this}setFromAxisAngle(axis,angle){const halfAngle=angle/2,s=Math.sin(halfAngle);this._x=axis.x*s;this._y=axis.y*s;this._z=axis.z*s;this._w=Math.cos(halfAngle);this._onChangeCallback();return this}setFromRotationMatrix(m){const te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10],trace=m11+m22+m33;if(trace>0){const s=.5/Math.sqrt(trace+1);this._w=.25/s;this._x=(m32-m23)*s;this._y=(m13-m31)*s;this._z=(m21-m12)*s}else if(m11>m22&&m11>m33){const s=2*Math.sqrt(1+m11-m22-m33);this._w=(m32-m23)/s;this._x=.25*s;this._y=(m12+m21)/s;this._z=(m13+m31)/s}else if(m22>m33){const s=2*Math.sqrt(1+m22-m11-m33);this._w=(m13-m31)/s;this._x=(m12+m21)/s;this._y=.25*s;this._z=(m23+m32)/s}else{const s=2*Math.sqrt(1+m33-m11-m22);this._w=(m21-m12)/s;this._x=(m13+m31)/s;this._y=(m23+m32)/s;this._z=.25*s}this._onChangeCallback();return this}setFromUnitVectors(vFrom,vTo){let r=vFrom.dot(vTo)+1;if(rMath.abs(vFrom.z)){this._x=-vFrom.y;this._y=vFrom.x;this._z=0;this._w=r}else{this._x=0;this._y=-vFrom.z;this._z=vFrom.y;this._w=r}}else{this._x=vFrom.y*vTo.z-vFrom.z*vTo.y;this._y=vFrom.z*vTo.x-vFrom.x*vTo.z;this._z=vFrom.x*vTo.y-vFrom.y*vTo.x;this._w=r}return this.normalize()}angleTo(q){return 2*Math.acos(Math.abs(clamp(this.dot(q),-1,1)))}rotateTowards(q,step){const angle=this.angleTo(q);if(angle===0)return this;const t=Math.min(1,step/angle);this.slerp(q,t);return this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this}dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let l=this.length();if(l===0){this._x=0;this._y=0;this._z=0;this._w=1}else{l=1/l;this._x=this._x*l;this._y=this._y*l;this._z=this._z*l;this._w=this._w*l}this._onChangeCallback();return this}multiply(q){return this.multiplyQuaternions(this,q)}premultiply(q){return this.multiplyQuaternions(q,this)}multiplyQuaternions(a,b){const qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;const qbx=b._x,qby=b._y,qbz=b._z,qbw=b._w;this._x=qax*qbw+qaw*qbx+qay*qbz-qaz*qby;this._y=qay*qbw+qaw*qby+qaz*qbx-qax*qbz;this._z=qaz*qbw+qaw*qbz+qax*qby-qay*qbx;this._w=qaw*qbw-qax*qbx-qay*qby-qaz*qbz;this._onChangeCallback();return this}slerp(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);const x2=this._x,y2=this._y,z=this._z,w=this._w;let cosHalfTheta=w*qb._w+x2*qb._x+y2*qb._y+z*qb._z;if(cosHalfTheta<0){this._w=-qb._w;this._x=-qb._x;this._y=-qb._y;this._z=-qb._z;cosHalfTheta=-cosHalfTheta}else{this.copy(qb)}if(cosHalfTheta>=1){this._w=w;this._x=x2;this._y=y2;this._z=z;return this}const sqrSinHalfTheta=1-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){const s=1-t;this._w=s*w+t*this._w;this._x=s*x2+t*this._x;this._y=s*y2+t*this._y;this._z=s*z+t*this._z;this.normalize();this._onChangeCallback();return this}const sinHalfTheta=Math.sqrt(sqrSinHalfTheta);const halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);const ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;this._w=w*ratioA+this._w*ratioB;this._x=x2*ratioA+this._x*ratioB;this._y=y2*ratioA+this._y*ratioB;this._z=z*ratioA+this._z*ratioB;this._onChangeCallback();return this}slerpQuaternions(qa,qb,t){return this.copy(qa).slerp(qb,t)}random(){const u1=Math.random();const sqrt1u1=Math.sqrt(1-u1);const sqrtu1=Math.sqrt(u1);const u2=2*Math.PI*Math.random();const u3=2*Math.PI*Math.random();return this.set(sqrt1u1*Math.cos(u2),sqrtu1*Math.sin(u3),sqrtu1*Math.cos(u3),sqrt1u1*Math.sin(u2))}equals(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w}fromArray(array,offset=0){this._x=array[offset];this._y=array[offset+1];this._z=array[offset+2];this._w=array[offset+3];this._onChangeCallback();return this}toArray(array=[],offset=0){array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._w;return array}fromBufferAttribute(attribute,index){this._x=attribute.getX(index);this._y=attribute.getY(index);this._z=attribute.getZ(index);this._w=attribute.getW(index);return this}_onChange(callback){this._onChangeCallback=callback;return this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x;yield this._y;yield this._z;yield this._w}};var Vector3=class{constructor(x2=0,y2=0,z=0){Vector3.prototype.isVector3=true;this.x=x2;this.y=y2;this.z=z}set(x2,y2,z){if(z===void 0)z=this.z;this.x=x2;this.y=y2;this.z=z;return this}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this}setX(x2){this.x=x2;return this}setY(y2){this.y=y2;return this}setZ(z){this.z=z;return this}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;default:throw new Error("index is out of range: "+index)}return this}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+index)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this}add(v){this.x+=v.x;this.y+=v.y;this.z+=v.z;return this}addScalar(s){this.x+=s;this.y+=s;this.z+=s;return this}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this}sub(v){this.x-=v.x;this.y-=v.y;this.z-=v.z;return this}subScalar(s){this.x-=s;this.y-=s;this.z-=s;return this}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this}multiply(v){this.x*=v.x;this.y*=v.y;this.z*=v.z;return this}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this}multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this}applyEuler(euler){return this.applyQuaternion(_quaternion$4.setFromEuler(euler))}applyAxisAngle(axis,angle){return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis,angle))}applyMatrix3(m){const x2=this.x,y2=this.y,z=this.z;const e=m.elements;this.x=e[0]*x2+e[3]*y2+e[6]*z;this.y=e[1]*x2+e[4]*y2+e[7]*z;this.z=e[2]*x2+e[5]*y2+e[8]*z;return this}applyNormalMatrix(m){return this.applyMatrix3(m).normalize()}applyMatrix4(m){const x2=this.x,y2=this.y,z=this.z;const e=m.elements;const w=1/(e[3]*x2+e[7]*y2+e[11]*z+e[15]);this.x=(e[0]*x2+e[4]*y2+e[8]*z+e[12])*w;this.y=(e[1]*x2+e[5]*y2+e[9]*z+e[13])*w;this.z=(e[2]*x2+e[6]*y2+e[10]*z+e[14])*w;return this}applyQuaternion(q){const x2=this.x,y2=this.y,z=this.z;const qx=q.x,qy=q.y,qz=q.z,qw=q.w;const ix=qw*x2+qy*z-qz*y2;const iy=qw*y2+qz*x2-qx*z;const iz=qw*z+qx*y2-qy*x2;const iw=-qx*x2-qy*y2-qz*z;this.x=ix*qw+iw*-qx+iy*-qz-iz*-qy;this.y=iy*qw+iw*-qy+iz*-qx-ix*-qz;this.z=iz*qw+iw*-qz+ix*-qy-iy*-qx;return this}project(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix)}unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld)}transformDirection(m){const x2=this.x,y2=this.y,z=this.z;const e=m.elements;this.x=e[0]*x2+e[4]*y2+e[8]*z;this.y=e[1]*x2+e[5]*y2+e[9]*z;this.z=e[2]*x2+e[6]*y2+e[10]*z;return this.normalize()}divide(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this}divideScalar(scalar){return this.multiplyScalar(1/scalar)}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);return this}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);return this}clamp(min,max){this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));return this}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));this.z=Math.max(minVal,Math.min(maxVal,this.z));return this}clampLength(min,max){const length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)))}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);return this}negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this}dot(v){return this.x*v.x+this.y*v.y+this.z*v.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(length){return this.normalize().multiplyScalar(length)}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;return this}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;this.z=v1.z+(v2.z-v1.z)*alpha;return this}cross(v){return this.crossVectors(this,v)}crossVectors(a,b){const ax=a.x,ay=a.y,az=a.z;const bx=b.x,by=b.y,bz=b.z;this.x=ay*bz-az*by;this.y=az*bx-ax*bz;this.z=ax*by-ay*bx;return this}projectOnVector(v){const denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);const scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar)}projectOnPlane(planeNormal){_vector$c.copy(this).projectOnVector(planeNormal);return this.sub(_vector$c)}reflect(normal){return this.sub(_vector$c.copy(normal).multiplyScalar(2*this.dot(normal)))}angleTo(v){const denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;const theta=this.dot(v)/denominator;return Math.acos(clamp(theta,-1,1))}distanceTo(v){return Math.sqrt(this.distanceToSquared(v))}distanceToSquared(v){const dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z)}setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta)}setFromSphericalCoords(radius,phi,theta){const sinPhiRadius=Math.sin(phi)*radius;this.x=sinPhiRadius*Math.sin(theta);this.y=Math.cos(phi)*radius;this.z=sinPhiRadius*Math.cos(theta);return this}setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y)}setFromCylindricalCoords(radius,theta,y2){this.x=radius*Math.sin(theta);this.y=y2;this.z=radius*Math.cos(theta);return this}setFromMatrixPosition(m){const e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this}setFromMatrixScale(m){const sx=this.setFromMatrixColumn(m,0).length();const sy=this.setFromMatrixColumn(m,1).length();const sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this}setFromMatrixColumn(m,index){return this.fromArray(m.elements,index*4)}setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3)}setFromEuler(e){this.x=e._x;this.y=e._y;this.z=e._z;return this}equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z}fromArray(array,offset=0){this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];return this}toArray(array=[],offset=0){array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;return array}fromBufferAttribute(attribute,index){this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);return this}random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this}randomDirection(){const u=(Math.random()-.5)*2;const t=Math.random()*Math.PI*2;const f=Math.sqrt(1-u**2);this.x=f*Math.cos(t);this.y=f*Math.sin(t);this.z=u;return this}*[Symbol.iterator](){yield this.x;yield this.y;yield this.z}};var _vector$c=new Vector3;var _quaternion$4=new Quaternion;var Box3=class{constructor(min=new Vector3(Infinity,Infinity,Infinity),max=new Vector3(-Infinity,-Infinity,-Infinity)){this.isBox3=true;this.min=min;this.max=max}set(min,max){this.min.copy(min);this.max.copy(max);return this}setFromArray(array){let minX=Infinity;let minY=Infinity;let minZ=Infinity;let maxX=-Infinity;let maxY=-Infinity;let maxZ=-Infinity;for(let i=0,l=array.length;imaxX)maxX=x2;if(y2>maxY)maxY=y2;if(z>maxZ)maxZ=z}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this}setFromBufferAttribute(attribute){let minX=Infinity;let minY=Infinity;let minZ=Infinity;let maxX=-Infinity;let maxY=-Infinity;let maxZ=-Infinity;for(let i=0,l=attribute.count;imaxX)maxX=x2;if(y2>maxY)maxY=y2;if(z>maxZ)maxZ=z}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this}setFromPoints(points){this.makeEmpty();for(let i=0,il=points.length;ithis.max.x||point.ythis.max.y||point.zthis.max.z?false:true}containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y&&this.min.z<=box.min.z&&box.max.z<=this.max.z}getParameter(point,target){return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y),(point.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(box){return box.max.xthis.max.x||box.max.ythis.max.y||box.max.zthis.max.z?false:true}intersectsSphere(sphere){this.clampPoint(sphere.center,_vector$b);return _vector$b.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius}intersectsPlane(plane){let min,max;if(plane.normal.x>0){min=plane.normal.x*this.min.x;max=plane.normal.x*this.max.x}else{min=plane.normal.x*this.max.x;max=plane.normal.x*this.min.x}if(plane.normal.y>0){min+=plane.normal.y*this.min.y;max+=plane.normal.y*this.max.y}else{min+=plane.normal.y*this.max.y;max+=plane.normal.y*this.min.y}if(plane.normal.z>0){min+=plane.normal.z*this.min.z;max+=plane.normal.z*this.max.z}else{min+=plane.normal.z*this.max.z;max+=plane.normal.z*this.min.z}return min<=-plane.constant&&max>=-plane.constant}intersectsTriangle(triangle){if(this.isEmpty()){return false}this.getCenter(_center);_extents.subVectors(this.max,_center);_v0$2.subVectors(triangle.a,_center);_v1$7.subVectors(triangle.b,_center);_v2$3.subVectors(triangle.c,_center);_f0.subVectors(_v1$7,_v0$2);_f1.subVectors(_v2$3,_v1$7);_f2.subVectors(_v0$2,_v2$3);let axes=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];if(!satForAxes(axes,_v0$2,_v1$7,_v2$3,_extents)){return false}axes=[1,0,0,0,1,0,0,0,1];if(!satForAxes(axes,_v0$2,_v1$7,_v2$3,_extents)){return false}_triangleNormal.crossVectors(_f0,_f1);axes=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z];return satForAxes(axes,_v0$2,_v1$7,_v2$3,_extents)}clampPoint(point,target){return target.copy(point).clamp(this.min,this.max)}distanceToPoint(point){const clampedPoint=_vector$b.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length()}getBoundingSphere(target){this.getCenter(target.center);target.radius=this.getSize(_vector$b).length()*.5;return target}intersect(box){this.min.max(box.min);this.max.min(box.max);if(this.isEmpty())this.makeEmpty();return this}union(box){this.min.min(box.min);this.max.max(box.max);return this}applyMatrix4(matrix){if(this.isEmpty())return this;_points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);_points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);_points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);_points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);_points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);_points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);_points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);_points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);this.setFromPoints(_points);return this}translate(offset){this.min.add(offset);this.max.add(offset);return this}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max)}};var _points=[new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3,new Vector3];var _vector$b=new Vector3;var _box$3=new Box3;var _v0$2=new Vector3;var _v1$7=new Vector3;var _v2$3=new Vector3;var _f0=new Vector3;var _f1=new Vector3;var _f2=new Vector3;var _center=new Vector3;var _extents=new Vector3;var _triangleNormal=new Vector3;var _testAxis=new Vector3;function satForAxes(axes,v0,v1,v2,extents){for(let i=0,j=axes.length-3;i<=j;i+=3){_testAxis.fromArray(axes,i);const r=extents.x*Math.abs(_testAxis.x)+extents.y*Math.abs(_testAxis.y)+extents.z*Math.abs(_testAxis.z);const p0=v0.dot(_testAxis);const p1=v1.dot(_testAxis);const p2=v2.dot(_testAxis);if(Math.max(-Math.max(p0,p1,p2),Math.min(p0,p1,p2))>r){return false}}return true}var _box$2=new Box3;var _v1$6=new Vector3;var _toFarthestPoint=new Vector3;var _toPoint=new Vector3;var Sphere=class{constructor(center=new Vector3,radius=-1){this.center=center;this.radius=radius}set(center,radius){this.center.copy(center);this.radius=radius;return this}setFromPoints(points,optionalCenter){const center=this.center;if(optionalCenter!==void 0){center.copy(optionalCenter)}else{_box$2.setFromPoints(points).getCenter(center)}let maxRadiusSq=0;for(let i=0,il=points.length;ithis.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center)}return target}getBoundingBox(target){if(this.isEmpty()){target.makeEmpty();return target}target.set(this.center,this.center);target.expandByScalar(this.radius);return target}applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this}translate(offset){this.center.add(offset);return this}expandByPoint(point){_toPoint.subVectors(point,this.center);const lengthSq=_toPoint.lengthSq();if(lengthSq>this.radius*this.radius){const length=Math.sqrt(lengthSq);const missingRadiusHalf=(length-this.radius)*.5;this.center.add(_toPoint.multiplyScalar(missingRadiusHalf/length));this.radius+=missingRadiusHalf}return this}union(sphere){if(this.center.equals(sphere.center)===true){_toFarthestPoint.set(0,0,1).multiplyScalar(sphere.radius)}else{_toFarthestPoint.subVectors(sphere.center,this.center).normalize().multiplyScalar(sphere.radius)}this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));return this}equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius}clone(){return new this.constructor().copy(this)}};var _vector$a=new Vector3;var _segCenter=new Vector3;var _segDir=new Vector3;var _diff=new Vector3;var _edge1=new Vector3;var _edge2=new Vector3;var _normal$1=new Vector3;var Ray=class{constructor(origin=new Vector3,direction=new Vector3(0,0,-1)){this.origin=origin;this.direction=direction}set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this}copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this}at(t,target){return target.copy(this.direction).multiplyScalar(t).add(this.origin)}lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this}recast(t){this.origin.copy(this.at(t,_vector$a));return this}closestPointToPoint(point,target){target.subVectors(point,this.origin);const directionDistance=target.dot(this.direction);if(directionDistance<0){return target.copy(this.origin)}return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin)}distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point))}distanceSqToPoint(point){const directionDistance=_vector$a.subVectors(point,this.origin).dot(this.direction);if(directionDistance<0){return this.origin.distanceToSquared(point)}_vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return _vector$a.distanceToSquared(point)}distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment){_segCenter.copy(v0).add(v1).multiplyScalar(.5);_segDir.copy(v1).sub(v0).normalize();_diff.copy(this.origin).sub(_segCenter);const segExtent=v0.distanceTo(v1)*.5;const a01=-this.direction.dot(_segDir);const b0=_diff.dot(this.direction);const b1=-_diff.dot(_segDir);const c=_diff.lengthSq();const det=Math.abs(1-a01*a01);let s0,s1,sqrDist,extDet;if(det>0){s0=a01*b1-b0;s1=a01*b0-b1;extDet=segExtent*det;if(s0>=0){if(s1>=-extDet){if(s1<=extDet){const invDet=1/det;s0*=invDet;s1*=invDet;sqrDist=s0*(s0+a01*s1+2*b0)+s1*(a01*s0+s1+2*b1)+c}else{s1=segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}}else{s1=-segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}}else{if(s1<=-extDet){s0=Math.max(0,-(-a01*segExtent+b0));s1=s0>0?-segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c}else if(s1<=extDet){s0=0;s1=Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=s1*(s1+2*b1)+c}else{s0=Math.max(0,-(a01*segExtent+b0));s1=s0>0?segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c}}}else{s1=a01>0?-segExtent:segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c}if(optionalPointOnRay){optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin)}if(optionalPointOnSegment){optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter)}return sqrDist}intersectSphere(sphere,target){_vector$a.subVectors(sphere.center,this.origin);const tca=_vector$a.dot(this.direction);const d2=_vector$a.dot(_vector$a)-tca*tca;const radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;const thc=Math.sqrt(radius2-d2);const t0=tca-thc;const t1=tca+thc;if(t0<0&&t1<0)return null;if(t0<0)return this.at(t1,target);return this.at(t0,target)}intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius}distanceToPlane(plane){const denominator=plane.normal.dot(this.direction);if(denominator===0){if(plane.distanceToPoint(this.origin)===0){return 0}return null}const t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;return t>=0?t:null}intersectPlane(plane,target){const t=this.distanceToPlane(plane);if(t===null){return null}return this.at(t,target)}intersectsPlane(plane){const distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true}const denominator=plane.normal.dot(this.direction);if(denominator*distToPoint<0){return true}return false}intersectBox(box,target){let tmin,tmax,tymin,tymax,tzmin,tzmax;const invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;const origin=this.origin;if(invdirx>=0){tmin=(box.min.x-origin.x)*invdirx;tmax=(box.max.x-origin.x)*invdirx}else{tmin=(box.max.x-origin.x)*invdirx;tmax=(box.min.x-origin.x)*invdirx}if(invdiry>=0){tymin=(box.min.y-origin.y)*invdiry;tymax=(box.max.y-origin.y)*invdiry}else{tymin=(box.max.y-origin.y)*invdiry;tymax=(box.min.y-origin.y)*invdiry}if(tmin>tymax||tymin>tmax)return null;if(tymin>tmin||tmin!==tmin)tmin=tymin;if(tymax=0){tzmin=(box.min.z-origin.z)*invdirz;tzmax=(box.max.z-origin.z)*invdirz}else{tzmin=(box.max.z-origin.z)*invdirz;tzmax=(box.min.z-origin.z)*invdirz}if(tmin>tzmax||tzmin>tmax)return null;if(tzmin>tmin||tmin!==tmin)tmin=tzmin;if(tzmax=0?tmin:tmax,target)}intersectsBox(box){return this.intersectBox(box,_vector$a)!==null}intersectTriangle(a,b,c,backfaceCulling,target){_edge1.subVectors(b,a);_edge2.subVectors(c,a);_normal$1.crossVectors(_edge1,_edge2);let DdN=this.direction.dot(_normal$1);let sign2;if(DdN>0){if(backfaceCulling)return null;sign2=1}else if(DdN<0){sign2=-1;DdN=-DdN}else{return null}_diff.subVectors(this.origin,a);const DdQxE2=sign2*this.direction.dot(_edge2.crossVectors(_diff,_edge2));if(DdQxE2<0){return null}const DdE1xQ=sign2*this.direction.dot(_edge1.cross(_diff));if(DdE1xQ<0){return null}if(DdQxE2+DdE1xQ>DdN){return null}const QdN=-sign2*_diff.dot(_normal$1);if(QdN<0){return null}return this.at(QdN/DdN,target)}applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this}equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}};var Matrix4=class{constructor(){Matrix4.prototype.isMatrix4=true;this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}set(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){const te=this.elements;te[0]=n11;te[4]=n12;te[8]=n13;te[12]=n14;te[1]=n21;te[5]=n22;te[9]=n23;te[13]=n24;te[2]=n31;te[6]=n32;te[10]=n33;te[14]=n34;te[3]=n41;te[7]=n42;te[11]=n43;te[15]=n44;return this}identity(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this}clone(){return new Matrix4().fromArray(this.elements)}copy(m){const te=this.elements;const me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];te[9]=me[9];te[10]=me[10];te[11]=me[11];te[12]=me[12];te[13]=me[13];te[14]=me[14];te[15]=me[15];return this}copyPosition(m){const te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this}setFromMatrix3(m){const me=m.elements;this.set(me[0],me[3],me[6],0,me[1],me[4],me[7],0,me[2],me[5],me[8],0,0,0,0,1);return this}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this}makeBasis(xAxis,yAxis,zAxis){this.set(xAxis.x,yAxis.x,zAxis.x,0,xAxis.y,yAxis.y,zAxis.y,0,xAxis.z,yAxis.z,zAxis.z,0,0,0,0,1);return this}extractRotation(m){const te=this.elements;const me=m.elements;const scaleX=1/_v1$5.setFromMatrixColumn(m,0).length();const scaleY=1/_v1$5.setFromMatrixColumn(m,1).length();const scaleZ=1/_v1$5.setFromMatrixColumn(m,2).length();te[0]=me[0]*scaleX;te[1]=me[1]*scaleX;te[2]=me[2]*scaleX;te[3]=0;te[4]=me[4]*scaleY;te[5]=me[5]*scaleY;te[6]=me[6]*scaleY;te[7]=0;te[8]=me[8]*scaleZ;te[9]=me[9]*scaleZ;te[10]=me[10]*scaleZ;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this}makeRotationFromEuler(euler){const te=this.elements;const x2=euler.x,y2=euler.y,z=euler.z;const a=Math.cos(x2),b=Math.sin(x2);const c=Math.cos(y2),d=Math.sin(y2);const e=Math.cos(z),f=Math.sin(z);if(euler.order==="XYZ"){const ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=-c*f;te[8]=d;te[1]=af+be*d;te[5]=ae-bf*d;te[9]=-b*c;te[2]=bf-ae*d;te[6]=be+af*d;te[10]=a*c}else if(euler.order==="YXZ"){const ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce+df*b;te[4]=de*b-cf;te[8]=a*d;te[1]=a*f;te[5]=a*e;te[9]=-b;te[2]=cf*b-de;te[6]=df+ce*b;te[10]=a*c}else if(euler.order==="ZXY"){const ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce-df*b;te[4]=-a*f;te[8]=de+cf*b;te[1]=cf+de*b;te[5]=a*e;te[9]=df-ce*b;te[2]=-a*d;te[6]=b;te[10]=a*c}else if(euler.order==="ZYX"){const ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=be*d-af;te[8]=ae*d+bf;te[1]=c*f;te[5]=bf*d+ae;te[9]=af*d-be;te[2]=-d;te[6]=b*c;te[10]=a*c}else if(euler.order==="YZX"){const ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=bd-ac*f;te[8]=bc*f+ad;te[1]=f;te[5]=a*e;te[9]=-b*e;te[2]=-d*e;te[6]=ad*f+bc;te[10]=ac-bd*f}else if(euler.order==="XZY"){const ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=-f;te[8]=d*e;te[1]=ac*f+bd;te[5]=a*e;te[9]=ad*f-bc;te[2]=bc*f-ad;te[6]=b*e;te[10]=bd*f+ac}te[3]=0;te[7]=0;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this}makeRotationFromQuaternion(q){return this.compose(_zero,q,_one)}lookAt(eye,target,up){const te=this.elements;_z.subVectors(eye,target);if(_z.lengthSq()===0){_z.z=1}_z.normalize();_x.crossVectors(up,_z);if(_x.lengthSq()===0){if(Math.abs(up.z)===1){_z.x+=1e-4}else{_z.z+=1e-4}_z.normalize();_x.crossVectors(up,_z)}_x.normalize();_y.crossVectors(_z,_x);te[0]=_x.x;te[4]=_y.x;te[8]=_z.x;te[1]=_x.y;te[5]=_y.y;te[9]=_z.y;te[2]=_x.z;te[6]=_y.z;te[10]=_z.z;return this}multiply(m){return this.multiplyMatrices(this,m)}premultiply(m){return this.multiplyMatrices(m,this)}multiplyMatrices(a,b){const ae=a.elements;const be=b.elements;const te=this.elements;const a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];const a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];const a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];const a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];const b11=be[0],b12=be[4],b13=be[8],b14=be[12];const b21=be[1],b22=be[5],b23=be[9],b24=be[13];const b31=be[2],b32=be[6],b33=be[10],b34=be[14];const b41=be[3],b42=be[7],b43=be[11],b44=be[15];te[0]=a11*b11+a12*b21+a13*b31+a14*b41;te[4]=a11*b12+a12*b22+a13*b32+a14*b42;te[8]=a11*b13+a12*b23+a13*b33+a14*b43;te[12]=a11*b14+a12*b24+a13*b34+a14*b44;te[1]=a21*b11+a22*b21+a23*b31+a24*b41;te[5]=a21*b12+a22*b22+a23*b32+a24*b42;te[9]=a21*b13+a22*b23+a23*b33+a24*b43;te[13]=a21*b14+a22*b24+a23*b34+a24*b44;te[2]=a31*b11+a32*b21+a33*b31+a34*b41;te[6]=a31*b12+a32*b22+a33*b32+a34*b42;te[10]=a31*b13+a32*b23+a33*b33+a34*b43;te[14]=a31*b14+a32*b24+a33*b34+a34*b44;te[3]=a41*b11+a42*b21+a43*b31+a44*b41;te[7]=a41*b12+a42*b22+a43*b32+a44*b42;te[11]=a41*b13+a42*b23+a43*b33+a44*b43;te[15]=a41*b14+a42*b24+a43*b34+a44*b44;return this}multiplyScalar(s){const te=this.elements;te[0]*=s;te[4]*=s;te[8]*=s;te[12]*=s;te[1]*=s;te[5]*=s;te[9]*=s;te[13]*=s;te[2]*=s;te[6]*=s;te[10]*=s;te[14]*=s;te[3]*=s;te[7]*=s;te[11]*=s;te[15]*=s;return this}determinant(){const te=this.elements;const n11=te[0],n12=te[4],n13=te[8],n14=te[12];const n21=te[1],n22=te[5],n23=te[9],n24=te[13];const n31=te[2],n32=te[6],n33=te[10],n34=te[14];const n41=te[3],n42=te[7],n43=te[11],n44=te[15];return n41*(+n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34)+n42*(+n11*n23*n34-n11*n24*n33+n14*n21*n33-n13*n21*n34+n13*n24*n31-n14*n23*n31)+n43*(+n11*n24*n32-n11*n22*n34-n14*n21*n32+n12*n21*n34+n14*n22*n31-n12*n24*n31)+n44*(-n13*n22*n31-n11*n23*n32+n11*n22*n33+n13*n21*n32-n12*n21*n33+n12*n23*n31)}transpose(){const te=this.elements;let tmp2;tmp2=te[1];te[1]=te[4];te[4]=tmp2;tmp2=te[2];te[2]=te[8];te[8]=tmp2;tmp2=te[6];te[6]=te[9];te[9]=tmp2;tmp2=te[3];te[3]=te[12];te[12]=tmp2;tmp2=te[7];te[7]=te[13];te[13]=tmp2;tmp2=te[11];te[11]=te[14];te[14]=tmp2;return this}setPosition(x2,y2,z){const te=this.elements;if(x2.isVector3){te[12]=x2.x;te[13]=x2.y;te[14]=x2.z}else{te[12]=x2;te[13]=y2;te[14]=z}return this}invert(){const te=this.elements,n11=te[0],n21=te[1],n31=te[2],n41=te[3],n12=te[4],n22=te[5],n32=te[6],n42=te[7],n13=te[8],n23=te[9],n33=te[10],n43=te[11],n14=te[12],n24=te[13],n34=te[14],n44=te[15],t11=n23*n34*n42-n24*n33*n42+n24*n32*n43-n22*n34*n43-n23*n32*n44+n22*n33*n44,t12=n14*n33*n42-n13*n34*n42-n14*n32*n43+n12*n34*n43+n13*n32*n44-n12*n33*n44,t13=n13*n24*n42-n14*n23*n42+n14*n22*n43-n12*n24*n43-n13*n22*n44+n12*n23*n44,t14=n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34;const det=n11*t11+n21*t12+n31*t13+n41*t14;if(det===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const detInv=1/det;te[0]=t11*detInv;te[1]=(n24*n33*n41-n23*n34*n41-n24*n31*n43+n21*n34*n43+n23*n31*n44-n21*n33*n44)*detInv;te[2]=(n22*n34*n41-n24*n32*n41+n24*n31*n42-n21*n34*n42-n22*n31*n44+n21*n32*n44)*detInv;te[3]=(n23*n32*n41-n22*n33*n41-n23*n31*n42+n21*n33*n42+n22*n31*n43-n21*n32*n43)*detInv;te[4]=t12*detInv;te[5]=(n13*n34*n41-n14*n33*n41+n14*n31*n43-n11*n34*n43-n13*n31*n44+n11*n33*n44)*detInv;te[6]=(n14*n32*n41-n12*n34*n41-n14*n31*n42+n11*n34*n42+n12*n31*n44-n11*n32*n44)*detInv;te[7]=(n12*n33*n41-n13*n32*n41+n13*n31*n42-n11*n33*n42-n12*n31*n43+n11*n32*n43)*detInv;te[8]=t13*detInv;te[9]=(n14*n23*n41-n13*n24*n41-n14*n21*n43+n11*n24*n43+n13*n21*n44-n11*n23*n44)*detInv;te[10]=(n12*n24*n41-n14*n22*n41+n14*n21*n42-n11*n24*n42-n12*n21*n44+n11*n22*n44)*detInv;te[11]=(n13*n22*n41-n12*n23*n41-n13*n21*n42+n11*n23*n42+n12*n21*n43-n11*n22*n43)*detInv;te[12]=t14*detInv;te[13]=(n13*n24*n31-n14*n23*n31+n14*n21*n33-n11*n24*n33-n13*n21*n34+n11*n23*n34)*detInv;te[14]=(n14*n22*n31-n12*n24*n31-n14*n21*n32+n11*n24*n32+n12*n21*n34-n11*n22*n34)*detInv;te[15]=(n12*n23*n31-n13*n22*n31+n13*n21*n32-n11*n23*n32-n12*n21*n33+n11*n22*n33)*detInv;return this}scale(v){const te=this.elements;const x2=v.x,y2=v.y,z=v.z;te[0]*=x2;te[4]*=y2;te[8]*=z;te[1]*=x2;te[5]*=y2;te[9]*=z;te[2]*=x2;te[6]*=y2;te[10]*=z;te[3]*=x2;te[7]*=y2;te[11]*=z;return this}getMaxScaleOnAxis(){const te=this.elements;const scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];const scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];const scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq))}makeTranslation(x2,y2,z){this.set(1,0,0,x2,0,1,0,y2,0,0,1,z,0,0,0,1);return this}makeRotationX(theta){const c=Math.cos(theta),s=Math.sin(theta);this.set(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);return this}makeRotationY(theta){const c=Math.cos(theta),s=Math.sin(theta);this.set(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);return this}makeRotationZ(theta){const c=Math.cos(theta),s=Math.sin(theta);this.set(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return this}makeRotationAxis(axis,angle){const c=Math.cos(angle);const s=Math.sin(angle);const t=1-c;const x2=axis.x,y2=axis.y,z=axis.z;const tx=t*x2,ty=t*y2;this.set(tx*x2+c,tx*y2-s*z,tx*z+s*y2,0,tx*y2+s*z,ty*y2+c,ty*z-s*x2,0,tx*z-s*y2,ty*z+s*x2,t*z*z+c,0,0,0,0,1);return this}makeScale(x2,y2,z){this.set(x2,0,0,0,0,y2,0,0,0,0,z,0,0,0,0,1);return this}makeShear(xy,xz,yx,yz,zx,zy){this.set(1,yx,zx,0,xy,1,zy,0,xz,yz,1,0,0,0,0,1);return this}compose(position,quaternion,scale){const te=this.elements;const x2=quaternion._x,y2=quaternion._y,z=quaternion._z,w=quaternion._w;const x22=x2+x2,y22=y2+y2,z2=z+z;const xx=x2*x22,xy=x2*y22,xz=x2*z2;const yy=y2*y22,yz=y2*z2,zz=z*z2;const wx=w*x22,wy=w*y22,wz=w*z2;const sx=scale.x,sy=scale.y,sz=scale.z;te[0]=(1-(yy+zz))*sx;te[1]=(xy+wz)*sx;te[2]=(xz-wy)*sx;te[3]=0;te[4]=(xy-wz)*sy;te[5]=(1-(xx+zz))*sy;te[6]=(yz+wx)*sy;te[7]=0;te[8]=(xz+wy)*sz;te[9]=(yz-wx)*sz;te[10]=(1-(xx+yy))*sz;te[11]=0;te[12]=position.x;te[13]=position.y;te[14]=position.z;te[15]=1;return this}decompose(position,quaternion,scale){const te=this.elements;let sx=_v1$5.set(te[0],te[1],te[2]).length();const sy=_v1$5.set(te[4],te[5],te[6]).length();const sz=_v1$5.set(te[8],te[9],te[10]).length();const det=this.determinant();if(det<0)sx=-sx;position.x=te[12];position.y=te[13];position.z=te[14];_m1$2.copy(this);const invSX=1/sx;const invSY=1/sy;const invSZ=1/sz;_m1$2.elements[0]*=invSX;_m1$2.elements[1]*=invSX;_m1$2.elements[2]*=invSX;_m1$2.elements[4]*=invSY;_m1$2.elements[5]*=invSY;_m1$2.elements[6]*=invSY;_m1$2.elements[8]*=invSZ;_m1$2.elements[9]*=invSZ;_m1$2.elements[10]*=invSZ;quaternion.setFromRotationMatrix(_m1$2);scale.x=sx;scale.y=sy;scale.z=sz;return this}makePerspective(left,right,top,bottom,near,far){const te=this.elements;const x2=2*near/(right-left);const y2=2*near/(top-bottom);const a=(right+left)/(right-left);const b=(top+bottom)/(top-bottom);const c=-(far+near)/(far-near);const d=-2*far*near/(far-near);te[0]=x2;te[4]=0;te[8]=a;te[12]=0;te[1]=0;te[5]=y2;te[9]=b;te[13]=0;te[2]=0;te[6]=0;te[10]=c;te[14]=d;te[3]=0;te[7]=0;te[11]=-1;te[15]=0;return this}makeOrthographic(left,right,top,bottom,near,far){const te=this.elements;const w=1/(right-left);const h=1/(top-bottom);const p=1/(far-near);const x2=(right+left)*w;const y2=(top+bottom)*h;const z=(far+near)*p;te[0]=2*w;te[4]=0;te[8]=0;te[12]=-x2;te[1]=0;te[5]=2*h;te[9]=0;te[13]=-y2;te[2]=0;te[6]=0;te[10]=-2*p;te[14]=-z;te[3]=0;te[7]=0;te[11]=0;te[15]=1;return this}equals(matrix){const te=this.elements;const me=matrix.elements;for(let i=0;i<16;i++){if(te[i]!==me[i])return false}return true}fromArray(array,offset=0){for(let i=0;i<16;i++){this.elements[i]=array[i+offset]}return this}toArray(array=[],offset=0){const te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];array[offset+9]=te[9];array[offset+10]=te[10];array[offset+11]=te[11];array[offset+12]=te[12];array[offset+13]=te[13];array[offset+14]=te[14];array[offset+15]=te[15];return array}};var _v1$5=new Vector3;var _m1$2=new Matrix4;var _zero=new Vector3(0,0,0);var _one=new Vector3(1,1,1);var _x=new Vector3;var _y=new Vector3;var _z=new Vector3;var _matrix$1=new Matrix4;var _quaternion$3=new Quaternion;var Euler=class{constructor(x2=0,y2=0,z=0,order=Euler.DefaultOrder){this.isEuler=true;this._x=x2;this._y=y2;this._z=z;this._order=order}get x(){return this._x}set x(value){this._x=value;this._onChangeCallback()}get y(){return this._y}set y(value){this._y=value;this._onChangeCallback()}get z(){return this._z}set z(value){this._z=value;this._onChangeCallback()}get order(){return this._order}set order(value){this._order=value;this._onChangeCallback()}set(x2,y2,z,order=this._order){this._x=x2;this._y=y2;this._z=z;this._order=order;this._onChangeCallback();return this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this}setFromRotationMatrix(m,order=this._order,update=true){const te=m.elements;const m11=te[0],m12=te[4],m13=te[8];const m21=te[1],m22=te[5],m23=te[9];const m31=te[2],m32=te[6],m33=te[10];switch(order){case"XYZ":this._y=Math.asin(clamp(m13,-1,1));if(Math.abs(m13)<.9999999){this._x=Math.atan2(-m23,m33);this._z=Math.atan2(-m12,m11)}else{this._x=Math.atan2(m32,m22);this._z=0}break;case"YXZ":this._x=Math.asin(-clamp(m23,-1,1));if(Math.abs(m23)<.9999999){this._y=Math.atan2(m13,m33);this._z=Math.atan2(m21,m22)}else{this._y=Math.atan2(-m31,m11);this._z=0}break;case"ZXY":this._x=Math.asin(clamp(m32,-1,1));if(Math.abs(m32)<.9999999){this._y=Math.atan2(-m31,m33);this._z=Math.atan2(-m12,m22)}else{this._y=0;this._z=Math.atan2(m21,m11)}break;case"ZYX":this._y=Math.asin(-clamp(m31,-1,1));if(Math.abs(m31)<.9999999){this._x=Math.atan2(m32,m33);this._z=Math.atan2(m21,m11)}else{this._x=0;this._z=Math.atan2(-m12,m22)}break;case"YZX":this._z=Math.asin(clamp(m21,-1,1));if(Math.abs(m21)<.9999999){this._x=Math.atan2(-m23,m22);this._y=Math.atan2(-m31,m11)}else{this._x=0;this._y=Math.atan2(m13,m33)}break;case"XZY":this._z=Math.asin(-clamp(m12,-1,1));if(Math.abs(m12)<.9999999){this._x=Math.atan2(m32,m22);this._y=Math.atan2(m13,m11)}else{this._x=Math.atan2(-m23,m33);this._y=0}break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+order)}this._order=order;if(update===true)this._onChangeCallback();return this}setFromQuaternion(q,order,update){_matrix$1.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix$1,order,update)}setFromVector3(v,order=this._order){return this.set(v.x,v.y,v.z,order)}reorder(newOrder){_quaternion$3.setFromEuler(this);return this.setFromQuaternion(_quaternion$3,newOrder)}equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order}fromArray(array){this._x=array[0];this._y=array[1];this._z=array[2];if(array[3]!==void 0)this._order=array[3];this._onChangeCallback();return this}toArray(array=[],offset=0){array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._order;return array}_onChange(callback){this._onChangeCallback=callback;return this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x;yield this._y;yield this._z;yield this._order}toVector3(){console.error("THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead")}};Euler.DefaultOrder="XYZ";Euler.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"];var Layers=class{constructor(){this.mask=1|0}set(channel){this.mask=(1<>>0}enable(channel){this.mask|=1<1){for(let i=0;i1){for(let i=0;i0){object.children=[];for(let i=0;i0){object.animations=[];for(let i=0;i0)output.geometries=geometries;if(materials.length>0)output.materials=materials;if(textures.length>0)output.textures=textures;if(images.length>0)output.images=images;if(shapes.length>0)output.shapes=shapes;if(skeletons.length>0)output.skeletons=skeletons;if(animations.length>0)output.animations=animations;if(nodes.length>0)output.nodes=nodes}output.object=object;return output;function extractFromCache(cache){const values=[];for(const key in cache){const data=cache[key];delete data.metadata;values.push(data)}return values}}clone(recursive){return new this.constructor().copy(this,recursive)}copy(source,recursive=true){this.name=source.name;this.up.copy(source.up);this.position.copy(source.position);this.rotation.order=source.rotation.order;this.quaternion.copy(source.quaternion);this.scale.copy(source.scale);this.matrix.copy(source.matrix);this.matrixWorld.copy(source.matrixWorld);this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrixWorldNeedsUpdate=source.matrixWorldNeedsUpdate;this.layers.mask=source.layers.mask;this.visible=source.visible;this.castShadow=source.castShadow;this.receiveShadow=source.receiveShadow;this.frustumCulled=source.frustumCulled;this.renderOrder=source.renderOrder;this.userData=JSON.parse(JSON.stringify(source.userData));if(recursive===true){for(let i=0;i0){return target.multiplyScalar(1/Math.sqrt(targetLengthSq))}return target.set(0,0,0)}static getBarycoord(point,a,b,c,target){_v0$1.subVectors(c,a);_v1$3.subVectors(b,a);_v2$2.subVectors(point,a);const dot00=_v0$1.dot(_v0$1);const dot01=_v0$1.dot(_v1$3);const dot02=_v0$1.dot(_v2$2);const dot11=_v1$3.dot(_v1$3);const dot12=_v1$3.dot(_v2$2);const denom=dot00*dot11-dot01*dot01;if(denom===0){return target.set(-2,-1,-1)}const invDenom=1/denom;const u=(dot11*dot02-dot01*dot12)*invDenom;const v=(dot00*dot12-dot01*dot02)*invDenom;return target.set(1-u-v,v,u)}static containsPoint(point,a,b,c){this.getBarycoord(point,a,b,c,_v3$1);return _v3$1.x>=0&&_v3$1.y>=0&&_v3$1.x+_v3$1.y<=1}static getUV(point,p1,p2,p3,uv1,uv2,uv3,target){this.getBarycoord(point,p1,p2,p3,_v3$1);target.set(0,0);target.addScaledVector(uv1,_v3$1.x);target.addScaledVector(uv2,_v3$1.y);target.addScaledVector(uv3,_v3$1.z);return target}static isFrontFacing(a,b,c,direction){_v0$1.subVectors(c,b);_v1$3.subVectors(a,b);return _v0$1.cross(_v1$3).dot(direction)<0?true:false}set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this}setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this}setFromAttributeAndIndices(attribute,i0,i1,i2){this.a.fromBufferAttribute(attribute,i0);this.b.fromBufferAttribute(attribute,i1);this.c.fromBufferAttribute(attribute,i2);return this}clone(){return new this.constructor().copy(this)}copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this}getArea(){_v0$1.subVectors(this.c,this.b);_v1$3.subVectors(this.a,this.b);return _v0$1.cross(_v1$3).length()*.5}getMidpoint(target){return target.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(target){return Triangle.getNormal(this.a,this.b,this.c,target)}getPlane(target){return target.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(point,target){return Triangle.getBarycoord(point,this.a,this.b,this.c,target)}getUV(point,uv1,uv2,uv3,target){return Triangle.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target)}containsPoint(point){return Triangle.containsPoint(point,this.a,this.b,this.c)}isFrontFacing(direction){return Triangle.isFrontFacing(this.a,this.b,this.c,direction)}intersectsBox(box){return box.intersectsTriangle(this)}closestPointToPoint(p,target){const a=this.a,b=this.b,c=this.c;let v,w;_vab.subVectors(b,a);_vac.subVectors(c,a);_vap.subVectors(p,a);const d1=_vab.dot(_vap);const d2=_vac.dot(_vap);if(d1<=0&&d2<=0){return target.copy(a)}_vbp.subVectors(p,b);const d3=_vab.dot(_vbp);const d4=_vac.dot(_vbp);if(d3>=0&&d4<=d3){return target.copy(b)}const vc=d1*d4-d3*d2;if(vc<=0&&d1>=0&&d3<=0){v=d1/(d1-d3);return target.copy(a).addScaledVector(_vab,v)}_vcp.subVectors(p,c);const d5=_vab.dot(_vcp);const d6=_vac.dot(_vcp);if(d6>=0&&d5<=d6){return target.copy(c)}const vb=d5*d2-d1*d6;if(vb<=0&&d2>=0&&d6<=0){w=d2/(d2-d6);return target.copy(a).addScaledVector(_vac,w)}const va=d3*d6-d5*d4;if(va<=0&&d4-d3>=0&&d5-d6>=0){_vbc.subVectors(c,b);w=(d4-d3)/(d4-d3+(d5-d6));return target.copy(b).addScaledVector(_vbc,w)}const denom=1/(va+vb+vc);v=vb*denom;w=vc*denom;return target.copy(a).addScaledVector(_vab,v).addScaledVector(_vac,w)}equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c)}};var materialId=0;var Material=class extends EventDispatcher2{constructor(){super();this.isMaterial=true;Object.defineProperty(this,"id",{value:materialId++});this.uuid=generateUUID();this.name="";this.type="Material";this.blending=NormalBlending;this.side=FrontSide;this.vertexColors=false;this.opacity=1;this.transparent=false;this.blendSrc=SrcAlphaFactor;this.blendDst=OneMinusSrcAlphaFactor;this.blendEquation=AddEquation;this.blendSrcAlpha=null;this.blendDstAlpha=null;this.blendEquationAlpha=null;this.depthFunc=LessEqualDepth;this.depthTest=true;this.depthWrite=true;this.stencilWriteMask=255;this.stencilFunc=AlwaysStencilFunc;this.stencilRef=0;this.stencilFuncMask=255;this.stencilFail=KeepStencilOp;this.stencilZFail=KeepStencilOp;this.stencilZPass=KeepStencilOp;this.stencilWrite=false;this.clippingPlanes=null;this.clipIntersection=false;this.clipShadows=false;this.shadowSide=null;this.colorWrite=true;this.precision=null;this.polygonOffset=false;this.polygonOffsetFactor=0;this.polygonOffsetUnits=0;this.dithering=false;this.alphaToCoverage=false;this.premultipliedAlpha=false;this.visible=true;this.toneMapped=true;this.userData={};this.version=0;this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(value){if(this._alphaTest>0!==value>0){this.version++}this._alphaTest=value}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(values){if(values===void 0)return;for(const key in values){const newValue=values[key];if(newValue===void 0){console.warn("THREE.Material: '"+key+"' parameter is undefined.");continue}if(key==="shading"){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");this.flatShading=newValue===FlatShading?true:false;continue}const currentValue=this[key];if(currentValue===void 0){console.warn("THREE."+this.type+": '"+key+"' is not a property of this material.");continue}if(currentValue&¤tValue.isColor){currentValue.set(newValue)}else if(currentValue&¤tValue.isVector3&&(newValue&&newValue.isVector3)){currentValue.copy(newValue)}else{this[key]=newValue}}}toJSON(meta){const isRootObject=meta===void 0||typeof meta==="string";if(isRootObject){meta={textures:{},images:{}}}const data={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};data.uuid=this.uuid;data.type=this.type;if(this.name!=="")data.name=this.name;if(this.color&&this.color.isColor)data.color=this.color.getHex();if(this.roughness!==void 0)data.roughness=this.roughness;if(this.metalness!==void 0)data.metalness=this.metalness;if(this.sheen!==void 0)data.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)data.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)data.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)data.emissive=this.emissive.getHex();if(this.emissiveIntensity&&this.emissiveIntensity!==1)data.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)data.specular=this.specular.getHex();if(this.specularIntensity!==void 0)data.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)data.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)data.shininess=this.shininess;if(this.clearcoat!==void 0)data.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)data.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture){data.clearcoatMap=this.clearcoatMap.toJSON(meta).uuid}if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture){data.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(meta).uuid}if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture){data.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(meta).uuid;data.clearcoatNormalScale=this.clearcoatNormalScale.toArray()}if(this.iridescence!==void 0)data.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)data.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)data.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture){data.iridescenceMap=this.iridescenceMap.toJSON(meta).uuid}if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture){data.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(meta).uuid}if(this.map&&this.map.isTexture)data.map=this.map.toJSON(meta).uuid;if(this.matcap&&this.matcap.isTexture)data.matcap=this.matcap.toJSON(meta).uuid;if(this.alphaMap&&this.alphaMap.isTexture)data.alphaMap=this.alphaMap.toJSON(meta).uuid;if(this.lightMap&&this.lightMap.isTexture){data.lightMap=this.lightMap.toJSON(meta).uuid;data.lightMapIntensity=this.lightMapIntensity}if(this.aoMap&&this.aoMap.isTexture){data.aoMap=this.aoMap.toJSON(meta).uuid;data.aoMapIntensity=this.aoMapIntensity}if(this.bumpMap&&this.bumpMap.isTexture){data.bumpMap=this.bumpMap.toJSON(meta).uuid;data.bumpScale=this.bumpScale}if(this.normalMap&&this.normalMap.isTexture){data.normalMap=this.normalMap.toJSON(meta).uuid;data.normalMapType=this.normalMapType;data.normalScale=this.normalScale.toArray()}if(this.displacementMap&&this.displacementMap.isTexture){data.displacementMap=this.displacementMap.toJSON(meta).uuid;data.displacementScale=this.displacementScale;data.displacementBias=this.displacementBias}if(this.roughnessMap&&this.roughnessMap.isTexture)data.roughnessMap=this.roughnessMap.toJSON(meta).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)data.metalnessMap=this.metalnessMap.toJSON(meta).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)data.emissiveMap=this.emissiveMap.toJSON(meta).uuid;if(this.specularMap&&this.specularMap.isTexture)data.specularMap=this.specularMap.toJSON(meta).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)data.specularIntensityMap=this.specularIntensityMap.toJSON(meta).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)data.specularColorMap=this.specularColorMap.toJSON(meta).uuid;if(this.envMap&&this.envMap.isTexture){data.envMap=this.envMap.toJSON(meta).uuid;if(this.combine!==void 0)data.combine=this.combine}if(this.envMapIntensity!==void 0)data.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)data.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)data.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture){data.gradientMap=this.gradientMap.toJSON(meta).uuid}if(this.transmission!==void 0)data.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)data.transmissionMap=this.transmissionMap.toJSON(meta).uuid;if(this.thickness!==void 0)data.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)data.thicknessMap=this.thicknessMap.toJSON(meta).uuid;if(this.attenuationDistance!==void 0)data.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)data.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)data.size=this.size;if(this.shadowSide!==null)data.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)data.sizeAttenuation=this.sizeAttenuation;if(this.blending!==NormalBlending)data.blending=this.blending;if(this.side!==FrontSide)data.side=this.side;if(this.vertexColors)data.vertexColors=true;if(this.opacity<1)data.opacity=this.opacity;if(this.transparent===true)data.transparent=this.transparent;data.depthFunc=this.depthFunc;data.depthTest=this.depthTest;data.depthWrite=this.depthWrite;data.colorWrite=this.colorWrite;data.stencilWrite=this.stencilWrite;data.stencilWriteMask=this.stencilWriteMask;data.stencilFunc=this.stencilFunc;data.stencilRef=this.stencilRef;data.stencilFuncMask=this.stencilFuncMask;data.stencilFail=this.stencilFail;data.stencilZFail=this.stencilZFail;data.stencilZPass=this.stencilZPass;if(this.rotation!==void 0&&this.rotation!==0)data.rotation=this.rotation;if(this.polygonOffset===true)data.polygonOffset=true;if(this.polygonOffsetFactor!==0)data.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)data.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)data.linewidth=this.linewidth;if(this.dashSize!==void 0)data.dashSize=this.dashSize;if(this.gapSize!==void 0)data.gapSize=this.gapSize;if(this.scale!==void 0)data.scale=this.scale;if(this.dithering===true)data.dithering=true;if(this.alphaTest>0)data.alphaTest=this.alphaTest;if(this.alphaToCoverage===true)data.alphaToCoverage=this.alphaToCoverage;if(this.premultipliedAlpha===true)data.premultipliedAlpha=this.premultipliedAlpha;if(this.wireframe===true)data.wireframe=this.wireframe;if(this.wireframeLinewidth>1)data.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")data.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")data.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===true)data.flatShading=this.flatShading;if(this.visible===false)data.visible=false;if(this.toneMapped===false)data.toneMapped=false;if(this.fog===false)data.fog=false;if(JSON.stringify(this.userData)!=="{}")data.userData=this.userData;function extractFromCache(cache){const values=[];for(const key in cache){const data2=cache[key];delete data2.metadata;values.push(data2)}return values}if(isRootObject){const textures=extractFromCache(meta.textures);const images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images}return data}clone(){return new this.constructor().copy(this)}copy(source){this.name=source.name;this.blending=source.blending;this.side=source.side;this.vertexColors=source.vertexColors;this.opacity=source.opacity;this.transparent=source.transparent;this.blendSrc=source.blendSrc;this.blendDst=source.blendDst;this.blendEquation=source.blendEquation;this.blendSrcAlpha=source.blendSrcAlpha;this.blendDstAlpha=source.blendDstAlpha;this.blendEquationAlpha=source.blendEquationAlpha;this.depthFunc=source.depthFunc;this.depthTest=source.depthTest;this.depthWrite=source.depthWrite;this.stencilWriteMask=source.stencilWriteMask;this.stencilFunc=source.stencilFunc;this.stencilRef=source.stencilRef;this.stencilFuncMask=source.stencilFuncMask;this.stencilFail=source.stencilFail;this.stencilZFail=source.stencilZFail;this.stencilZPass=source.stencilZPass;this.stencilWrite=source.stencilWrite;const srcPlanes=source.clippingPlanes;let dstPlanes=null;if(srcPlanes!==null){const n=srcPlanes.length;dstPlanes=new Array(n);for(let i=0;i!==n;++i){dstPlanes[i]=srcPlanes[i].clone()}}this.clippingPlanes=dstPlanes;this.clipIntersection=source.clipIntersection;this.clipShadows=source.clipShadows;this.shadowSide=source.shadowSide;this.colorWrite=source.colorWrite;this.precision=source.precision;this.polygonOffset=source.polygonOffset;this.polygonOffsetFactor=source.polygonOffsetFactor;this.polygonOffsetUnits=source.polygonOffsetUnits;this.dithering=source.dithering;this.alphaTest=source.alphaTest;this.alphaToCoverage=source.alphaToCoverage;this.premultipliedAlpha=source.premultipliedAlpha;this.visible=source.visible;this.toneMapped=source.toneMapped;this.userData=JSON.parse(JSON.stringify(source.userData));return this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(value){if(value===true)this.version++}};var MeshBasicMaterial=class extends Material{constructor(parameters){super();this.isMeshBasicMaterial=true;this.type="MeshBasicMaterial";this.color=new Color(16777215);this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.fog=source.fog;return this}};var _vector$9=new Vector3;var _vector2$1=new Vector2;var BufferAttribute=class{constructor(array,itemSize,normalized){if(Array.isArray(array)){throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.")}this.isBufferAttribute=true;this.name="";this.array=array;this.itemSize=itemSize;this.count=array!==void 0?array.length/itemSize:0;this.normalized=normalized===true;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0}onUploadCallback(){}set needsUpdate(value){if(value===true)this.version++}setUsage(value){this.usage=value;return this}copy(source){this.name=source.name;this.array=new source.array.constructor(source.array);this.itemSize=source.itemSize;this.count=source.count;this.normalized=source.normalized;this.usage=source.usage;return this}copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(let i=0,l=this.itemSize;i0)data.userData=this.userData;if(this.parameters!==void 0){const parameters=this.parameters;for(const key in parameters){if(parameters[key]!==void 0)data[key]=parameters[key]}return data}data.data={attributes:{}};const index=this.index;if(index!==null){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)}}const attributes=this.attributes;for(const key in attributes){const attribute=attributes[key];data.data.attributes[key]=attribute.toJSON(data.data)}const morphAttributes={};let hasMorphAttributes=false;for(const key in this.morphAttributes){const attributeArray=this.morphAttributes[key];const array=[];for(let i=0,il=attributeArray.length;i0){morphAttributes[key]=array;hasMorphAttributes=true}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative}const groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups))}const boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius}}return data}clone(){return new this.constructor().copy(this)}copy(source){this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;const data={};this.name=source.name;const index=source.index;if(index!==null){this.setIndex(index.clone(data))}const attributes=source.attributes;for(const name in attributes){const attribute=attributes[name];this.setAttribute(name,attribute.clone(data))}const morphAttributes=source.morphAttributes;for(const name in morphAttributes){const array=[];const morphAttribute=morphAttributes[name];for(let i=0,l=morphAttribute.length;i0){const morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==void 0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(let m=0,ml=morphAttribute.length;mraycaster.far)return null;return{distance,point:_intersectionPointWorld.clone(),object}}function checkBufferGeometryIntersection(object,material,raycaster,ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c){_vA$1.fromBufferAttribute(position,a);_vB$1.fromBufferAttribute(position,b);_vC$1.fromBufferAttribute(position,c);const morphInfluences=object.morphTargetInfluences;if(morphPosition&&morphInfluences){_morphA.set(0,0,0);_morphB.set(0,0,0);_morphC.set(0,0,0);for(let i=0,il=morphPosition.length;i0?1:-1;normals.push(vector.x,vector.y,vector.z);uvs.push(ix/gridX);uvs.push(1-iy/gridY);vertexCounter+=1}}for(let iy=0;iy0)data.defines=this.defines;data.vertexShader=this.vertexShader;data.fragmentShader=this.fragmentShader;const extensions={};for(const key in this.extensions){if(this.extensions[key]===true)extensions[key]=true}if(Object.keys(extensions).length>0)data.extensions=extensions;return data}};var Camera=class extends Object3D{constructor(){super();this.isCamera=true;this.type="Camera";this.matrixWorldInverse=new Matrix4;this.projectionMatrix=new Matrix4;this.projectionMatrixInverse=new Matrix4}copy(source,recursive){super.copy(source,recursive);this.matrixWorldInverse.copy(source.matrixWorldInverse);this.projectionMatrix.copy(source.projectionMatrix);this.projectionMatrixInverse.copy(source.projectionMatrixInverse);return this}getWorldDirection(target){this.updateWorldMatrix(true,false);const e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize()}updateMatrixWorld(force){super.updateMatrixWorld(force);this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(updateParents,updateChildren){super.updateWorldMatrix(updateParents,updateChildren);this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}};var PerspectiveCamera=class extends Camera{constructor(fov2=50,aspect2=1,near=.1,far=2e3){super();this.isPerspectiveCamera=true;this.type="PerspectiveCamera";this.fov=fov2;this.zoom=1;this.near=near;this.far=far;this.focus=10;this.aspect=aspect2;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}copy(source,recursive){super.copy(source,recursive);this.fov=source.fov;this.zoom=source.zoom;this.near=source.near;this.far=source.far;this.focus=source.focus;this.aspect=source.aspect;this.view=source.view===null?null:Object.assign({},source.view);this.filmGauge=source.filmGauge;this.filmOffset=source.filmOffset;return this}setFocalLength(focalLength){const vExtentSlope=.5*this.getFilmHeight()/focalLength;this.fov=RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix()}getFocalLength(){const vExtentSlope=Math.tan(DEG2RAD*.5*this.fov);return .5*this.getFilmHeight()/vExtentSlope}getEffectiveFOV(){return RAD2DEG*2*Math.atan(Math.tan(DEG2RAD*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(fullWidth,fullHeight,x2,y2,width,height){this.aspect=fullWidth/fullHeight;if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x2;this.view.offsetY=y2;this.view.width=width;this.view.height=height;this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null){this.view.enabled=false}this.updateProjectionMatrix()}updateProjectionMatrix(){const near=this.near;let top=near*Math.tan(DEG2RAD*.5*this.fov)/this.zoom;let height=2*top;let width=this.aspect*height;let left=-.5*width;const view=this.view;if(this.view!==null&&this.view.enabled){const fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight}const skew=this.filmOffset;if(skew!==0)left+=near*skew/this.getFilmWidth();this.projectionMatrix.makePerspective(left,left+width,top,top-height,near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(meta){const data=super.toJSON(meta);data.object.fov=this.fov;data.object.zoom=this.zoom;data.object.near=this.near;data.object.far=this.far;data.object.focus=this.focus;data.object.aspect=this.aspect;if(this.view!==null)data.object.view=Object.assign({},this.view);data.object.filmGauge=this.filmGauge;data.object.filmOffset=this.filmOffset;return data}};var fov=90;var aspect=1;var CubeCamera=class extends Object3D{constructor(near,far,renderTarget){super();this.type="CubeCamera";if(renderTarget.isWebGLCubeRenderTarget!==true){console.error("THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.");return}this.renderTarget=renderTarget;const cameraPX=new PerspectiveCamera(fov,aspect,near,far);cameraPX.layers=this.layers;cameraPX.up.set(0,-1,0);cameraPX.lookAt(new Vector3(1,0,0));this.add(cameraPX);const cameraNX=new PerspectiveCamera(fov,aspect,near,far);cameraNX.layers=this.layers;cameraNX.up.set(0,-1,0);cameraNX.lookAt(new Vector3(-1,0,0));this.add(cameraNX);const cameraPY=new PerspectiveCamera(fov,aspect,near,far);cameraPY.layers=this.layers;cameraPY.up.set(0,0,1);cameraPY.lookAt(new Vector3(0,1,0));this.add(cameraPY);const cameraNY=new PerspectiveCamera(fov,aspect,near,far);cameraNY.layers=this.layers;cameraNY.up.set(0,0,-1);cameraNY.lookAt(new Vector3(0,-1,0));this.add(cameraNY);const cameraPZ=new PerspectiveCamera(fov,aspect,near,far);cameraPZ.layers=this.layers;cameraPZ.up.set(0,-1,0);cameraPZ.lookAt(new Vector3(0,0,1));this.add(cameraPZ);const cameraNZ=new PerspectiveCamera(fov,aspect,near,far);cameraNZ.layers=this.layers;cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3(0,0,-1));this.add(cameraNZ)}update(renderer,scene){if(this.parent===null)this.updateMatrixWorld();const renderTarget=this.renderTarget;const[cameraPX,cameraNX,cameraPY,cameraNY,cameraPZ,cameraNZ]=this.children;const currentRenderTarget=renderer.getRenderTarget();const currentToneMapping=renderer.toneMapping;const currentXrEnabled=renderer.xr.enabled;renderer.toneMapping=NoToneMapping;renderer.xr.enabled=false;const generateMipmaps=renderTarget.texture.generateMipmaps;renderTarget.texture.generateMipmaps=false;renderer.setRenderTarget(renderTarget,0);renderer.render(scene,cameraPX);renderer.setRenderTarget(renderTarget,1);renderer.render(scene,cameraNX);renderer.setRenderTarget(renderTarget,2);renderer.render(scene,cameraPY);renderer.setRenderTarget(renderTarget,3);renderer.render(scene,cameraNY);renderer.setRenderTarget(renderTarget,4);renderer.render(scene,cameraPZ);renderTarget.texture.generateMipmaps=generateMipmaps;renderer.setRenderTarget(renderTarget,5);renderer.render(scene,cameraNZ);renderer.setRenderTarget(currentRenderTarget);renderer.toneMapping=currentToneMapping;renderer.xr.enabled=currentXrEnabled;renderTarget.texture.needsPMREMUpdate=true}};var CubeTexture=class extends Texture{constructor(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){images=images!==void 0?images:[];mapping=mapping!==void 0?mapping:CubeReflectionMapping;super(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.isCubeTexture=true;this.flipY=false}get images(){return this.image}set images(value){this.image=value}};var WebGLCubeRenderTarget=class extends WebGLRenderTarget{constructor(size,options={}){super(size,size,options);this.isWebGLCubeRenderTarget=true;const image={width:size,height:size,depth:1};const images=[image,image,image,image,image,image];this.texture=new CubeTexture(images,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture.isRenderTargetTexture=true;this.texture.generateMipmaps=options.generateMipmaps!==void 0?options.generateMipmaps:false;this.texture.minFilter=options.minFilter!==void 0?options.minFilter:LinearFilter}fromEquirectangularTexture(renderer,texture){this.texture.type=texture.type;this.texture.encoding=texture.encoding;this.texture.generateMipmaps=texture.generateMipmaps;this.texture.minFilter=texture.minFilter;this.texture.magFilter=texture.magFilter;const shader={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `};const geometry=new BoxGeometry(5,5,5);const material=new ShaderMaterial({name:"CubemapFromEquirect",uniforms:cloneUniforms(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide,blending:NoBlending});material.uniforms.tEquirect.value=texture;const mesh=new Mesh(geometry,material);const currentMinFilter=texture.minFilter;if(texture.minFilter===LinearMipmapLinearFilter)texture.minFilter=LinearFilter;const camera=new CubeCamera(1,10,this);camera.update(renderer,mesh);texture.minFilter=currentMinFilter;mesh.geometry.dispose();mesh.material.dispose();return this}clear(renderer,color,depth,stencil){const currentRenderTarget=renderer.getRenderTarget();for(let i=0;i<6;i++){renderer.setRenderTarget(this,i);renderer.clear(color,depth,stencil)}renderer.setRenderTarget(currentRenderTarget)}};var _vector1=new Vector3;var _vector2=new Vector3;var _normalMatrix=new Matrix3;var Plane=class{constructor(normal=new Vector3(1,0,0),constant=0){this.isPlane=true;this.normal=normal;this.constant=constant}set(normal,constant){this.normal.copy(normal);this.constant=constant;return this}setComponents(x2,y2,z,w){this.normal.set(x2,y2,z);this.constant=w;return this}setFromNormalAndCoplanarPoint(normal,point){this.normal.copy(normal);this.constant=-point.dot(this.normal);return this}setFromCoplanarPoints(a,b,c){const normal=_vector1.subVectors(c,b).cross(_vector2.subVectors(a,b)).normalize();this.setFromNormalAndCoplanarPoint(normal,a);return this}copy(plane){this.normal.copy(plane.normal);this.constant=plane.constant;return this}normalize(){const inverseNormalLength=1/this.normal.length();this.normal.multiplyScalar(inverseNormalLength);this.constant*=inverseNormalLength;return this}negate(){this.constant*=-1;this.normal.negate();return this}distanceToPoint(point){return this.normal.dot(point)+this.constant}distanceToSphere(sphere){return this.distanceToPoint(sphere.center)-sphere.radius}projectPoint(point,target){return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point)}intersectLine(line,target){const direction=line.delta(_vector1);const denominator=this.normal.dot(direction);if(denominator===0){if(this.distanceToPoint(line.start)===0){return target.copy(line.start)}return null}const t=-(line.start.dot(this.normal)+this.constant)/denominator;if(t<0||t>1){return null}return target.copy(direction).multiplyScalar(t).add(line.start)}intersectsLine(line){const startSign=this.distanceToPoint(line.start);const endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0}intersectsBox(box){return box.intersectsPlane(this)}intersectsSphere(sphere){return sphere.intersectsPlane(this)}coplanarPoint(target){return target.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(matrix,optionalNormalMatrix){const normalMatrix=optionalNormalMatrix||_normalMatrix.getNormalMatrix(matrix);const referencePoint=this.coplanarPoint(_vector1).applyMatrix4(matrix);const normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this}translate(offset){this.constant-=offset.dot(this.normal);return this}equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant}clone(){return new this.constructor().copy(this)}};var _sphere$2=new Sphere;var _vector$7=new Vector3;var Frustum=class{constructor(p0=new Plane,p1=new Plane,p2=new Plane,p3=new Plane,p4=new Plane,p5=new Plane){this.planes=[p0,p1,p2,p3,p4,p5]}set(p0,p1,p2,p3,p4,p5){const planes=this.planes;planes[0].copy(p0);planes[1].copy(p1);planes[2].copy(p2);planes[3].copy(p3);planes[4].copy(p4);planes[5].copy(p5);return this}copy(frustum){const planes=this.planes;for(let i=0;i<6;i++){planes[i].copy(frustum.planes[i])}return this}setFromProjectionMatrix(m){const planes=this.planes;const me=m.elements;const me0=me[0],me1=me[1],me2=me[2],me3=me[3];const me4=me[4],me5=me[5],me6=me[6],me7=me[7];const me8=me[8],me9=me[9],me10=me[10],me11=me[11];const me12=me[12],me13=me[13],me14=me[14],me15=me[15];planes[0].setComponents(me3-me0,me7-me4,me11-me8,me15-me12).normalize();planes[1].setComponents(me3+me0,me7+me4,me11+me8,me15+me12).normalize();planes[2].setComponents(me3+me1,me7+me5,me11+me9,me15+me13).normalize();planes[3].setComponents(me3-me1,me7-me5,me11-me9,me15-me13).normalize();planes[4].setComponents(me3-me2,me7-me6,me11-me10,me15-me14).normalize();planes[5].setComponents(me3+me2,me7+me6,me11+me10,me15+me14).normalize();return this}intersectsObject(object){const geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$2)}intersectsSprite(sprite){_sphere$2.center.set(0,0,0);_sphere$2.radius=.7071067811865476;_sphere$2.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(_sphere$2)}intersectsSphere(sphere){const planes=this.planes;const center=sphere.center;const negRadius=-sphere.radius;for(let i=0;i<6;i++){const distance=planes[i].distanceToPoint(center);if(distance0?box.max.x:box.min.x;_vector$7.y=plane.normal.y>0?box.max.y:box.min.y;_vector$7.z=plane.normal.z>0?box.max.z:box.min.z;if(plane.distanceToPoint(_vector$7)<0){return false}}return true}containsPoint(point){const planes=this.planes;for(let i=0;i<6;i++){if(planes[i].distanceToPoint(point)<0){return false}}return true}clone(){return new this.constructor().copy(this)}};function WebGLAnimation(){let context=null;let isAnimating=false;let animationLoop=null;let requestId=null;function onAnimationFrame(time,frame){animationLoop(time,frame);requestId=context.requestAnimationFrame(onAnimationFrame)}return{start:function(){if(isAnimating===true)return;if(animationLoop===null)return;requestId=context.requestAnimationFrame(onAnimationFrame);isAnimating=true},stop:function(){context.cancelAnimationFrame(requestId);isAnimating=false},setAnimationLoop:function(callback){animationLoop=callback},setContext:function(value){context=value}}}function WebGLAttributes(gl,capabilities){const isWebGL2=capabilities.isWebGL2;const buffers=new WeakMap;function createBuffer(attribute,bufferType){const array=attribute.array;const usage=attribute.usage;const buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();let type;if(array instanceof Float32Array){type=5126}else if(array instanceof Uint16Array){if(attribute.isFloat16BufferAttribute){if(isWebGL2){type=5131}else{throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.")}}else{type=5123}}else if(array instanceof Int16Array){type=5122}else if(array instanceof Uint32Array){type=5125}else if(array instanceof Int32Array){type=5124}else if(array instanceof Int8Array){type=5120}else if(array instanceof Uint8Array){type=5121}else if(array instanceof Uint8ClampedArray){type=5121}else{throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+array)}return{buffer,type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version}}function updateBuffer(buffer,attribute,bufferType){const array=attribute.array;const updateRange=attribute.updateRange;gl.bindBuffer(bufferType,buffer);if(updateRange.count===-1){gl.bufferSubData(bufferType,0,array)}else{if(isWebGL2){gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array,updateRange.offset,updateRange.count)}else{gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array.subarray(updateRange.offset,updateRange.offset+updateRange.count))}updateRange.count=-1}}function get3(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;return buffers.get(attribute)}function remove(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;const data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute)}}function update(attribute,bufferType){if(attribute.isGLBufferAttribute){const cached=buffers.get(attribute);if(!cached||cached.version=0){const cachedAttribute=cachedAttributes[name];let geometryAttribute=geometryAttributes[name];if(geometryAttribute===void 0){if(name==="instanceMatrix"&&object.instanceMatrix)geometryAttribute=object.instanceMatrix;if(name==="instanceColor"&&object.instanceColor)geometryAttribute=object.instanceColor}if(cachedAttribute===void 0)return true;if(cachedAttribute.attribute!==geometryAttribute)return true;if(geometryAttribute&&cachedAttribute.data!==geometryAttribute.data)return true;attributesNum++}}if(currentState.attributesNum!==attributesNum)return true;if(currentState.index!==index)return true;return false}function saveCache(object,geometry,program,index){const cache={};const attributes2=geometry.attributes;let attributesNum=0;const programAttributes=program.getAttributes();for(const name in programAttributes){const programAttribute=programAttributes[name];if(programAttribute.location>=0){let attribute=attributes2[name];if(attribute===void 0){if(name==="instanceMatrix"&&object.instanceMatrix)attribute=object.instanceMatrix;if(name==="instanceColor"&&object.instanceColor)attribute=object.instanceColor}const data={};data.attribute=attribute;if(attribute&&attribute.data){data.data=attribute.data}cache[name]=data;attributesNum++}}currentState.attributes=cache;currentState.attributesNum=attributesNum;currentState.index=index}function initAttributes(){const newAttributes=currentState.newAttributes;for(let i=0,il=newAttributes.length;i=0){let geometryAttribute=geometryAttributes[name];if(geometryAttribute===void 0){if(name==="instanceMatrix"&&object.instanceMatrix)geometryAttribute=object.instanceMatrix;if(name==="instanceColor"&&object.instanceColor)geometryAttribute=object.instanceColor}if(geometryAttribute!==void 0){const normalized=geometryAttribute.normalized;const size=geometryAttribute.itemSize;const attribute=attributes.get(geometryAttribute);if(attribute===void 0)continue;const buffer=attribute.buffer;const type=attribute.type;const bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){const data=geometryAttribute.data;const stride=data.stride;const offset=geometryAttribute.offset;if(data.isInstancedInterleavedBuffer){for(let i=0;i0&&gl.getShaderPrecisionFormat(35632,36338).precision>0){return"highp"}precision2="mediump"}if(precision2==="mediump"){if(gl.getShaderPrecisionFormat(35633,36337).precision>0&&gl.getShaderPrecisionFormat(35632,36337).precision>0){return"mediump"}}return"lowp"}const isWebGL2=typeof WebGL2RenderingContext!=="undefined"&&gl instanceof WebGL2RenderingContext||typeof WebGL2ComputeRenderingContext!=="undefined"&&gl instanceof WebGL2ComputeRenderingContext;let precision=parameters.precision!==void 0?parameters.precision:"highp";const maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn("THREE.WebGLRenderer:",precision,"not supported, using",maxPrecision,"instead.");precision=maxPrecision}const drawBuffers=isWebGL2||extensions.has("WEBGL_draw_buffers");const logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true;const maxTextures=gl.getParameter(34930);const maxVertexTextures=gl.getParameter(35660);const maxTextureSize=gl.getParameter(3379);const maxCubemapSize=gl.getParameter(34076);const maxAttributes=gl.getParameter(34921);const maxVertexUniforms=gl.getParameter(36347);const maxVaryings=gl.getParameter(36348);const maxFragmentUniforms=gl.getParameter(36349);const vertexTextures=maxVertexTextures>0;const floatFragmentTextures=isWebGL2||extensions.has("OES_texture_float");const floatVertexTextures=vertexTextures&&floatFragmentTextures;const maxSamples=isWebGL2?gl.getParameter(36183):0;return{isWebGL2,drawBuffers,getMaxAnisotropy,getMaxPrecision,precision,logarithmicDepthBuffer,maxTextures,maxVertexTextures,maxTextureSize,maxCubemapSize,maxAttributes,maxVertexUniforms,maxVaryings,maxFragmentUniforms,vertexTextures,floatFragmentTextures,floatVertexTextures,maxSamples}}function WebGLClipping(properties){const scope=this;let globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false;const plane=new Plane,viewNormalMatrix=new Matrix3,uniform={value:null,needsUpdate:false};this.uniform=uniform;this.numPlanes=0;this.numIntersection=0;this.init=function(planes,enableLocalClipping,camera){const enabled=planes.length!==0||enableLocalClipping||numGlobalPlanes!==0||localClippingEnabled;localClippingEnabled=enableLocalClipping;globalState=projectPlanes(planes,camera,0);numGlobalPlanes=planes.length;return enabled};this.beginShadows=function(){renderingShadows=true;projectPlanes(null)};this.endShadows=function(){renderingShadows=false;resetGlobalState()};this.setState=function(material,camera,useCache){const planes=material.clippingPlanes,clipIntersection=material.clipIntersection,clipShadows=material.clipShadows;const materialProperties=properties.get(material);if(!localClippingEnabled||planes===null||planes.length===0||renderingShadows&&!clipShadows){if(renderingShadows){projectPlanes(null)}else{resetGlobalState()}}else{const nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4;let dstArray=materialProperties.clippingState||null;uniform.value=dstArray;dstArray=projectPlanes(planes,camera,lGlobal,useCache);for(let i=0;i!==lGlobal;++i){dstArray[i]=globalState[i]}materialProperties.clippingState=dstArray;this.numIntersection=clipIntersection?this.numPlanes:0;this.numPlanes+=nGlobal}};function resetGlobalState(){if(uniform.value!==globalState){uniform.value=globalState;uniform.needsUpdate=numGlobalPlanes>0}scope.numPlanes=numGlobalPlanes;scope.numIntersection=0}function projectPlanes(planes,camera,dstOffset,skipTransform){const nPlanes=planes!==null?planes.length:0;let dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){const flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length0){const renderTarget=new WebGLCubeRenderTarget(image.height/2);renderTarget.fromEquirectangularTexture(renderer,texture);cubemaps.set(texture,renderTarget);texture.addEventListener("dispose",onTextureDispose);return mapTextureMapping(renderTarget.texture,texture.mapping)}else{return null}}}}return texture}function onTextureDispose(event){const texture=event.target;texture.removeEventListener("dispose",onTextureDispose);const cubemap=cubemaps.get(texture);if(cubemap!==void 0){cubemaps.delete(texture);cubemap.dispose()}}function dispose(){cubemaps=new WeakMap}return{get:get3,dispose}}var OrthographicCamera=class extends Camera{constructor(left=-1,right=1,top=1,bottom=-1,near=.1,far=2e3){super();this.isOrthographicCamera=true;this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=left;this.right=right;this.top=top;this.bottom=bottom;this.near=near;this.far=far;this.updateProjectionMatrix()}copy(source,recursive){super.copy(source,recursive);this.left=source.left;this.right=source.right;this.top=source.top;this.bottom=source.bottom;this.near=source.near;this.far=source.far;this.zoom=source.zoom;this.view=source.view===null?null:Object.assign({},source.view);return this}setViewOffset(fullWidth,fullHeight,x2,y2,width,height){if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x2;this.view.offsetY=y2;this.view.width=width;this.view.height=height;this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null){this.view.enabled=false}this.updateProjectionMatrix()}updateProjectionMatrix(){const dx=(this.right-this.left)/(2*this.zoom);const dy=(this.top-this.bottom)/(2*this.zoom);const cx=(this.right+this.left)/2;const cy=(this.top+this.bottom)/2;let left=cx-dx;let right=cx+dx;let top=cy+dy;let bottom=cy-dy;if(this.view!==null&&this.view.enabled){const scaleW=(this.right-this.left)/this.view.fullWidth/this.zoom;const scaleH=(this.top-this.bottom)/this.view.fullHeight/this.zoom;left+=scaleW*this.view.offsetX;right=left+scaleW*this.view.width;top-=scaleH*this.view.offsetY;bottom=top-scaleH*this.view.height}this.projectionMatrix.makeOrthographic(left,right,top,bottom,this.near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(meta){const data=super.toJSON(meta);data.object.zoom=this.zoom;data.object.left=this.left;data.object.right=this.right;data.object.top=this.top;data.object.bottom=this.bottom;data.object.near=this.near;data.object.far=this.far;if(this.view!==null)data.object.view=Object.assign({},this.view);return data}};var LOD_MIN=4;var EXTRA_LOD_SIGMA=[.125,.215,.35,.446,.526,.582];var MAX_SAMPLES=20;var _flatCamera=new OrthographicCamera;var _clearColor=new Color;var _oldTarget=null;var PHI=(1+Math.sqrt(5))/2;var INV_PHI=1/PHI;var _axisDirections=[new Vector3(1,1,1),new Vector3(-1,1,1),new Vector3(1,1,-1),new Vector3(-1,1,-1),new Vector3(0,PHI,INV_PHI),new Vector3(0,PHI,-INV_PHI),new Vector3(INV_PHI,0,PHI),new Vector3(-INV_PHI,0,PHI),new Vector3(PHI,INV_PHI,0),new Vector3(-PHI,INV_PHI,0)];var PMREMGenerator=class{constructor(renderer){this._renderer=renderer;this._pingPongRenderTarget=null;this._lodMax=0;this._cubeSize=0;this._lodPlanes=[];this._sizeLods=[];this._sigmas=[];this._blurMaterial=null;this._cubemapMaterial=null;this._equirectMaterial=null;this._compileMaterial(this._blurMaterial)}fromScene(scene,sigma=0,near=.1,far=100){_oldTarget=this._renderer.getRenderTarget();this._setSize(256);const cubeUVRenderTarget=this._allocateTargets();cubeUVRenderTarget.depthBuffer=true;this._sceneToCubeUV(scene,near,far,cubeUVRenderTarget);if(sigma>0){this._blur(cubeUVRenderTarget,0,0,sigma)}this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget}fromEquirectangular(equirectangular,renderTarget=null){return this._fromTexture(equirectangular,renderTarget)}fromCubemap(cubemap,renderTarget=null){return this._fromTexture(cubemap,renderTarget)}compileCubemapShader(){if(this._cubemapMaterial===null){this._cubemapMaterial=_getCubemapMaterial();this._compileMaterial(this._cubemapMaterial)}}compileEquirectangularShader(){if(this._equirectMaterial===null){this._equirectMaterial=_getEquirectMaterial();this._compileMaterial(this._equirectMaterial)}}dispose(){this._dispose();if(this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose()}_setSize(cubeSize){this._lodMax=Math.floor(Math.log2(cubeSize));this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._pingPongRenderTarget!==null)this._pingPongRenderTarget.dispose();for(let i=0;i2?size:0,size,size);renderer.setRenderTarget(cubeUVRenderTarget);if(useSolidColor){renderer.render(backgroundBox,cubeCamera)}renderer.render(scene,cubeCamera)}backgroundBox.geometry.dispose();backgroundBox.material.dispose();renderer.toneMapping=toneMapping;renderer.autoClear=originalAutoClear;scene.background=background}_textureToCubeUV(texture,cubeUVRenderTarget){const renderer=this._renderer;const isCubeTexture=texture.mapping===CubeReflectionMapping||texture.mapping===CubeRefractionMapping;if(isCubeTexture){if(this._cubemapMaterial===null){this._cubemapMaterial=_getCubemapMaterial()}this._cubemapMaterial.uniforms.flipEnvMap.value=texture.isRenderTargetTexture===false?-1:1}else{if(this._equirectMaterial===null){this._equirectMaterial=_getEquirectMaterial()}}const material=isCubeTexture?this._cubemapMaterial:this._equirectMaterial;const mesh=new Mesh(this._lodPlanes[0],material);const uniforms=material.uniforms;uniforms["envMap"].value=texture;const size=this._cubeSize;_setViewport(cubeUVRenderTarget,0,0,3*size,2*size);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(mesh,_flatCamera)}_applyPMREM(cubeUVRenderTarget){const renderer=this._renderer;const autoClear=renderer.autoClear;renderer.autoClear=false;for(let i=1;iMAX_SAMPLES){console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`)}const weights=[];let sum=0;for(let i=0;i_lodMax-LOD_MIN?lodOut-_lodMax+LOD_MIN:0);const y2=4*(this._cubeSize-outputSize);_setViewport(targetOut,x2,y2,3*outputSize,2*outputSize);renderer.setRenderTarget(targetOut);renderer.render(blurMesh,_flatCamera)}};function _createPlanes(lodMax){const lodPlanes=[];const sizeLods=[];const sigmas=[];let lod=lodMax;const totalLods=lodMax-LOD_MIN+1+EXTRA_LOD_SIGMA.length;for(let i=0;ilodMax-LOD_MIN){sigma=EXTRA_LOD_SIGMA[i-lodMax+LOD_MIN-1]}else if(i===0){sigma=0}sigmas.push(sigma);const texelSize=1/(sizeLod-2);const min=-texelSize;const max=1+texelSize;const uv1=[min,min,max,min,max,max,min,min,max,max,min,max];const cubeFaces=6;const vertices=6;const positionSize=3;const uvSize=2;const faceIndexSize=1;const position=new Float32Array(positionSize*vertices*cubeFaces);const uv=new Float32Array(uvSize*vertices*cubeFaces);const faceIndex=new Float32Array(faceIndexSize*vertices*cubeFaces);for(let face=0;face2?0:-1;const coordinates=[x2,y2,0,x2+2/3,y2,0,x2+2/3,y2+1,0,x2,y2,0,x2+2/3,y2+1,0,x2,y2+1,0];position.set(coordinates,positionSize*vertices*face);uv.set(uv1,uvSize*vertices*face);const fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*vertices*face)}const planes=new BufferGeometry;planes.setAttribute("position",new BufferAttribute(position,positionSize));planes.setAttribute("uv",new BufferAttribute(uv,uvSize));planes.setAttribute("faceIndex",new BufferAttribute(faceIndex,faceIndexSize));lodPlanes.push(planes);if(lod>LOD_MIN){lod--}}return{lodPlanes,sizeLods,sigmas}}function _createRenderTarget(width,height,params){const cubeUVRenderTarget=new WebGLRenderTarget(width,height,params);cubeUVRenderTarget.texture.mapping=CubeUVReflectionMapping;cubeUVRenderTarget.texture.name="PMREM.cubeUv";cubeUVRenderTarget.scissorTest=true;return cubeUVRenderTarget}function _setViewport(target,x2,y2,width,height){target.viewport.set(x2,y2,width,height);target.scissor.set(x2,y2,width,height)}function _getBlurShader(lodMax,width,height){const weights=new Float32Array(MAX_SAMPLES);const poleAxis=new Vector3(0,1,0);const shaderMaterial=new ShaderMaterial({name:"SphericalGaussianBlur",defines:{"n":MAX_SAMPLES,"CUBEUV_TEXEL_WIDTH":1/width,"CUBEUV_TEXEL_HEIGHT":1/height,"CUBEUV_MAX_MIP":`${lodMax}.0`},uniforms:{"envMap":{value:null},"samples":{value:1},"weights":{value:weights},"latitudinal":{value:false},"dTheta":{value:0},"mipInt":{value:0},"poleAxis":{value:poleAxis}},vertexShader:_getCommonVertexShader(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial}function _getEquirectMaterial(){return new ShaderMaterial({name:"EquirectangularToCubeUV",uniforms:{"envMap":{value:null}},vertexShader:_getCommonVertexShader(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:NoBlending,depthTest:false,depthWrite:false})}function _getCubemapMaterial(){return new ShaderMaterial({name:"CubemapToCubeUV",uniforms:{"envMap":{value:null},"flipEnvMap":{value:-1}},vertexShader:_getCommonVertexShader(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:NoBlending,depthTest:false,depthWrite:false})}function _getCommonVertexShader(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function WebGLCubeUVMaps(renderer){let cubeUVmaps=new WeakMap;let pmremGenerator=null;function get3(texture){if(texture&&texture.isTexture){const mapping=texture.mapping;const isEquirectMap=mapping===EquirectangularReflectionMapping||mapping===EquirectangularRefractionMapping;const isCubeMap=mapping===CubeReflectionMapping||mapping===CubeRefractionMapping;if(isEquirectMap||isCubeMap){if(texture.isRenderTargetTexture&&texture.needsPMREMUpdate===true){texture.needsPMREMUpdate=false;let renderTarget=cubeUVmaps.get(texture);if(pmremGenerator===null)pmremGenerator=new PMREMGenerator(renderer);renderTarget=isEquirectMap?pmremGenerator.fromEquirectangular(texture,renderTarget):pmremGenerator.fromCubemap(texture,renderTarget);cubeUVmaps.set(texture,renderTarget);return renderTarget.texture}else{if(cubeUVmaps.has(texture)){return cubeUVmaps.get(texture).texture}else{const image=texture.image;if(isEquirectMap&&image&&image.height>0||isCubeMap&&image&&isCubeTextureComplete(image)){if(pmremGenerator===null)pmremGenerator=new PMREMGenerator(renderer);const renderTarget=isEquirectMap?pmremGenerator.fromEquirectangular(texture):pmremGenerator.fromCubemap(texture);cubeUVmaps.set(texture,renderTarget);texture.addEventListener("dispose",onTextureDispose);return renderTarget.texture}else{return null}}}}}return texture}function isCubeTextureComplete(image){let count=0;const length=6;for(let i=0;icapabilities.maxTextureSize){height=Math.ceil(width/capabilities.maxTextureSize);width=capabilities.maxTextureSize}const buffer=new Float32Array(width*height*4*morphTargetsCount);const texture=new DataArrayTexture(buffer,width,height,morphTargetsCount);texture.type=FloatType;texture.needsUpdate=true;const vertexDataStride=vertexDataCount*4;for(let i=0;i0)return array;const n=nBlocks*blockSize;let r=arrayCacheF32[n];if(r===void 0){r=new Float32Array(n);arrayCacheF32[n]=r}if(nBlocks!==0){firstElem.toArray(r,0);for(let i=1,offset=0;i!==nBlocks;++i){offset+=blockSize;array[i].toArray(r,offset)}}return r}function arraysEqual(a,b){if(a.length!==b.length)return false;for(let i=0,l=a.length;i":" "} ${line}: ${lines[i]}`)}return lines2.join("\n")}function getEncodingComponents(encoding){switch(encoding){case LinearEncoding:return["Linear","( value )"];case sRGBEncoding:return["sRGB","( value )"];default:console.warn("THREE.WebGLProgram: Unsupported encoding:",encoding);return["Linear","( value )"]}}function getShaderErrors(gl,shader,type){const status=gl.getShaderParameter(shader,35713);const errors=gl.getShaderInfoLog(shader).trim();if(status&&errors==="")return"";const errorMatches=/ERROR: 0:(\d+)/.exec(errors);if(errorMatches){const errorLine=parseInt(errorMatches[1]);return type.toUpperCase()+"\n\n"+errors+"\n\n"+handleSource(gl.getShaderSource(shader),errorLine)}else{return errors}}function getTexelEncodingFunction(functionName,encoding){const components=getEncodingComponents(encoding);return"vec4 "+functionName+"( vec4 value ) { return LinearTo"+components[0]+components[1]+"; }"}function getToneMappingFunction(functionName,toneMapping){let toneMappingName;switch(toneMapping){case LinearToneMapping:toneMappingName="Linear";break;case ReinhardToneMapping:toneMappingName="Reinhard";break;case CineonToneMapping:toneMappingName="OptimizedCineon";break;case ACESFilmicToneMapping:toneMappingName="ACESFilmic";break;case CustomToneMapping:toneMappingName="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",toneMapping);toneMappingName="Linear"}return"vec3 "+functionName+"( vec3 color ) { return "+toneMappingName+"ToneMapping( color ); }"}function generateExtensions(parameters){const chunks=[parameters.extensionDerivatives||!!parameters.envMapCubeUVHeight||parameters.bumpMap||parameters.tangentSpaceNormalMap||parameters.clearcoatNormalMap||parameters.flatShading||parameters.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(parameters.extensionFragDepth||parameters.logarithmicDepthBuffer)&¶meters.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",parameters.extensionDrawBuffers&¶meters.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(parameters.extensionShaderTextureLOD||parameters.envMap||parameters.transmission)&¶meters.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""];return chunks.filter(filterEmptyLine).join("\n")}function generateDefines(defines){const chunks=[];for(const name in defines){const value=defines[name];if(value===false)continue;chunks.push("#define "+name+" "+value)}return chunks.join("\n")}function fetchAttributeLocations(gl,program){const attributes={};const n=gl.getProgramParameter(program,35721);for(let i=0;i/gm;function resolveIncludes(string){return string.replace(includePattern,includeReplacer)}function includeReplacer(match,include){const string=ShaderChunk[include];if(string===void 0){throw new Error("Can not resolve #include <"+include+">")}return resolveIncludes(string)}var deprecatedUnrollLoopPattern=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;var unrollLoopPattern=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function unrollLoops(string){return string.replace(unrollLoopPattern,loopReplacer).replace(deprecatedUnrollLoopPattern,deprecatedLoopReplacer)}function deprecatedLoopReplacer(match,start,end,snippet){console.warn("WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.");return loopReplacer(match,start,end,snippet)}function loopReplacer(match,start,end,snippet){let string="";for(let i=parseInt(start);i0){prefixVertex+="\n"}prefixFragment=[customExtensions,customDefines].filter(filterEmptyLine).join("\n");if(prefixFragment.length>0){prefixFragment+="\n"}}else{prefixVertex=[generatePrecision(parameters),"#define SHADER_NAME "+parameters.shaderName,customDefines,parameters.instancing?"#define USE_INSTANCING":"",parameters.instancingColor?"#define USE_INSTANCING_COLOR":"",parameters.supportsVertexTextures?"#define VERTEX_TEXTURES":"",parameters.useFog&¶meters.fog?"#define USE_FOG":"",parameters.useFog&¶meters.fogExp2?"#define FOG_EXP2":"",parameters.map?"#define USE_MAP":"",parameters.envMap?"#define USE_ENVMAP":"",parameters.envMap?"#define "+envMapModeDefine:"",parameters.lightMap?"#define USE_LIGHTMAP":"",parameters.aoMap?"#define USE_AOMAP":"",parameters.emissiveMap?"#define USE_EMISSIVEMAP":"",parameters.bumpMap?"#define USE_BUMPMAP":"",parameters.normalMap?"#define USE_NORMALMAP":"",parameters.normalMap&¶meters.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",parameters.normalMap&¶meters.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",parameters.clearcoatMap?"#define USE_CLEARCOATMAP":"",parameters.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",parameters.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",parameters.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",parameters.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",parameters.displacementMap&¶meters.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",parameters.specularMap?"#define USE_SPECULARMAP":"",parameters.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",parameters.specularColorMap?"#define USE_SPECULARCOLORMAP":"",parameters.roughnessMap?"#define USE_ROUGHNESSMAP":"",parameters.metalnessMap?"#define USE_METALNESSMAP":"",parameters.alphaMap?"#define USE_ALPHAMAP":"",parameters.transmission?"#define USE_TRANSMISSION":"",parameters.transmissionMap?"#define USE_TRANSMISSIONMAP":"",parameters.thicknessMap?"#define USE_THICKNESSMAP":"",parameters.sheenColorMap?"#define USE_SHEENCOLORMAP":"",parameters.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",parameters.vertexTangents?"#define USE_TANGENT":"",parameters.vertexColors?"#define USE_COLOR":"",parameters.vertexAlphas?"#define USE_COLOR_ALPHA":"",parameters.vertexUvs?"#define USE_UV":"",parameters.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",parameters.flatShading?"#define FLAT_SHADED":"",parameters.skinning?"#define USE_SKINNING":"",parameters.morphTargets?"#define USE_MORPHTARGETS":"",parameters.morphNormals&¶meters.flatShading===false?"#define USE_MORPHNORMALS":"",parameters.morphColors&¶meters.isWebGL2?"#define USE_MORPHCOLORS":"",parameters.morphTargetsCount>0&¶meters.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",parameters.morphTargetsCount>0&¶meters.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+parameters.morphTextureStride:"",parameters.morphTargetsCount>0&¶meters.isWebGL2?"#define MORPHTARGETS_COUNT "+parameters.morphTargetsCount:"",parameters.doubleSided?"#define DOUBLE_SIDED":"",parameters.flipSided?"#define FLIP_SIDED":"",parameters.shadowMapEnabled?"#define USE_SHADOWMAP":"",parameters.shadowMapEnabled?"#define "+shadowMapTypeDefine:"",parameters.sizeAttenuation?"#define USE_SIZEATTENUATION":"",parameters.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif","\n"].filter(filterEmptyLine).join("\n");prefixFragment=[customExtensions,generatePrecision(parameters),"#define SHADER_NAME "+parameters.shaderName,customDefines,parameters.useFog&¶meters.fog?"#define USE_FOG":"",parameters.useFog&¶meters.fogExp2?"#define FOG_EXP2":"",parameters.map?"#define USE_MAP":"",parameters.matcap?"#define USE_MATCAP":"",parameters.envMap?"#define USE_ENVMAP":"",parameters.envMap?"#define "+envMapTypeDefine:"",parameters.envMap?"#define "+envMapModeDefine:"",parameters.envMap?"#define "+envMapBlendingDefine:"",envMapCubeUVSize?"#define CUBEUV_TEXEL_WIDTH "+envMapCubeUVSize.texelWidth:"",envMapCubeUVSize?"#define CUBEUV_TEXEL_HEIGHT "+envMapCubeUVSize.texelHeight:"",envMapCubeUVSize?"#define CUBEUV_MAX_MIP "+envMapCubeUVSize.maxMip+".0":"",parameters.lightMap?"#define USE_LIGHTMAP":"",parameters.aoMap?"#define USE_AOMAP":"",parameters.emissiveMap?"#define USE_EMISSIVEMAP":"",parameters.bumpMap?"#define USE_BUMPMAP":"",parameters.normalMap?"#define USE_NORMALMAP":"",parameters.normalMap&¶meters.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",parameters.normalMap&¶meters.tangentSpaceNormalMap?"#define TANGENTSPACE_NORMALMAP":"",parameters.clearcoat?"#define USE_CLEARCOAT":"",parameters.clearcoatMap?"#define USE_CLEARCOATMAP":"",parameters.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",parameters.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",parameters.iridescence?"#define USE_IRIDESCENCE":"",parameters.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",parameters.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",parameters.specularMap?"#define USE_SPECULARMAP":"",parameters.specularIntensityMap?"#define USE_SPECULARINTENSITYMAP":"",parameters.specularColorMap?"#define USE_SPECULARCOLORMAP":"",parameters.roughnessMap?"#define USE_ROUGHNESSMAP":"",parameters.metalnessMap?"#define USE_METALNESSMAP":"",parameters.alphaMap?"#define USE_ALPHAMAP":"",parameters.alphaTest?"#define USE_ALPHATEST":"",parameters.sheen?"#define USE_SHEEN":"",parameters.sheenColorMap?"#define USE_SHEENCOLORMAP":"",parameters.sheenRoughnessMap?"#define USE_SHEENROUGHNESSMAP":"",parameters.transmission?"#define USE_TRANSMISSION":"",parameters.transmissionMap?"#define USE_TRANSMISSIONMAP":"",parameters.thicknessMap?"#define USE_THICKNESSMAP":"",parameters.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",parameters.vertexTangents?"#define USE_TANGENT":"",parameters.vertexColors||parameters.instancingColor?"#define USE_COLOR":"",parameters.vertexAlphas?"#define USE_COLOR_ALPHA":"",parameters.vertexUvs?"#define USE_UV":"",parameters.uvsVertexOnly?"#define UVS_VERTEX_ONLY":"",parameters.gradientMap?"#define USE_GRADIENTMAP":"",parameters.flatShading?"#define FLAT_SHADED":"",parameters.doubleSided?"#define DOUBLE_SIDED":"",parameters.flipSided?"#define FLIP_SIDED":"",parameters.shadowMapEnabled?"#define USE_SHADOWMAP":"",parameters.shadowMapEnabled?"#define "+shadowMapTypeDefine:"",parameters.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",parameters.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",parameters.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",parameters.logarithmicDepthBuffer&¶meters.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",parameters.toneMapping!==NoToneMapping?"#define TONE_MAPPING":"",parameters.toneMapping!==NoToneMapping?ShaderChunk["tonemapping_pars_fragment"]:"",parameters.toneMapping!==NoToneMapping?getToneMappingFunction("toneMapping",parameters.toneMapping):"",parameters.dithering?"#define DITHERING":"",parameters.opaque?"#define OPAQUE":"",ShaderChunk["encodings_pars_fragment"],getTexelEncodingFunction("linearToOutputTexel",parameters.outputEncoding),parameters.useDepthPacking?"#define DEPTH_PACKING "+parameters.depthPacking:"","\n"].filter(filterEmptyLine).join("\n")}vertexShader=resolveIncludes(vertexShader);vertexShader=replaceLightNums(vertexShader,parameters);vertexShader=replaceClippingPlaneNums(vertexShader,parameters);fragmentShader=resolveIncludes(fragmentShader);fragmentShader=replaceLightNums(fragmentShader,parameters);fragmentShader=replaceClippingPlaneNums(fragmentShader,parameters);vertexShader=unrollLoops(vertexShader);fragmentShader=unrollLoops(fragmentShader);if(parameters.isWebGL2&¶meters.isRawShaderMaterial!==true){versionString="#version 300 es\n";prefixVertex=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+prefixVertex;prefixFragment=["#define varying in",parameters.glslVersion===GLSL3?"":"layout(location = 0) out highp vec4 pc_fragColor;",parameters.glslVersion===GLSL3?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+prefixFragment}const vertexGlsl=versionString+prefixVertex+vertexShader;const fragmentGlsl=versionString+prefixFragment+fragmentShader;const glVertexShader=WebGLShader(gl,35633,vertexGlsl);const glFragmentShader=WebGLShader(gl,35632,fragmentGlsl);gl.attachShader(program,glVertexShader);gl.attachShader(program,glFragmentShader);if(parameters.index0AttributeName!==void 0){gl.bindAttribLocation(program,0,parameters.index0AttributeName)}else if(parameters.morphTargets===true){gl.bindAttribLocation(program,0,"position")}gl.linkProgram(program);if(renderer.debug.checkShaderErrors){const programLog=gl.getProgramInfoLog(program).trim();const vertexLog=gl.getShaderInfoLog(glVertexShader).trim();const fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();let runnable=true;let haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;const vertexErrors=getShaderErrors(gl,glVertexShader,"vertex");const fragmentErrors=getShaderErrors(gl,glFragmentShader,"fragment");console.error("THREE.WebGLProgram: Shader Error "+gl.getError()+" - VALIDATE_STATUS "+gl.getProgramParameter(program,35715)+"\n\nProgram Info Log: "+programLog+"\n"+vertexErrors+"\n"+fragmentErrors)}else if(programLog!==""){console.warn("THREE.WebGLProgram: Program Info Log:",programLog)}else if(vertexLog===""||fragmentLog===""){haveDiagnostics=false}if(haveDiagnostics){this.diagnostics={runnable,programLog,vertexShader:{log:vertexLog,prefix:prefixVertex},fragmentShader:{log:fragmentLog,prefix:prefixFragment}}}}gl.deleteShader(glVertexShader);gl.deleteShader(glFragmentShader);let cachedUniforms;this.getUniforms=function(){if(cachedUniforms===void 0){cachedUniforms=new WebGLUniforms(gl,program)}return cachedUniforms};let cachedAttributes;this.getAttributes=function(){if(cachedAttributes===void 0){cachedAttributes=fetchAttributeLocations(gl,program)}return cachedAttributes};this.destroy=function(){bindingStates.releaseStatesOfProgram(this);gl.deleteProgram(program);this.program=void 0};this.name=parameters.shaderName;this.id=programIdCount++;this.cacheKey=cacheKey;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this}var _id=0;var WebGLShaderCache=class{constructor(){this.shaderCache=new Map;this.materialCache=new Map}update(material){const vertexShader=material.vertexShader;const fragmentShader=material.fragmentShader;const vertexShaderStage=this._getShaderStage(vertexShader);const fragmentShaderStage=this._getShaderStage(fragmentShader);const materialShaders=this._getShaderCacheForMaterial(material);if(materialShaders.has(vertexShaderStage)===false){materialShaders.add(vertexShaderStage);vertexShaderStage.usedTimes++}if(materialShaders.has(fragmentShaderStage)===false){materialShaders.add(fragmentShaderStage);fragmentShaderStage.usedTimes++}return this}remove(material){const materialShaders=this.materialCache.get(material);for(const shaderStage of materialShaders){shaderStage.usedTimes--;if(shaderStage.usedTimes===0)this.shaderCache.delete(shaderStage.code)}this.materialCache.delete(material);return this}getVertexShaderID(material){return this._getShaderStage(material.vertexShader).id}getFragmentShaderID(material){return this._getShaderStage(material.fragmentShader).id}dispose(){this.shaderCache.clear();this.materialCache.clear()}_getShaderCacheForMaterial(material){const cache=this.materialCache;if(cache.has(material)===false){cache.set(material,new Set)}return cache.get(material)}_getShaderStage(code){const cache=this.shaderCache;if(cache.has(code)===false){const stage=new WebGLShaderStage(code);cache.set(code,stage)}return cache.get(code)}};var WebGLShaderStage=class{constructor(code){this.id=_id++;this.code=code;this.usedTimes=0}};function WebGLPrograms(renderer,cubemaps,cubeuvmaps,extensions,capabilities,bindingStates,clipping){const _programLayers=new Layers;const _customShaders=new WebGLShaderCache;const programs=[];const isWebGL2=capabilities.isWebGL2;const logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;const vertexTextures=capabilities.vertexTextures;let precision=capabilities.precision;const shaderIDs={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function getParameters(material,lights,shadows,scene,object){const fog=scene.fog;const geometry=object.geometry;const environment=material.isMeshStandardMaterial?scene.environment:null;const envMap=(material.isMeshStandardMaterial?cubeuvmaps:cubemaps).get(material.envMap||environment);const envMapCubeUVHeight=!!envMap&&envMap.mapping===CubeUVReflectionMapping?envMap.image.height:null;const shaderID=shaderIDs[material.type];if(material.precision!==null){precision=capabilities.getMaxPrecision(material.precision);if(precision!==material.precision){console.warn("THREE.WebGLProgram.getParameters:",material.precision,"not supported, using",precision,"instead.")}}const morphAttribute=geometry.morphAttributes.position||geometry.morphAttributes.normal||geometry.morphAttributes.color;const morphTargetsCount=morphAttribute!==void 0?morphAttribute.length:0;let morphTextureStride=0;if(geometry.morphAttributes.position!==void 0)morphTextureStride=1;if(geometry.morphAttributes.normal!==void 0)morphTextureStride=2;if(geometry.morphAttributes.color!==void 0)morphTextureStride=3;let vertexShader,fragmentShader;let customVertexShaderID,customFragmentShaderID;if(shaderID){const shader=ShaderLib[shaderID];vertexShader=shader.vertexShader;fragmentShader=shader.fragmentShader}else{vertexShader=material.vertexShader;fragmentShader=material.fragmentShader;_customShaders.update(material);customVertexShaderID=_customShaders.getVertexShaderID(material);customFragmentShaderID=_customShaders.getFragmentShaderID(material)}const currentRenderTarget=renderer.getRenderTarget();const useAlphaTest=material.alphaTest>0;const useClearcoat=material.clearcoat>0;const useIridescence=material.iridescence>0;const parameters={isWebGL2,shaderID,shaderName:material.type,vertexShader,fragmentShader,defines:material.defines,customVertexShaderID,customFragmentShaderID,isRawShaderMaterial:material.isRawShaderMaterial===true,glslVersion:material.glslVersion,precision,instancing:object.isInstancedMesh===true,instancingColor:object.isInstancedMesh===true&&object.instanceColor!==null,supportsVertexTextures:vertexTextures,outputEncoding:currentRenderTarget===null?renderer.outputEncoding:currentRenderTarget.isXRRenderTarget===true?currentRenderTarget.texture.encoding:LinearEncoding,map:!!material.map,matcap:!!material.matcap,envMap:!!envMap,envMapMode:envMap&&envMap.mapping,envMapCubeUVHeight,lightMap:!!material.lightMap,aoMap:!!material.aoMap,emissiveMap:!!material.emissiveMap,bumpMap:!!material.bumpMap,normalMap:!!material.normalMap,objectSpaceNormalMap:material.normalMapType===ObjectSpaceNormalMap,tangentSpaceNormalMap:material.normalMapType===TangentSpaceNormalMap,decodeVideoTexture:!!material.map&&material.map.isVideoTexture===true&&material.map.encoding===sRGBEncoding,clearcoat:useClearcoat,clearcoatMap:useClearcoat&&!!material.clearcoatMap,clearcoatRoughnessMap:useClearcoat&&!!material.clearcoatRoughnessMap,clearcoatNormalMap:useClearcoat&&!!material.clearcoatNormalMap,iridescence:useIridescence,iridescenceMap:useIridescence&&!!material.iridescenceMap,iridescenceThicknessMap:useIridescence&&!!material.iridescenceThicknessMap,displacementMap:!!material.displacementMap,roughnessMap:!!material.roughnessMap,metalnessMap:!!material.metalnessMap,specularMap:!!material.specularMap,specularIntensityMap:!!material.specularIntensityMap,specularColorMap:!!material.specularColorMap,opaque:material.transparent===false&&material.blending===NormalBlending,alphaMap:!!material.alphaMap,alphaTest:useAlphaTest,gradientMap:!!material.gradientMap,sheen:material.sheen>0,sheenColorMap:!!material.sheenColorMap,sheenRoughnessMap:!!material.sheenRoughnessMap,transmission:material.transmission>0,transmissionMap:!!material.transmissionMap,thicknessMap:!!material.thicknessMap,combine:material.combine,vertexTangents:!!material.normalMap&&!!geometry.attributes.tangent,vertexColors:material.vertexColors,vertexAlphas:material.vertexColors===true&&!!geometry.attributes.color&&geometry.attributes.color.itemSize===4,vertexUvs:!!material.map||!!material.bumpMap||!!material.normalMap||!!material.specularMap||!!material.alphaMap||!!material.emissiveMap||!!material.roughnessMap||!!material.metalnessMap||!!material.clearcoatMap||!!material.clearcoatRoughnessMap||!!material.clearcoatNormalMap||!!material.iridescenceMap||!!material.iridescenceThicknessMap||!!material.displacementMap||!!material.transmissionMap||!!material.thicknessMap||!!material.specularIntensityMap||!!material.specularColorMap||!!material.sheenColorMap||!!material.sheenRoughnessMap,uvsVertexOnly:!(!!material.map||!!material.bumpMap||!!material.normalMap||!!material.specularMap||!!material.alphaMap||!!material.emissiveMap||!!material.roughnessMap||!!material.metalnessMap||!!material.clearcoatNormalMap||!!material.iridescenceMap||!!material.iridescenceThicknessMap||material.transmission>0||!!material.transmissionMap||!!material.thicknessMap||!!material.specularIntensityMap||!!material.specularColorMap||material.sheen>0||!!material.sheenColorMap||!!material.sheenRoughnessMap)&&!!material.displacementMap,fog:!!fog,useFog:material.fog===true,fogExp2:fog&&fog.isFogExp2,flatShading:!!material.flatShading,sizeAttenuation:material.sizeAttenuation,logarithmicDepthBuffer,skinning:object.isSkinnedMesh===true,morphTargets:geometry.morphAttributes.position!==void 0,morphNormals:geometry.morphAttributes.normal!==void 0,morphColors:geometry.morphAttributes.color!==void 0,morphTargetsCount,morphTextureStride,numDirLights:lights.directional.length,numPointLights:lights.point.length,numSpotLights:lights.spot.length,numRectAreaLights:lights.rectArea.length,numHemiLights:lights.hemi.length,numDirLightShadows:lights.directionalShadowMap.length,numPointLightShadows:lights.pointShadowMap.length,numSpotLightShadows:lights.spotShadowMap.length,numClippingPlanes:clipping.numPlanes,numClipIntersection:clipping.numIntersection,dithering:material.dithering,shadowMapEnabled:renderer.shadowMap.enabled&&shadows.length>0,shadowMapType:renderer.shadowMap.type,toneMapping:material.toneMapped?renderer.toneMapping:NoToneMapping,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,doubleSided:material.side===DoubleSide,flipSided:material.side===BackSide,useDepthPacking:!!material.depthPacking,depthPacking:material.depthPacking||0,index0AttributeName:material.index0AttributeName,extensionDerivatives:material.extensions&&material.extensions.derivatives,extensionFragDepth:material.extensions&&material.extensions.fragDepth,extensionDrawBuffers:material.extensions&&material.extensions.drawBuffers,extensionShaderTextureLOD:material.extensions&&material.extensions.shaderTextureLOD,rendererExtensionFragDepth:isWebGL2||extensions.has("EXT_frag_depth"),rendererExtensionDrawBuffers:isWebGL2||extensions.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:isWebGL2||extensions.has("EXT_shader_texture_lod"),customProgramCacheKey:material.customProgramCacheKey()};return parameters}function getProgramCacheKey(parameters){const array=[];if(parameters.shaderID){array.push(parameters.shaderID)}else{array.push(parameters.customVertexShaderID);array.push(parameters.customFragmentShaderID)}if(parameters.defines!==void 0){for(const name in parameters.defines){array.push(name);array.push(parameters.defines[name])}}if(parameters.isRawShaderMaterial===false){getProgramCacheKeyParameters(array,parameters);getProgramCacheKeyBooleans(array,parameters);array.push(renderer.outputEncoding)}array.push(parameters.customProgramCacheKey);return array.join()}function getProgramCacheKeyParameters(array,parameters){array.push(parameters.precision);array.push(parameters.outputEncoding);array.push(parameters.envMapMode);array.push(parameters.envMapCubeUVHeight);array.push(parameters.combine);array.push(parameters.vertexUvs);array.push(parameters.fogExp2);array.push(parameters.sizeAttenuation);array.push(parameters.morphTargetsCount);array.push(parameters.morphAttributeCount);array.push(parameters.numDirLights);array.push(parameters.numPointLights);array.push(parameters.numSpotLights);array.push(parameters.numHemiLights);array.push(parameters.numRectAreaLights);array.push(parameters.numDirLightShadows);array.push(parameters.numPointLightShadows);array.push(parameters.numSpotLightShadows);array.push(parameters.shadowMapType);array.push(parameters.toneMapping);array.push(parameters.numClippingPlanes);array.push(parameters.numClipIntersection);array.push(parameters.depthPacking)}function getProgramCacheKeyBooleans(array,parameters){_programLayers.disableAll();if(parameters.isWebGL2)_programLayers.enable(0);if(parameters.supportsVertexTextures)_programLayers.enable(1);if(parameters.instancing)_programLayers.enable(2);if(parameters.instancingColor)_programLayers.enable(3);if(parameters.map)_programLayers.enable(4);if(parameters.matcap)_programLayers.enable(5);if(parameters.envMap)_programLayers.enable(6);if(parameters.lightMap)_programLayers.enable(7);if(parameters.aoMap)_programLayers.enable(8);if(parameters.emissiveMap)_programLayers.enable(9);if(parameters.bumpMap)_programLayers.enable(10);if(parameters.normalMap)_programLayers.enable(11);if(parameters.objectSpaceNormalMap)_programLayers.enable(12);if(parameters.tangentSpaceNormalMap)_programLayers.enable(13);if(parameters.clearcoat)_programLayers.enable(14);if(parameters.clearcoatMap)_programLayers.enable(15);if(parameters.clearcoatRoughnessMap)_programLayers.enable(16);if(parameters.clearcoatNormalMap)_programLayers.enable(17);if(parameters.iridescence)_programLayers.enable(18);if(parameters.iridescenceMap)_programLayers.enable(19);if(parameters.iridescenceThicknessMap)_programLayers.enable(20);if(parameters.displacementMap)_programLayers.enable(21);if(parameters.specularMap)_programLayers.enable(22);if(parameters.roughnessMap)_programLayers.enable(23);if(parameters.metalnessMap)_programLayers.enable(24);if(parameters.gradientMap)_programLayers.enable(25);if(parameters.alphaMap)_programLayers.enable(26);if(parameters.alphaTest)_programLayers.enable(27);if(parameters.vertexColors)_programLayers.enable(28);if(parameters.vertexAlphas)_programLayers.enable(29);if(parameters.vertexUvs)_programLayers.enable(30);if(parameters.vertexTangents)_programLayers.enable(31);if(parameters.uvsVertexOnly)_programLayers.enable(32);if(parameters.fog)_programLayers.enable(33);array.push(_programLayers.mask);_programLayers.disableAll();if(parameters.useFog)_programLayers.enable(0);if(parameters.flatShading)_programLayers.enable(1);if(parameters.logarithmicDepthBuffer)_programLayers.enable(2);if(parameters.skinning)_programLayers.enable(3);if(parameters.morphTargets)_programLayers.enable(4);if(parameters.morphNormals)_programLayers.enable(5);if(parameters.morphColors)_programLayers.enable(6);if(parameters.premultipliedAlpha)_programLayers.enable(7);if(parameters.shadowMapEnabled)_programLayers.enable(8);if(parameters.physicallyCorrectLights)_programLayers.enable(9);if(parameters.doubleSided)_programLayers.enable(10);if(parameters.flipSided)_programLayers.enable(11);if(parameters.useDepthPacking)_programLayers.enable(12);if(parameters.dithering)_programLayers.enable(13);if(parameters.specularIntensityMap)_programLayers.enable(14);if(parameters.specularColorMap)_programLayers.enable(15);if(parameters.transmission)_programLayers.enable(16);if(parameters.transmissionMap)_programLayers.enable(17);if(parameters.thicknessMap)_programLayers.enable(18);if(parameters.sheen)_programLayers.enable(19);if(parameters.sheenColorMap)_programLayers.enable(20);if(parameters.sheenRoughnessMap)_programLayers.enable(21);if(parameters.decodeVideoTexture)_programLayers.enable(22);if(parameters.opaque)_programLayers.enable(23);array.push(_programLayers.mask)}function getUniforms(material){const shaderID=shaderIDs[material.type];let uniforms;if(shaderID){const shader=ShaderLib[shaderID];uniforms=UniformsUtils.clone(shader.uniforms)}else{uniforms=material.uniforms}return uniforms}function acquireProgram(parameters,cacheKey){let program;for(let p=0,pl=programs.length;p0){transmissive.push(renderItem)}else if(material.transparent===true){transparent.push(renderItem)}else{opaque.push(renderItem)}}function unshift(object,geometry,material,groupOrder,z,group){const renderItem=getNextRenderItem(object,geometry,material,groupOrder,z,group);if(material.transmission>0){transmissive.unshift(renderItem)}else if(material.transparent===true){transparent.unshift(renderItem)}else{opaque.unshift(renderItem)}}function sort(customOpaqueSort,customTransparentSort){if(opaque.length>1)opaque.sort(customOpaqueSort||painterSortStable);if(transmissive.length>1)transmissive.sort(customTransparentSort||reversePainterSortStable);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable)}function finish(){for(let i=renderItemsIndex,il=renderItems.length;i=lists.get(scene).length){list=new WebGLRenderList;lists.get(scene).push(list)}else{list=lists.get(scene)[renderCallDepth]}}return list}function dispose(){lists=new WeakMap}return{get:get3,dispose}}function UniformsCache(){const lights={};return{get:function(light){if(lights[light.id]!==void 0){return lights[light.id]}let uniforms;switch(light.type){case"DirectionalLight":uniforms={direction:new Vector3,color:new Color};break;case"SpotLight":uniforms={position:new Vector3,direction:new Vector3,color:new Color,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":uniforms={position:new Vector3,color:new Color,distance:0,decay:0};break;case"HemisphereLight":uniforms={direction:new Vector3,skyColor:new Color,groundColor:new Color};break;case"RectAreaLight":uniforms={color:new Color,position:new Vector3,halfWidth:new Vector3,halfHeight:new Vector3};break}lights[light.id]=uniforms;return uniforms}}}function ShadowUniformsCache(){const lights={};return{get:function(light){if(lights[light.id]!==void 0){return lights[light.id]}let uniforms;switch(light.type){case"DirectionalLight":uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"SpotLight":uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2};break;case"PointLight":uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2,shadowCameraNear:1,shadowCameraFar:1e3};break}lights[light.id]=uniforms;return uniforms}}}var nextVersion=0;function shadowCastingLightsFirst(lightA,lightB){return(lightB.castShadow?1:0)-(lightA.castShadow?1:0)}function WebGLLights(extensions,capabilities){const cache=new UniformsCache;const shadowCache=ShadowUniformsCache();const state={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(let i=0;i<9;i++)state.probe.push(new Vector3);const vector3=new Vector3;const matrix4=new Matrix4;const matrix42=new Matrix4;function setup(lights,physicallyCorrectLights){let r=0,g=0,b=0;for(let i=0;i<9;i++)state.probe[i].set(0,0,0);let directionalLength=0;let pointLength=0;let spotLength=0;let rectAreaLength=0;let hemiLength=0;let numDirectionalShadows=0;let numPointShadows=0;let numSpotShadows=0;lights.sort(shadowCastingLightsFirst);const scaleFactor=physicallyCorrectLights!==true?Math.PI:1;for(let i=0,l=lights.length;i0){if(capabilities.isWebGL2){state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2}else{if(extensions.has("OES_texture_float_linear")===true){state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2}else if(extensions.has("OES_texture_half_float_linear")===true){state.rectAreaLTC1=UniformsLib.LTC_HALF_1;state.rectAreaLTC2=UniformsLib.LTC_HALF_2}else{console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")}}}state.ambient[0]=r;state.ambient[1]=g;state.ambient[2]=b;const hash=state.hash;if(hash.directionalLength!==directionalLength||hash.pointLength!==pointLength||hash.spotLength!==spotLength||hash.rectAreaLength!==rectAreaLength||hash.hemiLength!==hemiLength||hash.numDirectionalShadows!==numDirectionalShadows||hash.numPointShadows!==numPointShadows||hash.numSpotShadows!==numSpotShadows){state.directional.length=directionalLength;state.spot.length=spotLength;state.rectArea.length=rectAreaLength;state.point.length=pointLength;state.hemi.length=hemiLength;state.directionalShadow.length=numDirectionalShadows;state.directionalShadowMap.length=numDirectionalShadows;state.pointShadow.length=numPointShadows;state.pointShadowMap.length=numPointShadows;state.spotShadow.length=numSpotShadows;state.spotShadowMap.length=numSpotShadows;state.directionalShadowMatrix.length=numDirectionalShadows;state.pointShadowMatrix.length=numPointShadows;state.spotShadowMatrix.length=numSpotShadows;hash.directionalLength=directionalLength;hash.pointLength=pointLength;hash.spotLength=spotLength;hash.rectAreaLength=rectAreaLength;hash.hemiLength=hemiLength;hash.numDirectionalShadows=numDirectionalShadows;hash.numPointShadows=numPointShadows;hash.numSpotShadows=numSpotShadows;state.version=nextVersion++}}function setupView(lights,camera){let directionalLength=0;let pointLength=0;let spotLength=0;let rectAreaLength=0;let hemiLength=0;const viewMatrix=camera.matrixWorldInverse;for(let i=0,l=lights.length;i=renderStates.get(scene).length){renderState=new WebGLRenderState(extensions,capabilities);renderStates.get(scene).push(renderState)}else{renderState=renderStates.get(scene)[renderCallDepth]}}return renderState}function dispose(){renderStates=new WeakMap}return{get:get3,dispose}}var MeshDepthMaterial=class extends Material{constructor(parameters){super();this.isMeshDepthMaterial=true;this.type="MeshDepthMaterial";this.depthPacking=BasicDepthPacking;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.setValues(parameters)}copy(source){super.copy(source);this.depthPacking=source.depthPacking;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;return this}};var MeshDistanceMaterial=class extends Material{constructor(parameters){super();this.isMeshDistanceMaterial=true;this.type="MeshDistanceMaterial";this.referencePosition=new Vector3;this.nearDistance=1;this.farDistance=1e3;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.setValues(parameters)}copy(source){super.copy(source);this.referencePosition.copy(source.referencePosition);this.nearDistance=source.nearDistance;this.farDistance=source.farDistance;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;return this}};var vertex="void main() {\n gl_Position = vec4( position, 1.0 );\n}";var fragment="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n const float samples = float( VSM_SAMPLES );\n float mean = 0.0;\n float squared_mean = 0.0;\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n for ( float i = 0.0; i < samples; i ++ ) {\n float uvOffset = uvStart + i * uvStride;\n #ifdef HORIZONTAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean / samples;\n squared_mean = squared_mean / samples;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";function WebGLShadowMap(_renderer,_objects,_capabilities){let _frustum=new Frustum;const _shadowMapSize=new Vector2,_viewportSize=new Vector2,_viewport=new Vector4,_depthMaterial=new MeshDepthMaterial({depthPacking:RGBADepthPacking}),_distanceMaterial=new MeshDistanceMaterial,_materialCache={},_maxTextureSize=_capabilities.maxTextureSize;const shadowSide={0:BackSide,1:FrontSide,2:DoubleSide};const shadowMaterialVertical=new ShaderMaterial({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2},radius:{value:4}},vertexShader:vertex,fragmentShader:fragment});const shadowMaterialHorizontal=shadowMaterialVertical.clone();shadowMaterialHorizontal.defines.HORIZONTAL_PASS=1;const fullScreenTri=new BufferGeometry;fullScreenTri.setAttribute("position",new BufferAttribute(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const fullScreenMesh=new Mesh(fullScreenTri,shadowMaterialVertical);const scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap;this.render=function(lights,scene,camera){if(scope.enabled===false)return;if(scope.autoUpdate===false&&scope.needsUpdate===false)return;if(lights.length===0)return;const currentRenderTarget=_renderer.getRenderTarget();const activeCubeFace=_renderer.getActiveCubeFace();const activeMipmapLevel=_renderer.getActiveMipmapLevel();const _state=_renderer.state;_state.setBlending(NoBlending);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);for(let i=0,il=lights.length;i_maxTextureSize||_shadowMapSize.y>_maxTextureSize){if(_shadowMapSize.x>_maxTextureSize){_viewportSize.x=Math.floor(_maxTextureSize/shadowFrameExtents.x);_shadowMapSize.x=_viewportSize.x*shadowFrameExtents.x;shadow.mapSize.x=_viewportSize.x}if(_shadowMapSize.y>_maxTextureSize){_viewportSize.y=Math.floor(_maxTextureSize/shadowFrameExtents.y);_shadowMapSize.y=_viewportSize.y*shadowFrameExtents.y;shadow.mapSize.y=_viewportSize.y}}if(shadow.map===null){const pars=this.type!==VSMShadowMap?{minFilter:NearestFilter,magFilter:NearestFilter}:{};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+".shadowMap";shadow.camera.updateProjectionMatrix()}_renderer.setRenderTarget(shadow.map);_renderer.clear();const viewportCount=shadow.getViewportCount();for(let vp=0;vp0){const keyA=result.uuid,keyB=material.uuid;let materialsForVariant=_materialCache[keyA];if(materialsForVariant===void 0){materialsForVariant={};_materialCache[keyA]=materialsForVariant}let cachedMaterial=materialsForVariant[keyB];if(cachedMaterial===void 0){cachedMaterial=result.clone();materialsForVariant[keyB]=cachedMaterial}result=cachedMaterial}result.visible=material.visible;result.wireframe=material.wireframe;if(type===VSMShadowMap){result.side=material.shadowSide!==null?material.shadowSide:material.side}else{result.side=material.shadowSide!==null?material.shadowSide:shadowSide[material.side]}result.alphaMap=material.alphaMap;result.alphaTest=material.alphaTest;result.clipShadows=material.clipShadows;result.clippingPlanes=material.clippingPlanes;result.clipIntersection=material.clipIntersection;result.displacementMap=material.displacementMap;result.displacementScale=material.displacementScale;result.displacementBias=material.displacementBias;result.wireframeLinewidth=material.wireframeLinewidth;result.linewidth=material.linewidth;if(light.isPointLight===true&&result.isMeshDistanceMaterial===true){result.referencePosition.setFromMatrixPosition(light.matrixWorld);result.nearDistance=shadowCameraNear;result.farDistance=shadowCameraFar}return result}function renderObject(object,camera,shadowCamera,light,type){if(object.visible===false)return;const visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if((object.castShadow||object.receiveShadow&&type===VSMShadowMap)&&(!object.frustumCulled||_frustum.intersectsObject(object))){object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse,object.matrixWorld);const geometry=_objects.update(object);const material=object.material;if(Array.isArray(material)){const groups=geometry.groups;for(let k=0,kl=groups.length;k=1}else if(glVersion.indexOf("OpenGL ES")!==-1){version=parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);lineWidthAvailable=version>=2}let currentTextureSlot=null;let currentBoundTextures={};const scissorParam=gl.getParameter(3088);const viewportParam=gl.getParameter(2978);const currentScissor=new Vector4().fromArray(scissorParam);const currentViewport=new Vector4().fromArray(viewportParam);function createTexture(type,target,count){const data=new Uint8Array(4);const texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(let i=0;imaxSize||image.height>maxSize){scale=maxSize/Math.max(image.width,image.height)}if(scale<1||needsPowerOfTwo===true){if(typeof HTMLImageElement!=="undefined"&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&image instanceof ImageBitmap){const floor=needsPowerOfTwo?floorPowerOfTwo:Math.floor;const width=floor(scale*image.width);const height=floor(scale*image.height);if(_canvas2===void 0)_canvas2=createCanvas(width,height);const canvas=needsNewCanvas?createCanvas(width,height):_canvas2;canvas.width=width;canvas.height=height;const context=canvas.getContext("2d");context.drawImage(image,0,0,width,height);console.warn("THREE.WebGLRenderer: Texture has been resized from ("+image.width+"x"+image.height+") to ("+width+"x"+height+").");return canvas}else{if("data"in image){console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+image.width+"x"+image.height+").")}return image}}return image}function isPowerOfTwo$1(image){return isPowerOfTwo(image.width)&&isPowerOfTwo(image.height)}function textureNeedsPowerOfTwo(texture){if(isWebGL2)return false;return texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping||texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter}function textureNeedsGenerateMipmaps(texture,supportsMips){return texture.generateMipmaps&&supportsMips&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter}function generateMipmap(target){_gl.generateMipmap(target)}function getInternalFormat(internalFormatName,glFormat,glType,encoding,isVideoTexture=false){if(isWebGL2===false)return glFormat;if(internalFormatName!==null){if(_gl[internalFormatName]!==void 0)return _gl[internalFormatName];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+internalFormatName+"'")}let internalFormat=glFormat;if(glFormat===6403){if(glType===5126)internalFormat=33326;if(glType===5131)internalFormat=33325;if(glType===5121)internalFormat=33321}if(glFormat===33319){if(glType===5126)internalFormat=33328;if(glType===5131)internalFormat=33327;if(glType===5121)internalFormat=33323}if(glFormat===6408){if(glType===5126)internalFormat=34836;if(glType===5131)internalFormat=34842;if(glType===5121)internalFormat=encoding===sRGBEncoding&&isVideoTexture===false?35907:32856;if(glType===32819)internalFormat=32854;if(glType===32820)internalFormat=32855}if(internalFormat===33325||internalFormat===33326||internalFormat===33327||internalFormat===33328||internalFormat===34842||internalFormat===34836){extensions.get("EXT_color_buffer_float")}return internalFormat}function getMipLevels(texture,image,supportsMips){if(textureNeedsGenerateMipmaps(texture,supportsMips)===true||texture.isFramebufferTexture&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){return Math.log2(Math.max(image.width,image.height))+1}else if(texture.mipmaps!==void 0&&texture.mipmaps.length>0){return texture.mipmaps.length}else if(texture.isCompressedTexture&&Array.isArray(texture.image)){return image.mipmaps.length}else{return 1}}function filterFallback(f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return 9728}return 9729}function onTextureDispose(event){const texture=event.target;texture.removeEventListener("dispose",onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture)}}function onRenderTargetDispose(event){const renderTarget=event.target;renderTarget.removeEventListener("dispose",onRenderTargetDispose);deallocateRenderTarget(renderTarget)}function deallocateTexture(texture){const textureProperties=properties.get(texture);if(textureProperties.__webglInit===void 0)return;const source=texture.source;const webglTextures=_sources.get(source);if(webglTextures){const webglTexture=webglTextures[textureProperties.__cacheKey];webglTexture.usedTimes--;if(webglTexture.usedTimes===0){deleteTexture(texture)}if(Object.keys(webglTextures).length===0){_sources.delete(source)}}properties.remove(texture)}function deleteTexture(texture){const textureProperties=properties.get(texture);_gl.deleteTexture(textureProperties.__webglTexture);const source=texture.source;const webglTextures=_sources.get(source);delete webglTextures[textureProperties.__cacheKey];info2.memory.textures--}function deallocateRenderTarget(renderTarget){const texture=renderTarget.texture;const renderTargetProperties=properties.get(renderTarget);const textureProperties=properties.get(texture);if(textureProperties.__webglTexture!==void 0){_gl.deleteTexture(textureProperties.__webglTexture);info2.memory.textures--}if(renderTarget.depthTexture){renderTarget.depthTexture.dispose()}if(renderTarget.isWebGLCubeRenderTarget){for(let i=0;i<6;i++){_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i])}}else{_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);if(renderTargetProperties.__webglMultisampledFramebuffer)_gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);if(renderTargetProperties.__webglColorRenderbuffer){for(let i=0;i=maxTextures){console.warn("THREE.WebGLTextures: Trying to use "+textureUnit+" texture units while this GPU supports only "+maxTextures)}textureUnits+=1;return textureUnit}function getTextureCacheKey(texture){const array=[];array.push(texture.wrapS);array.push(texture.wrapT);array.push(texture.magFilter);array.push(texture.minFilter);array.push(texture.anisotropy);array.push(texture.internalFormat);array.push(texture.format);array.push(texture.type);array.push(texture.generateMipmaps);array.push(texture.premultiplyAlpha);array.push(texture.flipY);array.push(texture.unpackAlignment);array.push(texture.encoding);return array.join()}function setTexture2D(texture,slot){const textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(texture);if(texture.isRenderTargetTexture===false&&texture.version>0&&textureProperties.__version!==texture.version){const image=texture.image;if(image===null){console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.")}else if(image.complete===false){console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}else{uploadTexture(textureProperties,texture,slot);return}}state.activeTexture(33984+slot);state.bindTexture(3553,textureProperties.__webglTexture)}function setTexture2DArray(texture,slot){const textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return}state.activeTexture(33984+slot);state.bindTexture(35866,textureProperties.__webglTexture)}function setTexture3D(texture,slot){const textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return}state.activeTexture(33984+slot);state.bindTexture(32879,textureProperties.__webglTexture)}function setTextureCube(texture,slot){const textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadCubeTexture(textureProperties,texture,slot);return}state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture)}const wrappingToGL={[RepeatWrapping]:10497,[ClampToEdgeWrapping]:33071,[MirroredRepeatWrapping]:33648};const filterToGL={[NearestFilter]:9728,[NearestMipmapNearestFilter]:9984,[NearestMipmapLinearFilter]:9986,[LinearFilter]:9729,[LinearMipmapNearestFilter]:9985,[LinearMipmapLinearFilter]:9987};function setTextureParameters(textureType,texture,supportsMips){if(supportsMips){_gl.texParameteri(textureType,10242,wrappingToGL[texture.wrapS]);_gl.texParameteri(textureType,10243,wrappingToGL[texture.wrapT]);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,wrappingToGL[texture.wrapR])}_gl.texParameteri(textureType,10240,filterToGL[texture.magFilter]);_gl.texParameteri(textureType,10241,filterToGL[texture.minFilter])}else{_gl.texParameteri(textureType,10242,33071);_gl.texParameteri(textureType,10243,33071);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,33071)}if(texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping){console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.")}_gl.texParameteri(textureType,10240,filterFallback(texture.magFilter));_gl.texParameteri(textureType,10241,filterFallback(texture.minFilter));if(texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")}}if(extensions.has("EXT_texture_filter_anisotropic")===true){const extension=extensions.get("EXT_texture_filter_anisotropic");if(texture.type===FloatType&&extensions.has("OES_texture_float_linear")===false)return;if(isWebGL2===false&&(texture.type===HalfFloatType&&extensions.has("OES_texture_half_float_linear")===false))return;if(texture.anisotropy>1||properties.get(texture).__currentAnisotropy){_gl.texParameterf(textureType,extension.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(texture.anisotropy,capabilities.getMaxAnisotropy()));properties.get(texture).__currentAnisotropy=texture.anisotropy}}}function initTexture(textureProperties,texture){let forceUpload=false;if(textureProperties.__webglInit===void 0){textureProperties.__webglInit=true;texture.addEventListener("dispose",onTextureDispose)}const source=texture.source;let webglTextures=_sources.get(source);if(webglTextures===void 0){webglTextures={};_sources.set(source,webglTextures)}const textureCacheKey=getTextureCacheKey(texture);if(textureCacheKey!==textureProperties.__cacheKey){if(webglTextures[textureCacheKey]===void 0){webglTextures[textureCacheKey]={texture:_gl.createTexture(),usedTimes:0};info2.memory.textures++;forceUpload=true}webglTextures[textureCacheKey].usedTimes++;const webglTexture=webglTextures[textureProperties.__cacheKey];if(webglTexture!==void 0){webglTextures[textureProperties.__cacheKey].usedTimes--;if(webglTexture.usedTimes===0){deleteTexture(texture)}}textureProperties.__cacheKey=textureCacheKey;textureProperties.__webglTexture=webglTextures[textureCacheKey].texture}return forceUpload}function uploadTexture(textureProperties,texture,slot){let textureType=3553;if(texture.isDataArrayTexture)textureType=35866;if(texture.isData3DTexture)textureType=32879;const forceUpload=initTexture(textureProperties,texture);const source=texture.source;state.activeTexture(33984+slot);state.bindTexture(textureType,textureProperties.__webglTexture);if(source.version!==source.__currentVersion||forceUpload===true){_gl.pixelStorei(37440,texture.flipY);_gl.pixelStorei(37441,texture.premultiplyAlpha);_gl.pixelStorei(3317,texture.unpackAlignment);_gl.pixelStorei(37443,0);const needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo$1(texture.image)===false;let image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);image=verifyColorSpace(texture,image);const supportsMips=isPowerOfTwo$1(image)||isWebGL2,glFormat=utils.convert(texture.format,texture.encoding);let glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType,texture.encoding,texture.isVideoTexture);setTextureParameters(textureType,texture,supportsMips);let mipmap;const mipmaps=texture.mipmaps;const useTexStorage=isWebGL2&&texture.isVideoTexture!==true;const allocateMemory=source.__currentVersion===void 0||forceUpload===true;const levels=getMipLevels(texture,image,supportsMips);if(texture.isDepthTexture){glInternalFormat=6402;if(isWebGL2){if(texture.type===FloatType){glInternalFormat=36012}else if(texture.type===UnsignedIntType){glInternalFormat=33190}else if(texture.type===UnsignedInt248Type){glInternalFormat=35056}else{glInternalFormat=33189}}else{if(texture.type===FloatType){console.error("WebGLRenderer: Floating point depth texture requires WebGL2.")}}if(texture.format===DepthFormat&&glInternalFormat===6402){if(texture.type!==UnsignedShortType&&texture.type!==UnsignedIntType){console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.");texture.type=UnsignedIntType;glType=utils.convert(texture.type)}}if(texture.format===DepthStencilFormat&&glInternalFormat===6402){glInternalFormat=34041;if(texture.type!==UnsignedInt248Type){console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.");texture.type=UnsignedInt248Type;glType=utils.convert(texture.type)}}if(allocateMemory){if(useTexStorage){state.texStorage2D(3553,1,glInternalFormat,image.width,image.height)}else{state.texImage2D(3553,0,glInternalFormat,image.width,image.height,0,glFormat,glType,null)}}}else if(texture.isDataTexture){if(mipmaps.length>0&&supportsMips){if(useTexStorage&&allocateMemory){state.texStorage2D(3553,levels,glInternalFormat,mipmaps[0].width,mipmaps[0].height)}for(let i=0,il=mipmaps.length;i>=1;height>>=1}}}}else{if(mipmaps.length>0&&supportsMips){if(useTexStorage&&allocateMemory){state.texStorage2D(3553,levels,glInternalFormat,mipmaps[0].width,mipmaps[0].height)}for(let i=0,il=mipmaps.length;i0)levels++;state.texStorage2D(34067,levels,glInternalFormat,cubeImage[0].width,cubeImage[0].height)}for(let i=0;i<6;i++){if(isDataTexture){if(useTexStorage){state.texSubImage2D(34069+i,0,0,0,cubeImage[i].width,cubeImage[i].height,glFormat,glType,cubeImage[i].data)}else{state.texImage2D(34069+i,0,glInternalFormat,cubeImage[i].width,cubeImage[i].height,0,glFormat,glType,cubeImage[i].data)}for(let j=0;j0&&useMultisampledRTT(renderTarget)===false){const textures=isMultipleRenderTargets?texture:[texture];renderTargetProperties.__webglMultisampledFramebuffer=_gl.createFramebuffer();renderTargetProperties.__webglColorRenderbuffer=[];state.bindFramebuffer(36160,renderTargetProperties.__webglMultisampledFramebuffer);for(let i=0;i0&&useMultisampledRTT(renderTarget)===false){const textures=renderTarget.isWebGLMultipleRenderTargets?renderTarget.texture:[renderTarget.texture];const width=renderTarget.width;const height=renderTarget.height;let mask=16384;const invalidationArray=[];const depthStyle=renderTarget.stencilBuffer?33306:36096;const renderTargetProperties=properties.get(renderTarget);const isMultipleRenderTargets=renderTarget.isWebGLMultipleRenderTargets===true;if(isMultipleRenderTargets){for(let i=0;i0&&extensions.has("WEBGL_multisampled_render_to_texture")===true&&renderTargetProperties.__useRenderToTexture!==false}function updateVideoTexture(texture){const frame=info2.render.frame;if(_videoTextures.get(texture)!==frame){_videoTextures.set(texture,frame);texture.update()}}function verifyColorSpace(texture,image){const encoding=texture.encoding;const format=texture.format;const type=texture.type;if(texture.isCompressedTexture===true||texture.isVideoTexture===true||texture.format===_SRGBAFormat)return image;if(encoding!==LinearEncoding){if(encoding===sRGBEncoding){if(isWebGL2===false){if(extensions.has("EXT_sRGB")===true&&format===RGBAFormat){texture.format=_SRGBAFormat;texture.minFilter=LinearFilter;texture.generateMipmaps=false}else{image=ImageUtils.sRGBToLinear(image)}}else{if(format!==RGBAFormat||type!==UnsignedByteType){console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}}}else{console.error("THREE.WebGLTextures: Unsupported texture encoding:",encoding)}}return image}this.allocateTextureUnit=allocateTextureUnit;this.resetTextureUnits=resetTextureUnits;this.setTexture2D=setTexture2D;this.setTexture2DArray=setTexture2DArray;this.setTexture3D=setTexture3D;this.setTextureCube=setTextureCube;this.rebindTextures=rebindTextures;this.setupRenderTarget=setupRenderTarget;this.updateRenderTargetMipmap=updateRenderTargetMipmap;this.updateMultisampleRenderTarget=updateMultisampleRenderTarget;this.setupDepthRenderbuffer=setupDepthRenderbuffer;this.setupFrameBufferTexture=setupFrameBufferTexture;this.useMultisampledRTT=useMultisampledRTT}function WebGLUtils(gl,extensions,capabilities){const isWebGL2=capabilities.isWebGL2;function convert(p,encoding=null){let extension;if(p===UnsignedByteType)return 5121;if(p===UnsignedShort4444Type)return 32819;if(p===UnsignedShort5551Type)return 32820;if(p===ByteType)return 5120;if(p===ShortType)return 5122;if(p===UnsignedShortType)return 5123;if(p===IntType)return 5124;if(p===UnsignedIntType)return 5125;if(p===FloatType)return 5126;if(p===HalfFloatType){if(isWebGL2)return 5131;extension=extensions.get("OES_texture_half_float");if(extension!==null){return extension.HALF_FLOAT_OES}else{return null}}if(p===AlphaFormat)return 6406;if(p===RGBAFormat)return 6408;if(p===LuminanceFormat)return 6409;if(p===LuminanceAlphaFormat)return 6410;if(p===DepthFormat)return 6402;if(p===DepthStencilFormat)return 34041;if(p===RedFormat)return 6403;if(p===RGBFormat){console.warn("THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228");return 6408}if(p===_SRGBAFormat){extension=extensions.get("EXT_sRGB");if(extension!==null){return extension.SRGB_ALPHA_EXT}else{return null}}if(p===RedIntegerFormat)return 36244;if(p===RGFormat)return 33319;if(p===RGIntegerFormat)return 33320;if(p===RGBAIntegerFormat)return 36249;if(p===RGB_S3TC_DXT1_Format||p===RGBA_S3TC_DXT1_Format||p===RGBA_S3TC_DXT3_Format||p===RGBA_S3TC_DXT5_Format){if(encoding===sRGBEncoding){extension=extensions.get("WEBGL_compressed_texture_s3tc_srgb");if(extension!==null){if(p===RGB_S3TC_DXT1_Format)return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT1_Format)return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT3_Format)return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(p===RGBA_S3TC_DXT5_Format)return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{return null}}else{extension=extensions.get("WEBGL_compressed_texture_s3tc");if(extension!==null){if(p===RGB_S3TC_DXT1_Format)return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT1_Format)return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT3_Format)return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(p===RGBA_S3TC_DXT5_Format)return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT}else{return null}}}if(p===RGB_PVRTC_4BPPV1_Format||p===RGB_PVRTC_2BPPV1_Format||p===RGBA_PVRTC_4BPPV1_Format||p===RGBA_PVRTC_2BPPV1_Format){extension=extensions.get("WEBGL_compressed_texture_pvrtc");if(extension!==null){if(p===RGB_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(p===RGB_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(p===RGBA_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(p===RGBA_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else{return null}}if(p===RGB_ETC1_Format){extension=extensions.get("WEBGL_compressed_texture_etc1");if(extension!==null){return extension.COMPRESSED_RGB_ETC1_WEBGL}else{return null}}if(p===RGB_ETC2_Format||p===RGBA_ETC2_EAC_Format){extension=extensions.get("WEBGL_compressed_texture_etc");if(extension!==null){if(p===RGB_ETC2_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ETC2:extension.COMPRESSED_RGB8_ETC2;if(p===RGBA_ETC2_EAC_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:extension.COMPRESSED_RGBA8_ETC2_EAC}else{return null}}if(p===RGBA_ASTC_4x4_Format||p===RGBA_ASTC_5x4_Format||p===RGBA_ASTC_5x5_Format||p===RGBA_ASTC_6x5_Format||p===RGBA_ASTC_6x6_Format||p===RGBA_ASTC_8x5_Format||p===RGBA_ASTC_8x6_Format||p===RGBA_ASTC_8x8_Format||p===RGBA_ASTC_10x5_Format||p===RGBA_ASTC_10x6_Format||p===RGBA_ASTC_10x8_Format||p===RGBA_ASTC_10x10_Format||p===RGBA_ASTC_12x10_Format||p===RGBA_ASTC_12x12_Format){extension=extensions.get("WEBGL_compressed_texture_astc");if(extension!==null){if(p===RGBA_ASTC_4x4_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:extension.COMPRESSED_RGBA_ASTC_4x4_KHR;if(p===RGBA_ASTC_5x4_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:extension.COMPRESSED_RGBA_ASTC_5x4_KHR;if(p===RGBA_ASTC_5x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:extension.COMPRESSED_RGBA_ASTC_5x5_KHR;if(p===RGBA_ASTC_6x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:extension.COMPRESSED_RGBA_ASTC_6x5_KHR;if(p===RGBA_ASTC_6x6_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:extension.COMPRESSED_RGBA_ASTC_6x6_KHR;if(p===RGBA_ASTC_8x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:extension.COMPRESSED_RGBA_ASTC_8x5_KHR;if(p===RGBA_ASTC_8x6_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:extension.COMPRESSED_RGBA_ASTC_8x6_KHR;if(p===RGBA_ASTC_8x8_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:extension.COMPRESSED_RGBA_ASTC_8x8_KHR;if(p===RGBA_ASTC_10x5_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:extension.COMPRESSED_RGBA_ASTC_10x5_KHR;if(p===RGBA_ASTC_10x6_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:extension.COMPRESSED_RGBA_ASTC_10x6_KHR;if(p===RGBA_ASTC_10x8_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:extension.COMPRESSED_RGBA_ASTC_10x8_KHR;if(p===RGBA_ASTC_10x10_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:extension.COMPRESSED_RGBA_ASTC_10x10_KHR;if(p===RGBA_ASTC_12x10_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:extension.COMPRESSED_RGBA_ASTC_12x10_KHR;if(p===RGBA_ASTC_12x12_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:extension.COMPRESSED_RGBA_ASTC_12x12_KHR}else{return null}}if(p===RGBA_BPTC_Format){extension=extensions.get("EXT_texture_compression_bptc");if(extension!==null){if(p===RGBA_BPTC_Format)return encoding===sRGBEncoding?extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:extension.COMPRESSED_RGBA_BPTC_UNORM_EXT}else{return null}}if(p===UnsignedInt248Type){if(isWebGL2)return 34042;extension=extensions.get("WEBGL_depth_texture");if(extension!==null){return extension.UNSIGNED_INT_24_8_WEBGL}else{return null}}return gl[p]!==void 0?gl[p]:null}return{convert}}var ArrayCamera=class extends PerspectiveCamera{constructor(array=[]){super();this.isArrayCamera=true;this.cameras=array}};var Group=class extends Object3D{constructor(){super();this.isGroup=true;this.type="Group"}};var _moveEvent={type:"move"};var WebXRController=class{constructor(){this._targetRay=null;this._grip=null;this._hand=null}getHandSpace(){if(this._hand===null){this._hand=new Group;this._hand.matrixAutoUpdate=false;this._hand.visible=false;this._hand.joints={};this._hand.inputState={pinching:false}}return this._hand}getTargetRaySpace(){if(this._targetRay===null){this._targetRay=new Group;this._targetRay.matrixAutoUpdate=false;this._targetRay.visible=false;this._targetRay.hasLinearVelocity=false;this._targetRay.linearVelocity=new Vector3;this._targetRay.hasAngularVelocity=false;this._targetRay.angularVelocity=new Vector3}return this._targetRay}getGripSpace(){if(this._grip===null){this._grip=new Group;this._grip.matrixAutoUpdate=false;this._grip.visible=false;this._grip.hasLinearVelocity=false;this._grip.linearVelocity=new Vector3;this._grip.hasAngularVelocity=false;this._grip.angularVelocity=new Vector3}return this._grip}dispatchEvent(event){if(this._targetRay!==null){this._targetRay.dispatchEvent(event)}if(this._grip!==null){this._grip.dispatchEvent(event)}if(this._hand!==null){this._hand.dispatchEvent(event)}return this}disconnect(inputSource){this.dispatchEvent({type:"disconnected",data:inputSource});if(this._targetRay!==null){this._targetRay.visible=false}if(this._grip!==null){this._grip.visible=false}if(this._hand!==null){this._hand.visible=false}return this}update(inputSource,frame,referenceSpace){let inputPose=null;let gripPose=null;let handPose=null;const targetRay=this._targetRay;const grip=this._grip;const hand=this._hand;if(inputSource&&frame.session.visibilityState!=="visible-blurred"){if(hand&&inputSource.hand){handPose=true;for(const inputjoint of inputSource.hand.values()){const jointPose=frame.getJointPose(inputjoint,referenceSpace);if(hand.joints[inputjoint.jointName]===void 0){const joint2=new Group;joint2.matrixAutoUpdate=false;joint2.visible=false;hand.joints[inputjoint.jointName]=joint2;hand.add(joint2)}const joint=hand.joints[inputjoint.jointName];if(jointPose!==null){joint.matrix.fromArray(jointPose.transform.matrix);joint.matrix.decompose(joint.position,joint.rotation,joint.scale);joint.jointRadius=jointPose.radius}joint.visible=jointPose!==null}const indexTip=hand.joints["index-finger-tip"];const thumbTip=hand.joints["thumb-tip"];const distance=indexTip.position.distanceTo(thumbTip.position);const distanceToPinch=.02;const threshold=.005;if(hand.inputState.pinching&&distance>distanceToPinch+threshold){hand.inputState.pinching=false;this.dispatchEvent({type:"pinchend",handedness:inputSource.handedness,target:this})}else if(!hand.inputState.pinching&&distance<=distanceToPinch-threshold){hand.inputState.pinching=true;this.dispatchEvent({type:"pinchstart",handedness:inputSource.handedness,target:this})}}else{if(grip!==null&&inputSource.gripSpace){gripPose=frame.getPose(inputSource.gripSpace,referenceSpace);if(gripPose!==null){grip.matrix.fromArray(gripPose.transform.matrix);grip.matrix.decompose(grip.position,grip.rotation,grip.scale);if(gripPose.linearVelocity){grip.hasLinearVelocity=true;grip.linearVelocity.copy(gripPose.linearVelocity)}else{grip.hasLinearVelocity=false}if(gripPose.angularVelocity){grip.hasAngularVelocity=true;grip.angularVelocity.copy(gripPose.angularVelocity)}else{grip.hasAngularVelocity=false}}}}if(targetRay!==null){inputPose=frame.getPose(inputSource.targetRaySpace,referenceSpace);if(inputPose===null&&gripPose!==null){inputPose=gripPose}if(inputPose!==null){targetRay.matrix.fromArray(inputPose.transform.matrix);targetRay.matrix.decompose(targetRay.position,targetRay.rotation,targetRay.scale);if(inputPose.linearVelocity){targetRay.hasLinearVelocity=true;targetRay.linearVelocity.copy(inputPose.linearVelocity)}else{targetRay.hasLinearVelocity=false}if(inputPose.angularVelocity){targetRay.hasAngularVelocity=true;targetRay.angularVelocity.copy(inputPose.angularVelocity)}else{targetRay.hasAngularVelocity=false}this.dispatchEvent(_moveEvent)}}}if(targetRay!==null){targetRay.visible=inputPose!==null}if(grip!==null){grip.visible=gripPose!==null}if(hand!==null){hand.visible=handPose!==null}return this}};var DepthTexture=class extends Texture{constructor(width,height,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,format){format=format!==void 0?format:DepthFormat;if(format!==DepthFormat&&format!==DepthStencilFormat){throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat")}if(type===void 0&&format===DepthFormat)type=UnsignedIntType;if(type===void 0&&format===DepthStencilFormat)type=UnsignedInt248Type;super(null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.isDepthTexture=true;this.image={width,height};this.magFilter=magFilter!==void 0?magFilter:NearestFilter;this.minFilter=minFilter!==void 0?minFilter:NearestFilter;this.flipY=false;this.generateMipmaps=false}};var WebXRManager=class extends EventDispatcher2{constructor(renderer,gl){super();const scope=this;let session=null;let framebufferScaleFactor=1;let referenceSpace=null;let referenceSpaceType="local-floor";let customReferenceSpace=null;let pose=null;let glBinding=null;let glProjLayer=null;let glBaseLayer=null;let xrFrame=null;const attributes=gl.getContextAttributes();let initialRenderTarget=null;let newRenderTarget=null;const controllers=[];const controllerInputSources=[];const cameraL=new PerspectiveCamera;cameraL.layers.enable(1);cameraL.viewport=new Vector4;const cameraR=new PerspectiveCamera;cameraR.layers.enable(2);cameraR.viewport=new Vector4;const cameras=[cameraL,cameraR];const cameraVR=new ArrayCamera;cameraVR.layers.enable(1);cameraVR.layers.enable(2);let _currentDepthNear=null;let _currentDepthFar=null;this.cameraAutoUpdate=true;this.enabled=false;this.isPresenting=false;this.getController=function(index){let controller=controllers[index];if(controller===void 0){controller=new WebXRController;controllers[index]=controller}return controller.getTargetRaySpace()};this.getControllerGrip=function(index){let controller=controllers[index];if(controller===void 0){controller=new WebXRController;controllers[index]=controller}return controller.getGripSpace()};this.getHand=function(index){let controller=controllers[index];if(controller===void 0){controller=new WebXRController;controllers[index]=controller}return controller.getHandSpace()};function onSessionEvent(event){const controllerIndex=controllerInputSources.indexOf(event.inputSource);if(controllerIndex===-1){return}const controller=controllers[controllerIndex];if(controller!==void 0){controller.dispatchEvent({type:event.type,data:event.inputSource})}}function onSessionEnd(){session.removeEventListener("select",onSessionEvent);session.removeEventListener("selectstart",onSessionEvent);session.removeEventListener("selectend",onSessionEvent);session.removeEventListener("squeeze",onSessionEvent);session.removeEventListener("squeezestart",onSessionEvent);session.removeEventListener("squeezeend",onSessionEvent);session.removeEventListener("end",onSessionEnd);session.removeEventListener("inputsourceschange",onInputSourcesChange);for(let i=0;i=0){controllerInputSources[index]=null;controllers[index].dispatchEvent({type:"disconnected",data:inputSource})}}for(let i=0;i=controllerInputSources.length){controllerInputSources.push(inputSource);controllerIndex=i2;break}else if(controllerInputSources[i2]===null){controllerInputSources[i2]=inputSource;controllerIndex=i2;break}}if(controllerIndex===-1)break}const controller=controllers[controllerIndex];if(controller){controller.dispatchEvent({type:"connected",data:inputSource})}}}const cameraLPos=new Vector3;const cameraRPos=new Vector3;function setProjectionFromUnion(camera,cameraL2,cameraR2){cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld);cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld);const ipd=cameraLPos.distanceTo(cameraRPos);const projL=cameraL2.projectionMatrix.elements;const projR=cameraR2.projectionMatrix.elements;const near=projL[14]/(projL[10]-1);const far=projL[14]/(projL[10]+1);const topFov=(projL[9]+1)/projL[5];const bottomFov=(projL[9]-1)/projL[5];const leftFov=(projL[8]-1)/projL[0];const rightFov=(projR[8]+1)/projR[0];const left=near*leftFov;const right=near*rightFov;const zOffset=ipd/(-leftFov+rightFov);const xOffset=zOffset*-leftFov;cameraL2.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);camera.translateX(xOffset);camera.translateZ(zOffset);camera.matrixWorld.compose(camera.position,camera.quaternion,camera.scale);camera.matrixWorldInverse.copy(camera.matrixWorld).invert();const near2=near+zOffset;const far2=far+zOffset;const left2=left-xOffset;const right2=right+(ipd-xOffset);const top2=topFov*far/far2*near2;const bottom2=bottomFov*far/far2*near2;camera.projectionMatrix.makePerspective(left2,right2,top2,bottom2,near2,far2)}function updateCamera(camera,parent){if(parent===null){camera.matrixWorld.copy(camera.matrix)}else{camera.matrixWorld.multiplyMatrices(parent.matrixWorld,camera.matrix)}camera.matrixWorldInverse.copy(camera.matrixWorld).invert()}this.updateCamera=function(camera){if(session===null)return;cameraVR.near=cameraR.near=cameraL.near=camera.near;cameraVR.far=cameraR.far=cameraL.far=camera.far;if(_currentDepthNear!==cameraVR.near||_currentDepthFar!==cameraVR.far){session.updateRenderState({depthNear:cameraVR.near,depthFar:cameraVR.far});_currentDepthNear=cameraVR.near;_currentDepthFar=cameraVR.far}const parent=camera.parent;const cameras2=cameraVR.cameras;updateCamera(cameraVR,parent);for(let i=0;i0){uniforms.alphaTest.value=material.alphaTest}const envMap=properties.get(material).envMap;if(envMap){uniforms.envMap.value=envMap;uniforms.flipEnvMap.value=envMap.isCubeTexture&&envMap.isRenderTargetTexture===false?-1:1;uniforms.reflectivity.value=material.reflectivity;uniforms.ior.value=material.ior;uniforms.refractionRatio.value=material.refractionRatio}if(material.lightMap){uniforms.lightMap.value=material.lightMap;const scaleFactor=renderer.physicallyCorrectLights!==true?Math.PI:1;uniforms.lightMapIntensity.value=material.lightMapIntensity*scaleFactor}if(material.aoMap){uniforms.aoMap.value=material.aoMap;uniforms.aoMapIntensity.value=material.aoMapIntensity}let uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.specularMap){uvScaleMap=material.specularMap}else if(material.displacementMap){uvScaleMap=material.displacementMap}else if(material.normalMap){uvScaleMap=material.normalMap}else if(material.bumpMap){uvScaleMap=material.bumpMap}else if(material.roughnessMap){uvScaleMap=material.roughnessMap}else if(material.metalnessMap){uvScaleMap=material.metalnessMap}else if(material.alphaMap){uvScaleMap=material.alphaMap}else if(material.emissiveMap){uvScaleMap=material.emissiveMap}else if(material.clearcoatMap){uvScaleMap=material.clearcoatMap}else if(material.clearcoatNormalMap){uvScaleMap=material.clearcoatNormalMap}else if(material.clearcoatRoughnessMap){uvScaleMap=material.clearcoatRoughnessMap}else if(material.iridescenceMap){uvScaleMap=material.iridescenceMap}else if(material.iridescenceThicknessMap){uvScaleMap=material.iridescenceThicknessMap}else if(material.specularIntensityMap){uvScaleMap=material.specularIntensityMap}else if(material.specularColorMap){uvScaleMap=material.specularColorMap}else if(material.transmissionMap){uvScaleMap=material.transmissionMap}else if(material.thicknessMap){uvScaleMap=material.thicknessMap}else if(material.sheenColorMap){uvScaleMap=material.sheenColorMap}else if(material.sheenRoughnessMap){uvScaleMap=material.sheenRoughnessMap}if(uvScaleMap!==void 0){if(uvScaleMap.isWebGLRenderTarget){uvScaleMap=uvScaleMap.texture}if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix()}uniforms.uvTransform.value.copy(uvScaleMap.matrix)}let uv2ScaleMap;if(material.aoMap){uv2ScaleMap=material.aoMap}else if(material.lightMap){uv2ScaleMap=material.lightMap}if(uv2ScaleMap!==void 0){if(uv2ScaleMap.isWebGLRenderTarget){uv2ScaleMap=uv2ScaleMap.texture}if(uv2ScaleMap.matrixAutoUpdate===true){uv2ScaleMap.updateMatrix()}uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix)}}function refreshUniformsLine(uniforms,material){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity}function refreshUniformsDash(uniforms,material){uniforms.dashSize.value=material.dashSize;uniforms.totalSize.value=material.dashSize+material.gapSize;uniforms.scale.value=material.scale}function refreshUniformsPoints(uniforms,material,pixelRatio,height){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;uniforms.size.value=material.size*pixelRatio;uniforms.scale.value=height*.5;if(material.map){uniforms.map.value=material.map}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap}if(material.alphaTest>0){uniforms.alphaTest.value=material.alphaTest}let uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.alphaMap){uvScaleMap=material.alphaMap}if(uvScaleMap!==void 0){if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix()}uniforms.uvTransform.value.copy(uvScaleMap.matrix)}}function refreshUniformsSprites(uniforms,material){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;uniforms.rotation.value=material.rotation;if(material.map){uniforms.map.value=material.map}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap}if(material.alphaTest>0){uniforms.alphaTest.value=material.alphaTest}let uvScaleMap;if(material.map){uvScaleMap=material.map}else if(material.alphaMap){uvScaleMap=material.alphaMap}if(uvScaleMap!==void 0){if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix()}uniforms.uvTransform.value.copy(uvScaleMap.matrix)}}function refreshUniformsPhong(uniforms,material){uniforms.specular.value.copy(material.specular);uniforms.shininess.value=Math.max(material.shininess,1e-4)}function refreshUniformsToon(uniforms,material){if(material.gradientMap){uniforms.gradientMap.value=material.gradientMap}}function refreshUniformsStandard(uniforms,material){uniforms.roughness.value=material.roughness;uniforms.metalness.value=material.metalness;if(material.roughnessMap){uniforms.roughnessMap.value=material.roughnessMap}if(material.metalnessMap){uniforms.metalnessMap.value=material.metalnessMap}const envMap=properties.get(material).envMap;if(envMap){uniforms.envMapIntensity.value=material.envMapIntensity}}function refreshUniformsPhysical(uniforms,material,transmissionRenderTarget){uniforms.ior.value=material.ior;if(material.sheen>0){uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);uniforms.sheenRoughness.value=material.sheenRoughness;if(material.sheenColorMap){uniforms.sheenColorMap.value=material.sheenColorMap}if(material.sheenRoughnessMap){uniforms.sheenRoughnessMap.value=material.sheenRoughnessMap}}if(material.clearcoat>0){uniforms.clearcoat.value=material.clearcoat;uniforms.clearcoatRoughness.value=material.clearcoatRoughness;if(material.clearcoatMap){uniforms.clearcoatMap.value=material.clearcoatMap}if(material.clearcoatRoughnessMap){uniforms.clearcoatRoughnessMap.value=material.clearcoatRoughnessMap}if(material.clearcoatNormalMap){uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);uniforms.clearcoatNormalMap.value=material.clearcoatNormalMap;if(material.side===BackSide){uniforms.clearcoatNormalScale.value.negate()}}}if(material.iridescence>0){uniforms.iridescence.value=material.iridescence;uniforms.iridescenceIOR.value=material.iridescenceIOR;uniforms.iridescenceThicknessMinimum.value=material.iridescenceThicknessRange[0];uniforms.iridescenceThicknessMaximum.value=material.iridescenceThicknessRange[1];if(material.iridescenceMap){uniforms.iridescenceMap.value=material.iridescenceMap}if(material.iridescenceThicknessMap){uniforms.iridescenceThicknessMap.value=material.iridescenceThicknessMap}}if(material.transmission>0){uniforms.transmission.value=material.transmission;uniforms.transmissionSamplerMap.value=transmissionRenderTarget.texture;uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width,transmissionRenderTarget.height);if(material.transmissionMap){uniforms.transmissionMap.value=material.transmissionMap}uniforms.thickness.value=material.thickness;if(material.thicknessMap){uniforms.thicknessMap.value=material.thicknessMap}uniforms.attenuationDistance.value=material.attenuationDistance;uniforms.attenuationColor.value.copy(material.attenuationColor)}uniforms.specularIntensity.value=material.specularIntensity;uniforms.specularColor.value.copy(material.specularColor);if(material.specularIntensityMap){uniforms.specularIntensityMap.value=material.specularIntensityMap}if(material.specularColorMap){uniforms.specularColorMap.value=material.specularColorMap}}function refreshUniformsMatcap(uniforms,material){if(material.matcap){uniforms.matcap.value=material.matcap}}function refreshUniformsDistance(uniforms,material){uniforms.referencePosition.value.copy(material.referencePosition);uniforms.nearDistance.value=material.nearDistance;uniforms.farDistance.value=material.farDistance}return{refreshFogUniforms,refreshMaterialUniforms}}function WebGLUniformsGroups(gl,info2,capabilities,state){let buffers={};let updateList={};let allocatedBindingPoints=[];const maxBindingPoints=capabilities.isWebGL2?gl.getParameter(35375):0;function bind(uniformsGroup,program){const webglProgram=program.program;state.uniformBlockBinding(uniformsGroup,webglProgram)}function update(uniformsGroup,program){let buffer=buffers[uniformsGroup.id];if(buffer===void 0){prepareUniformsGroup(uniformsGroup);buffer=createBuffer(uniformsGroup);buffers[uniformsGroup.id]=buffer;uniformsGroup.addEventListener("dispose",onUniformsGroupsDispose)}const webglProgram=program.program;state.updateUBOMapping(uniformsGroup,webglProgram);const frame=info2.render.frame;if(updateList[uniformsGroup.id]!==frame){updateBufferData(uniformsGroup);updateList[uniformsGroup.id]=frame}}function createBuffer(uniformsGroup){const bindingPointIndex=allocateBindingPointIndex();uniformsGroup.__bindingPointIndex=bindingPointIndex;const buffer=gl.createBuffer();const size=uniformsGroup.__size;const usage=uniformsGroup.usage;gl.bindBuffer(35345,buffer);gl.bufferData(35345,size,usage);gl.bindBuffer(35345,null);gl.bindBufferBase(35345,bindingPointIndex,buffer);return buffer}function allocateBindingPointIndex(){for(let i=0;i0){chunkOffset=offset%chunkSize;const remainingSizeInChunk=chunkSize-chunkOffset;if(chunkOffset!==0&&remainingSizeInChunk-info3.boundary<0){offset+=chunkSize-chunkOffset;uniform.__offset=offset}}offset+=info3.storage}chunkOffset=offset%chunkSize;if(chunkOffset>0)offset+=chunkSize-chunkOffset;uniformsGroup.__size=offset;uniformsGroup.__cache={};return this}function getUniformSize(uniform){const value=uniform.value;const info3={boundary:0,storage:0};if(typeof value==="number"){info3.boundary=4;info3.storage=4}else if(value.isVector2){info3.boundary=8;info3.storage=8}else if(value.isVector3||value.isColor){info3.boundary=16;info3.storage=12}else if(value.isVector4){info3.boundary=16;info3.storage=16}else if(value.isMatrix3){info3.boundary=48;info3.storage=48}else if(value.isMatrix4){info3.boundary=64;info3.storage=64}else if(value.isTexture){console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.")}else{console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",value)}return info3}function onUniformsGroupsDispose(event){const uniformsGroup=event.target;uniformsGroup.removeEventListener("dispose",onUniformsGroupsDispose);const index=allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);allocatedBindingPoints.splice(index,1);gl.deleteBuffer(buffers[uniformsGroup.id]);delete buffers[uniformsGroup.id];delete updateList[uniformsGroup.id]}function dispose(){for(const id2 in buffers){gl.deleteBuffer(buffers[id2])}allocatedBindingPoints=[];buffers={};updateList={}}return{bind,update,dispose}}function createCanvasElement(){const canvas=createElementNS("canvas");canvas.style.display="block";return canvas}function WebGLRenderer(parameters={}){this.isWebGLRenderer=true;const _canvas2=parameters.canvas!==void 0?parameters.canvas:createCanvasElement(),_context2=parameters.context!==void 0?parameters.context:null,_depth=parameters.depth!==void 0?parameters.depth:true,_stencil=parameters.stencil!==void 0?parameters.stencil:true,_antialias=parameters.antialias!==void 0?parameters.antialias:false,_premultipliedAlpha=parameters.premultipliedAlpha!==void 0?parameters.premultipliedAlpha:true,_preserveDrawingBuffer=parameters.preserveDrawingBuffer!==void 0?parameters.preserveDrawingBuffer:false,_powerPreference=parameters.powerPreference!==void 0?parameters.powerPreference:"default",_failIfMajorPerformanceCaveat=parameters.failIfMajorPerformanceCaveat!==void 0?parameters.failIfMajorPerformanceCaveat:false;let _alpha;if(_context2!==null){_alpha=_context2.getContextAttributes().alpha}else{_alpha=parameters.alpha!==void 0?parameters.alpha:false}let currentRenderList=null;let currentRenderState=null;const renderListStack=[];const renderStateStack=[];this.domElement=_canvas2;this.debug={checkShaderErrors:true};this.autoClear=true;this.autoClearColor=true;this.autoClearDepth=true;this.autoClearStencil=true;this.sortObjects=true;this.clippingPlanes=[];this.localClippingEnabled=false;this.outputEncoding=LinearEncoding;this.physicallyCorrectLights=false;this.toneMapping=NoToneMapping;this.toneMappingExposure=1;Object.defineProperties(this,{gammaFactor:{get:function(){console.warn("THREE.WebGLRenderer: .gammaFactor has been removed.");return 2},set:function(){console.warn("THREE.WebGLRenderer: .gammaFactor has been removed.")}}});const _this=this;let _isContextLost=false;let _currentActiveCubeFace=0;let _currentActiveMipmapLevel=0;let _currentRenderTarget=null;let _currentMaterialId=-1;let _currentCamera=null;const _currentViewport=new Vector4;const _currentScissor=new Vector4;let _currentScissorTest=null;let _width=_canvas2.width;let _height=_canvas2.height;let _pixelRatio=1;let _opaqueSort=null;let _transparentSort=null;const _viewport=new Vector4(0,0,_width,_height);const _scissor=new Vector4(0,0,_width,_height);let _scissorTest=false;const _frustum=new Frustum;let _clippingEnabled=false;let _localClippingEnabled=false;let _transmissionRenderTarget=null;const _projScreenMatrix2=new Matrix4;const _vector22=new Vector2;const _vector3=new Vector3;const _emptyScene={background:null,fog:null,environment:null,overrideMaterial:null,isScene:true};function getTargetPixelRatio(){return _currentRenderTarget===null?_pixelRatio:1}let _gl=_context2;function getContext(contextNames,contextAttributes){for(let i=0;i0){currentRenderState=renderStateStack[renderStateStack.length-1]}else{currentRenderState=null}renderListStack.pop();if(renderListStack.length>0){currentRenderList=renderListStack[renderListStack.length-1]}else{currentRenderList=null}};function projectObject(object,camera,groupOrder,sortObjects){if(object.visible===false)return;const visible=object.layers.test(camera.layers);if(visible){if(object.isGroup){groupOrder=object.renderOrder}else if(object.isLOD){if(object.autoUpdate===true)object.update(camera)}else if(object.isLight){currentRenderState.pushLight(object);if(object.castShadow){currentRenderState.pushShadow(object)}}else if(object.isSprite){if(!object.frustumCulled||_frustum.intersectsSprite(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2)}const geometry=objects2.update(object);const material=object.material;if(material.visible){currentRenderList.push(object,geometry,material,groupOrder,_vector3.z,null)}}}else if(object.isMesh||object.isLine||object.isPoints){if(object.isSkinnedMesh){if(object.skeleton.frame!==info2.render.frame){object.skeleton.update();object.skeleton.frame=info2.render.frame}}if(!object.frustumCulled||_frustum.intersectsObject(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2)}const geometry=objects2.update(object);const material=object.material;if(Array.isArray(material)){const groups=geometry.groups;for(let i=0,l=groups.length;i0)renderTransmissionPass(opaqueObjects,scene,camera);if(viewport)state.viewport(_currentViewport.copy(viewport));if(opaqueObjects.length>0)renderObjects(opaqueObjects,scene,camera);if(transmissiveObjects.length>0)renderObjects(transmissiveObjects,scene,camera);if(transparentObjects.length>0)renderObjects(transparentObjects,scene,camera);state.buffers.depth.setTest(true);state.buffers.depth.setMask(true);state.buffers.color.setMask(true);state.setPolygonOffset(false)}function renderTransmissionPass(opaqueObjects,scene,camera){const isWebGL2=capabilities.isWebGL2;if(_transmissionRenderTarget===null){_transmissionRenderTarget=new WebGLRenderTarget(1,1,{generateMipmaps:true,type:extensions.has("EXT_color_buffer_half_float")?HalfFloatType:UnsignedByteType,minFilter:LinearMipmapLinearFilter,samples:isWebGL2&&_antialias===true?4:0})}_this.getDrawingBufferSize(_vector22);if(isWebGL2){_transmissionRenderTarget.setSize(_vector22.x,_vector22.y)}else{_transmissionRenderTarget.setSize(floorPowerOfTwo(_vector22.x),floorPowerOfTwo(_vector22.y))}const currentRenderTarget=_this.getRenderTarget();_this.setRenderTarget(_transmissionRenderTarget);_this.clear();const currentToneMapping=_this.toneMapping;_this.toneMapping=NoToneMapping;renderObjects(opaqueObjects,scene,camera);_this.toneMapping=currentToneMapping;textures.updateMultisampleRenderTarget(_transmissionRenderTarget);textures.updateRenderTargetMipmap(_transmissionRenderTarget);_this.setRenderTarget(currentRenderTarget)}function renderObjects(renderList,scene,camera){const overrideMaterial=scene.isScene===true?scene.overrideMaterial:null;for(let i=0,l=renderList.length;i0&&textures.useMultisampledRTT(renderTarget)===false){framebuffer=properties.get(renderTarget).__webglMultisampledFramebuffer}else{framebuffer=__webglFramebuffer}_currentViewport.copy(renderTarget.viewport);_currentScissor.copy(renderTarget.scissor);_currentScissorTest=renderTarget.scissorTest}else{_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();_currentScissorTest=_scissorTest}const framebufferBound=state.bindFramebuffer(36160,framebuffer);if(framebufferBound&&capabilities.drawBuffers&&useDefaultFramebuffer){state.drawBuffers(renderTarget,framebuffer)}state.viewport(_currentViewport);state.scissor(_currentScissor);state.setScissorTest(_currentScissorTest);if(isCube){const textureProperties=properties.get(renderTarget.texture);_gl.framebufferTexture2D(36160,36064,34069+activeCubeFace,textureProperties.__webglTexture,activeMipmapLevel)}else if(isRenderTarget3D){const textureProperties=properties.get(renderTarget.texture);const layer=activeCubeFace||0;_gl.framebufferTextureLayer(36160,36064,textureProperties.__webglTexture,activeMipmapLevel||0,layer)}_currentMaterialId=-1};this.readRenderTargetPixels=function(renderTarget,x2,y2,width,height,buffer,activeCubeFaceIndex){if(!(renderTarget&&renderTarget.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==void 0){framebuffer=framebuffer[activeCubeFaceIndex]}if(framebuffer){state.bindFramebuffer(36160,framebuffer);try{const texture=renderTarget.texture;const textureFormat=texture.format;const textureType=texture.type;if(textureFormat!==RGBAFormat&&utils.convert(textureFormat)!==_gl.getParameter(35739)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const halfFloatSupportedByExt=textureType===HalfFloatType&&(extensions.has("EXT_color_buffer_half_float")||capabilities.isWebGL2&&extensions.has("EXT_color_buffer_float"));if(textureType!==UnsignedByteType&&utils.convert(textureType)!==_gl.getParameter(35738)&&!(textureType===FloatType&&(capabilities.isWebGL2||extensions.has("OES_texture_float")||extensions.has("WEBGL_color_buffer_float")))&&!halfFloatSupportedByExt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(x2>=0&&x2<=renderTarget.width-width&&(y2>=0&&y2<=renderTarget.height-height)){_gl.readPixels(x2,y2,width,height,utils.convert(textureFormat),utils.convert(textureType),buffer)}}finally{const framebuffer2=_currentRenderTarget!==null?properties.get(_currentRenderTarget).__webglFramebuffer:null;state.bindFramebuffer(36160,framebuffer2)}}};this.copyFramebufferToTexture=function(position,texture,level=0){const levelScale=Math.pow(2,-level);const width=Math.floor(texture.image.width*levelScale);const height=Math.floor(texture.image.height*levelScale);textures.setTexture2D(texture,0);_gl.copyTexSubImage2D(3553,level,0,0,position.x,position.y,width,height);state.unbindTexture()};this.copyTextureToTexture=function(position,srcTexture,dstTexture,level=0){const width=srcTexture.image.width;const height=srcTexture.image.height;const glFormat=utils.convert(dstTexture.format);const glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);_gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);if(srcTexture.isDataTexture){_gl.texSubImage2D(3553,level,position.x,position.y,width,height,glFormat,glType,srcTexture.image.data)}else{if(srcTexture.isCompressedTexture){_gl.compressedTexSubImage2D(3553,level,position.x,position.y,srcTexture.mipmaps[0].width,srcTexture.mipmaps[0].height,glFormat,srcTexture.mipmaps[0].data)}else{_gl.texSubImage2D(3553,level,position.x,position.y,glFormat,glType,srcTexture.image)}}if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(3553);state.unbindTexture()};this.copyTextureToTexture3D=function(sourceBox,position,srcTexture,dstTexture,level=0){if(_this.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const width=sourceBox.max.x-sourceBox.min.x+1;const height=sourceBox.max.y-sourceBox.min.y+1;const depth=sourceBox.max.z-sourceBox.min.z+1;const glFormat=utils.convert(dstTexture.format);const glType=utils.convert(dstTexture.type);let glTarget;if(dstTexture.isData3DTexture){textures.setTexture3D(dstTexture,0);glTarget=32879}else if(dstTexture.isDataArrayTexture){textures.setTexture2DArray(dstTexture,0);glTarget=35866}else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}_gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);const unpackRowLen=_gl.getParameter(3314);const unpackImageHeight=_gl.getParameter(32878);const unpackSkipPixels=_gl.getParameter(3316);const unpackSkipRows=_gl.getParameter(3315);const unpackSkipImages=_gl.getParameter(32877);const image=srcTexture.isCompressedTexture?srcTexture.mipmaps[0]:srcTexture.image;_gl.pixelStorei(3314,image.width);_gl.pixelStorei(32878,image.height);_gl.pixelStorei(3316,sourceBox.min.x);_gl.pixelStorei(3315,sourceBox.min.y);_gl.pixelStorei(32877,sourceBox.min.z);if(srcTexture.isDataTexture||srcTexture.isData3DTexture){_gl.texSubImage3D(glTarget,level,position.x,position.y,position.z,width,height,depth,glFormat,glType,image.data)}else{if(srcTexture.isCompressedTexture){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.");_gl.compressedTexSubImage3D(glTarget,level,position.x,position.y,position.z,width,height,depth,glFormat,image.data)}else{_gl.texSubImage3D(glTarget,level,position.x,position.y,position.z,width,height,depth,glFormat,glType,image)}}_gl.pixelStorei(3314,unpackRowLen);_gl.pixelStorei(32878,unpackImageHeight);_gl.pixelStorei(3316,unpackSkipPixels);_gl.pixelStorei(3315,unpackSkipRows);_gl.pixelStorei(32877,unpackSkipImages);if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(glTarget);state.unbindTexture()};this.initTexture=function(texture){if(texture.isCubeTexture){textures.setTextureCube(texture,0)}else if(texture.isData3DTexture){textures.setTexture3D(texture,0)}else if(texture.isDataArrayTexture){textures.setTexture2DArray(texture,0)}else{textures.setTexture2D(texture,0)}state.unbindTexture()};this.resetState=function(){_currentActiveCubeFace=0;_currentActiveMipmapLevel=0;_currentRenderTarget=null;state.reset();bindingStates.reset()};if(typeof __THREE_DEVTOOLS__!=="undefined"){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}var WebGL1Renderer=class extends WebGLRenderer{};WebGL1Renderer.prototype.isWebGL1Renderer=true;var FogExp2=class{constructor(color,density=25e-5){this.isFogExp2=true;this.name="";this.color=new Color(color);this.density=density}clone(){return new FogExp2(this.color,this.density)}toJSON(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}}};var Fog=class{constructor(color,near=1,far=1e3){this.isFog=true;this.name="";this.color=new Color(color);this.near=near;this.far=far}clone(){return new Fog(this.color,this.near,this.far)}toJSON(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}}};var Scene=class extends Object3D{constructor(){super();this.isScene=true;this.type="Scene";this.background=null;this.environment=null;this.fog=null;this.overrideMaterial=null;this.autoUpdate=true;if(typeof __THREE_DEVTOOLS__!=="undefined"){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}copy(source,recursive){super.copy(source,recursive);if(source.background!==null)this.background=source.background.clone();if(source.environment!==null)this.environment=source.environment.clone();if(source.fog!==null)this.fog=source.fog.clone();if(source.overrideMaterial!==null)this.overrideMaterial=source.overrideMaterial.clone();this.autoUpdate=source.autoUpdate;this.matrixAutoUpdate=source.matrixAutoUpdate;return this}toJSON(meta){const data=super.toJSON(meta);if(this.fog!==null)data.object.fog=this.fog.toJSON();return data}};var InterleavedBuffer=class{constructor(array,stride){this.isInterleavedBuffer=true;this.array=array;this.stride=stride;this.count=array!==void 0?array.length/stride:0;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;this.uuid=generateUUID()}onUploadCallback(){}set needsUpdate(value){if(value===true)this.version++}setUsage(value){this.usage=value;return this}copy(source){this.array=new source.array.constructor(source.array);this.count=source.count;this.stride=source.stride;this.usage=source.usage;return this}copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(let i=0,l=this.stride;iraycaster.far)return;intersects2.push({distance,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA,_vB,_vC,_uvA,_uvB,_uvC,new Vector2),face:null,object:this})}copy(source,recursive){super.copy(source,recursive);if(source.center!==void 0)this.center.copy(source.center);this.material=source.material;return this}};function transformVertex(vertexPosition,mvPosition,center,scale,sin,cos){_alignedPosition.subVectors(vertexPosition,center).addScalar(.5).multiply(scale);if(sin!==void 0){_rotatedPosition.x=cos*_alignedPosition.x-sin*_alignedPosition.y;_rotatedPosition.y=sin*_alignedPosition.x+cos*_alignedPosition.y}else{_rotatedPosition.copy(_alignedPosition)}vertexPosition.copy(mvPosition);vertexPosition.x+=_rotatedPosition.x;vertexPosition.y+=_rotatedPosition.y;vertexPosition.applyMatrix4(_viewWorldMatrix)}var _v1$2=new Vector3;var _v2$1=new Vector3;var LOD=class extends Object3D{constructor(){super();this._currentLevel=0;this.type="LOD";Object.defineProperties(this,{levels:{enumerable:true,value:[]},isLOD:{value:true}});this.autoUpdate=true}copy(source){super.copy(source,false);const levels=source.levels;for(let i=0,l=levels.length;i0){let i,l;for(i=1,l=levels.length;i0){_v1$2.setFromMatrixPosition(this.matrixWorld);const distance=raycaster.ray.origin.distanceTo(_v1$2);this.getObjectForDistance(distance).raycast(raycaster,intersects2)}}update(camera){const levels=this.levels;if(levels.length>1){_v1$2.setFromMatrixPosition(camera.matrixWorld);_v2$1.setFromMatrixPosition(this.matrixWorld);const distance=_v1$2.distanceTo(_v2$1)/camera.zoom;levels[0].object.visible=true;let i,l;for(i=1,l=levels.length;i=levels[i].distance){levels[i-1].object.visible=false;levels[i].object.visible=true}else{break}}this._currentLevel=i-1;for(;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);const distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.far)continue;intersects2.push({distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}else{const start=Math.max(0,drawRange.start);const end=Math.min(positionAttribute.count,drawRange.start+drawRange.count);for(let i=start,l=end-1;ilocalThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);const distance=raycaster.ray.origin.distanceTo(interRay);if(distanceraycaster.far)continue;intersects2.push({distance,point:interSegment.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const geometry=this.geometry;const morphAttributes=geometry.morphAttributes;const keys=Object.keys(morphAttributes);if(keys.length>0){const morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==void 0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(let m=0,ml=morphAttribute.length;m0){const morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==void 0){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(let m=0,ml=morphAttribute.length;mraycaster.far)return;intersects2.push({distance,distanceToRay:Math.sqrt(rayPointDistanceSq),point:intersectPoint,index,face:null,object})}}var VideoTexture=class extends Texture{constructor(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){super(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.isVideoTexture=true;this.minFilter=minFilter!==void 0?minFilter:LinearFilter;this.magFilter=magFilter!==void 0?magFilter:LinearFilter;this.generateMipmaps=false;const scope=this;function updateVideo(){scope.needsUpdate=true;video.requestVideoFrameCallback(updateVideo)}if("requestVideoFrameCallback"in video){video.requestVideoFrameCallback(updateVideo)}}clone(){return new this.constructor(this.image).copy(this)}update(){const video=this.image;const hasVideoFrameCallback="requestVideoFrameCallback"in video;if(hasVideoFrameCallback===false&&video.readyState>=video.HAVE_CURRENT_DATA){this.needsUpdate=true}}};var FramebufferTexture=class extends Texture{constructor(width,height,format){super({width,height});this.isFramebufferTexture=true;this.format=format;this.magFilter=NearestFilter;this.minFilter=NearestFilter;this.generateMipmaps=false;this.needsUpdate=true}};var CompressedTexture=class extends Texture{constructor(mipmaps,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){super(null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.isCompressedTexture=true;this.image={width,height};this.mipmaps=mipmaps;this.flipY=false;this.generateMipmaps=false}};var CanvasTexture=class extends Texture{constructor(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){super(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.isCanvasTexture=true;this.needsUpdate=true}};var Curve=class{constructor(){this.type="Curve";this.arcLengthDivisions=200}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.");return null}getPointAt(u,optionalTarget){const t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget)}getPoints(divisions=5){const points=[];for(let d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions))}return points}getSpacedPoints(divisions=5){const points=[];for(let d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions))}return points}getLength(){const lengths=this.getLengths();return lengths[lengths.length-1]}getLengths(divisions=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths}this.needsUpdate=false;const cache=[];let current,last=this.getPoint(0);let sum=0;cache.push(0);for(let p=1;p<=divisions;p++){current=this.getPoint(p/divisions);sum+=current.distanceTo(last);cache.push(sum);last=current}this.cacheArcLengths=cache;return cache}updateArcLengths(){this.needsUpdate=true;this.getLengths()}getUtoTmapping(u,distance){const arcLengths=this.getLengths();let i=0;const il=arcLengths.length;let targetArcLength;if(distance){targetArcLength=distance}else{targetArcLength=u*arcLengths[il-1]}let low=0,high=il-1,comparison;while(low<=high){i=Math.floor(low+(high-low)/2);comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1}else if(comparison>0){high=i-1}else{high=i;break}}i=high;if(arcLengths[i]===targetArcLength){return i/(il-1)}const lengthBefore=arcLengths[i];const lengthAfter=arcLengths[i+1];const segmentLength=lengthAfter-lengthBefore;const segmentFraction=(targetArcLength-lengthBefore)/segmentLength;const t=(i+segmentFraction)/(il-1);return t}getTangent(t,optionalTarget){const delta=1e-4;let t1=t-delta;let t2=t+delta;if(t1<0)t1=0;if(t2>1)t2=1;const pt1=this.getPoint(t1);const pt2=this.getPoint(t2);const tangent=optionalTarget||(pt1.isVector2?new Vector2:new Vector3);tangent.copy(pt2).sub(pt1).normalize();return tangent}getTangentAt(u,optionalTarget){const t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget)}computeFrenetFrames(segments,closed){const normal=new Vector3;const tangents=[];const normals=[];const binormals=[];const vec=new Vector3;const mat=new Matrix4;for(let i=0;i<=segments;i++){const u=i/segments;tangents[i]=this.getTangentAt(u,new Vector3)}normals[0]=new Vector3;binormals[0]=new Vector3;let min=Number.MAX_VALUE;const tx=Math.abs(tangents[0].x);const ty=Math.abs(tangents[0].y);const tz=Math.abs(tangents[0].z);if(tx<=min){min=tx;normal.set(1,0,0)}if(ty<=min){min=ty;normal.set(0,1,0)}if(tz<=min){normal.set(0,0,1)}vec.crossVectors(tangents[0],normal).normalize();normals[0].crossVectors(tangents[0],vec);binormals[0].crossVectors(tangents[0],normals[0]);for(let i=1;i<=segments;i++){normals[i]=normals[i-1].clone();binormals[i]=binormals[i-1].clone();vec.crossVectors(tangents[i-1],tangents[i]);if(vec.length()>Number.EPSILON){vec.normalize();const theta=Math.acos(clamp(tangents[i-1].dot(tangents[i]),-1,1));normals[i].applyMatrix4(mat.makeRotationAxis(vec,theta))}binormals[i].crossVectors(tangents[i],normals[i])}if(closed===true){let theta=Math.acos(clamp(normals[0].dot(normals[segments]),-1,1));theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){theta=-theta}for(let i=1;i<=segments;i++){normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i],theta*i));binormals[i].crossVectors(tangents[i],normals[i])}}return{tangents,normals,binormals}}clone(){return new this.constructor().copy(this)}copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this}toJSON(){const data={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data}fromJSON(json){this.arcLengthDivisions=json.arcLengthDivisions;return this}};var EllipseCurve=class extends Curve{constructor(aX=0,aY=0,xRadius=1,yRadius=1,aStartAngle=0,aEndAngle=Math.PI*2,aClockwise=false,aRotation=0){super();this.isEllipseCurve=true;this.type="EllipseCurve";this.aX=aX;this.aY=aY;this.xRadius=xRadius;this.yRadius=yRadius;this.aStartAngle=aStartAngle;this.aEndAngle=aEndAngle;this.aClockwise=aClockwise;this.aRotation=aRotation}getPoint(t,optionalTarget){const point=optionalTarget||new Vector2;const twoPi=Math.PI*2;let deltaAngle=this.aEndAngle-this.aStartAngle;const samePoints=Math.abs(deltaAngle)twoPi)deltaAngle-=twoPi;if(deltaAngle0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1}let p0,p3;if(this.closed||intPoint>0){p0=points[(intPoint-1)%l]}else{tmp.subVectors(points[0],points[1]).add(points[0]);p0=tmp}const p1=points[intPoint%l];const p2=points[(intPoint+1)%l];if(this.closed||intPoint+2points.length-2?points.length-1:intPoint+1];const p3=points[intPoint>points.length-3?points.length-1:intPoint+2];point.set(CatmullRom(weight,p0.x,p1.x,p2.x,p3.x),CatmullRom(weight,p0.y,p1.y,p2.y,p3.y));return point}copy(source){super.copy(source);this.points=[];for(let i=0,l=source.points.length;i=d){const diff=curveLengths[i]-d;const curve=this.curves[i];const segmentLength=curve.getLength();const u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u,optionalTarget)}i++}return null}getLength(){const lens=this.getCurveLengths();return lens[lens.length-1]}updateArcLengths(){this.needsUpdate=true;this.cacheLengths=null;this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length){return this.cacheLengths}const lengths=[];let sums=0;for(let i=0,l=this.curves.length;i1&&!points[points.length-1].equals(points[0])){points.push(points[0])}return points}copy(source){super.copy(source);this.curves=[];for(let i=0,l=source.curves.length;i0){const firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y)}}this.curves.push(curve);const lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint);return this}copy(source){super.copy(source);this.currentPoint.copy(source.currentPoint);return this}toJSON(){const data=super.toJSON();data.currentPoint=this.currentPoint.toArray();return data}fromJSON(json){super.fromJSON(json);this.currentPoint.fromArray(json.currentPoint);return this}};var LatheGeometry=class extends BufferGeometry{constructor(points=[new Vector2(0,-.5),new Vector2(.5,0),new Vector2(0,.5)],segments=12,phiStart=0,phiLength=Math.PI*2){super();this.type="LatheGeometry";this.parameters={points,segments,phiStart,phiLength};segments=Math.floor(segments);phiLength=clamp(phiLength,0,Math.PI*2);const indices=[];const vertices=[];const uvs=[];const initNormals=[];const normals=[];const inverseSegments=1/segments;const vertex2=new Vector3;const uv=new Vector2;const normal=new Vector3;const curNormal=new Vector3;const prevNormal=new Vector3;let dx=0;let dy=0;for(let j=0;j<=points.length-1;j++){switch(j){case 0:dx=points[j+1].x-points[j].x;dy=points[j+1].y-points[j].y;normal.x=dy*1;normal.y=-dx;normal.z=dy*0;prevNormal.copy(normal);normal.normalize();initNormals.push(normal.x,normal.y,normal.z);break;case points.length-1:initNormals.push(prevNormal.x,prevNormal.y,prevNormal.z);break;default:dx=points[j+1].x-points[j].x;dy=points[j+1].y-points[j].y;normal.x=dy*1;normal.y=-dx;normal.z=dy*0;curNormal.copy(normal);normal.x+=prevNormal.x;normal.y+=prevNormal.y;normal.z+=prevNormal.z;normal.normalize();initNormals.push(normal.x,normal.y,normal.z);prevNormal.copy(curNormal)}}for(let i=0;i<=segments;i++){const phi=phiStart+i*inverseSegments*phiLength;const sin=Math.sin(phi);const cos=Math.cos(phi);for(let j=0;j<=points.length-1;j++){vertex2.x=points[j].x*sin;vertex2.y=points[j].y;vertex2.z=points[j].x*cos;vertices.push(vertex2.x,vertex2.y,vertex2.z);uv.x=i/segments;uv.y=j/(points.length-1);uvs.push(uv.x,uv.y);const x2=initNormals[3*j+0]*sin;const y2=initNormals[3*j+1];const z=initNormals[3*j+0]*cos;normals.push(x2,y2,z)}}for(let i=0;i0)generateCap(true);if(radiusBottom>0)generateCap(false)}this.setIndex(indices);this.setAttribute("position",new Float32BufferAttribute(vertices,3));this.setAttribute("normal",new Float32BufferAttribute(normals,3));this.setAttribute("uv",new Float32BufferAttribute(uvs,2));function generateTorso(){const normal=new Vector3;const vertex2=new Vector3;let groupCount=0;const slope=(radiusBottom-radiusTop)/height;for(let y2=0;y2<=heightSegments;y2++){const indexRow=[];const v=y2/heightSegments;const radius=v*(radiusBottom-radiusTop)+radiusTop;for(let x2=0;x2<=radialSegments;x2++){const u=x2/radialSegments;const theta=u*thetaLength+thetaStart;const sinTheta=Math.sin(theta);const cosTheta=Math.cos(theta);vertex2.x=radius*sinTheta;vertex2.y=-v*height+halfHeight;vertex2.z=radius*cosTheta;vertices.push(vertex2.x,vertex2.y,vertex2.z);normal.set(sinTheta,slope,cosTheta).normalize();normals.push(normal.x,normal.y,normal.z);uvs.push(u,1-v);indexRow.push(index++)}indexArray.push(indexRow)}for(let x2=0;x2.9&&min<.1){if(x0<.2)uvBuffer[i+0]+=1;if(x1<.2)uvBuffer[i+2]+=1;if(x2<.2)uvBuffer[i+4]+=1}}}function pushVertex(vertex2){vertexBuffer.push(vertex2.x,vertex2.y,vertex2.z)}function getVertexByIndex(index,vertex2){const stride=index*3;vertex2.x=vertices[stride+0];vertex2.y=vertices[stride+1];vertex2.z=vertices[stride+2]}function correctUVs(){const a=new Vector3;const b=new Vector3;const c=new Vector3;const centroid=new Vector3;const uvA=new Vector2;const uvB=new Vector2;const uvC=new Vector2;for(let i=0,j=0;i80*dim){minX=maxX=data[0];minY=maxY=data[1];for(let i=dim;imaxX)maxX=x2;if(y2>maxY)maxY=y2}invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?1/invSize:0}earcutLinked(outerNode,triangles,dim,minX,minY,invSize);return triangles}};function linkedList(data,start,end,dim,clockwise){let i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i=start;i-=dim)last=insertNode(i,data[i],data[i+1],last)}if(last&&equals(last,last.next)){removeNode(last);last=last.next}return last}function filterPoints(start,end){if(!start)return start;if(!end)end=start;let p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)break;again=true}else{p=p.next}}while(again||p!==end);return end}function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);let stop=ear,prev,next;while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);ear=next.next;stop=next.next;continue}ear=next;if(ear===stop){if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1)}else if(pass===1){ear=cureLocalIntersections(filterPoints(ear),triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2)}else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize)}break}}}function isEar(ear){const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;let p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next}return true}function isEarHashed(ear,minX,minY,invSize){const a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;const minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;const minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);let p=ear.prevZ,n=ear.nextZ;while(p&&p.z>=minZ&&n&&n.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ}while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ}while(n&&n.z<=maxZ){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ}return true}function cureLocalIntersections(start,triangles,dim){let p=start;do{const a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);removeNode(p);removeNode(p.next);p=start=b}p=p.next}while(p!==start);return filterPoints(p)}function splitEarcut(start,triangles,dim,minX,minY,invSize){let a=start;do{let b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){let c=splitPolygon(a,b);a=filterPoints(a,a.next);c=filterPoints(c,c.next);earcutLinked(a,triangles,dim,minX,minY,invSize);earcutLinked(c,triangles,dim,minX,minY,invSize);return}b=b.next}a=a.next}while(a!==start)}function eliminateHoles(data,holeIndices,outerNode,dim){const queue=[];let i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y&&p.next.y!==p.y){const x2=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x2<=hx&&x2>qx){qx=x2;if(x2===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next}m=p.x=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x||p.x===m.x&§orContainsSector(m,p)))){m=p;tanMin=tan}}p=p.next}while(p!==stop);return m}function sectorContainsSector(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0}function indexCurve(start,minX,minY,invSize){let p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,invSize);p.prevZ=p.prev;p.nextZ=p.next;p=p.next}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p)}function sortLinked(list){let i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||qSize>0&&q){if(pSize!==0&&(qSize===0||!q||p.z<=q.z)){e=p;p=p.nextZ;pSize--}else{e=q;q=q.nextZ;qSize--}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e}p=q}tail.nextZ=null;inSize*=2}while(numMerges>1);return list}function zOrder(x2,y2,minX,minY,invSize){x2=32767*(x2-minX)*invSize;y2=32767*(y2-minY)*invSize;x2=(x2|x2<<8)&16711935;x2=(x2|x2<<4)&252645135;x2=(x2|x2<<2)&858993459;x2=(x2|x2<<1)&1431655765;y2=(y2|y2<<8)&16711935;y2=(y2|y2<<4)&252645135;y2=(y2|y2<<2)&858993459;y2=(y2|y2<<1)&1431655765;return x2|y2<<1}function getLeftmost(start){let p=start,leftmost=start;do{if(p.x=0&&(ax-px2)*(by-py2)-(bx-px2)*(ay-py2)>=0&&(bx-px2)*(cy-py2)-(cx-px2)*(by-py2)>=0}function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0)}function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y)}function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y}function intersects(p1,q1,p2,q2){const o1=sign(area(p1,q1,p2));const o2=sign(area(p1,q1,q2));const o3=sign(area(p2,q2,p1));const o4=sign(area(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;if(o1===0&&onSegment(p1,p2,q1))return true;if(o2===0&&onSegment(p1,q2,q1))return true;if(o3===0&&onSegment(p2,p1,q2))return true;if(o4===0&&onSegment(p2,q1,q2))return true;return false}function onSegment(p,q,r){return q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y)}function sign(num){return num>0?1:num<0?-1:0}function intersectsPolygon(a,b){let p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next}while(p!==a);return false}function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0}function middleInside(a,b){let p=a,inside=false;const px2=(a.x+b.x)/2,py2=(a.y+b.y)/2;do{if(p.y>py2!==p.next.y>py2&&p.next.y!==p.y&&px2<(p.next.x-p.x)*(py2-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next}while(p!==a);return inside}function splitPolygon(a,b){const a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2}function insertNode(i,x2,y2,last){const p=new Node(i,x2,y2);if(!last){p.prev=p;p.next=p}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p}return p}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ}function Node(i,x2,y2){this.i=i;this.x=x2;this.y=y2;this.prev=null;this.next=null;this.z=null;this.prevZ=null;this.nextZ=null;this.steiner=false}function signedArea(data,start,end,dim){let sum=0;for(let i=start,j=end-dim;i2&&points[l-1].equals(points[0])){points.pop()}}function addContour(vertices,contour){for(let i=0;iNumber.EPSILON){const v_prev_len=Math.sqrt(v_prev_lensq);const v_next_len=Math.sqrt(v_next_x*v_next_x+v_next_y*v_next_y);const ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;const ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;const ptNextShift_x=inNext.x-v_next_y/v_next_len;const ptNextShift_y=inNext.y+v_next_x/v_next_len;const sf=((ptNextShift_x-ptPrevShift_x)*v_next_y-(ptNextShift_y-ptPrevShift_y)*v_next_x)/(v_prev_x*v_next_y-v_prev_y*v_next_x);v_trans_x=ptPrevShift_x+v_prev_x*sf-inPt.x;v_trans_y=ptPrevShift_y+v_prev_y*sf-inPt.y;const v_trans_lensq=v_trans_x*v_trans_x+v_trans_y*v_trans_y;if(v_trans_lensq<=2){return new Vector2(v_trans_x,v_trans_y)}else{shrink_by=Math.sqrt(v_trans_lensq/2)}}else{let direction_eq=false;if(v_prev_x>Number.EPSILON){if(v_next_x>Number.EPSILON){direction_eq=true}}else{if(v_prev_x<-Number.EPSILON){if(v_next_x<-Number.EPSILON){direction_eq=true}}else{if(Math.sign(v_prev_y)===Math.sign(v_next_y)){direction_eq=true}}}if(direction_eq){v_trans_x=-v_prev_y;v_trans_y=v_prev_x;shrink_by=Math.sqrt(v_prev_lensq)}else{v_trans_x=v_prev_x;v_trans_y=v_prev_y;shrink_by=Math.sqrt(v_prev_lensq/2)}}return new Vector2(v_trans_x/shrink_by,v_trans_y/shrink_by)}const contourMovements=[];for(let i=0,il=contour.length,j=il-1,k=i+1;i=0;b--){const t=b/bevelSegments;const z=bevelThickness*Math.cos(t*Math.PI/2);const bs2=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;for(let i=0,il=contour.length;i=0){const j=i;let k=i-1;if(k<0)k=contour2.length-1;for(let s=0,sl=steps+bevelSegments*2;s0)indices.push(a,b,d);if(iy!==heightSegments-1||thetaEnd0!==value>0){this.version++}this._sheen=value}get clearcoat(){return this._clearcoat}set clearcoat(value){if(this._clearcoat>0!==value>0){this.version++}this._clearcoat=value}get iridescence(){return this._iridescence}set iridescence(value){if(this._iridescence>0!==value>0){this.version++}this._iridescence=value}get transmission(){return this._transmission}set transmission(value){if(this._transmission>0!==value>0){this.version++}this._transmission=value}copy(source){super.copy(source);this.defines={"STANDARD":"","PHYSICAL":""};this.clearcoat=source.clearcoat;this.clearcoatMap=source.clearcoatMap;this.clearcoatRoughness=source.clearcoatRoughness;this.clearcoatRoughnessMap=source.clearcoatRoughnessMap;this.clearcoatNormalMap=source.clearcoatNormalMap;this.clearcoatNormalScale.copy(source.clearcoatNormalScale);this.ior=source.ior;this.iridescence=source.iridescence;this.iridescenceMap=source.iridescenceMap;this.iridescenceIOR=source.iridescenceIOR;this.iridescenceThicknessRange=[...source.iridescenceThicknessRange];this.iridescenceThicknessMap=source.iridescenceThicknessMap;this.sheen=source.sheen;this.sheenColor.copy(source.sheenColor);this.sheenColorMap=source.sheenColorMap;this.sheenRoughness=source.sheenRoughness;this.sheenRoughnessMap=source.sheenRoughnessMap;this.transmission=source.transmission;this.transmissionMap=source.transmissionMap;this.thickness=source.thickness;this.thicknessMap=source.thicknessMap;this.attenuationDistance=source.attenuationDistance;this.attenuationColor.copy(source.attenuationColor);this.specularIntensity=source.specularIntensity;this.specularIntensityMap=source.specularIntensityMap;this.specularColor.copy(source.specularColor);this.specularColorMap=source.specularColorMap;return this}};var MeshPhongMaterial=class extends Material{constructor(parameters){super();this.isMeshPhongMaterial=true;this.type="MeshPhongMaterial";this.color=new Color(16777215);this.specular=new Color(1118481);this.shininess=30;this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.flatShading=false;this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.specular.copy(source.specular);this.shininess=source.shininess;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.flatShading=source.flatShading;this.fog=source.fog;return this}};var MeshToonMaterial=class extends Material{constructor(parameters){super();this.isMeshToonMaterial=true;this.defines={"TOON":""};this.type="MeshToonMaterial";this.color=new Color(16777215);this.map=null;this.gradientMap=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.map=source.map;this.gradientMap=source.gradientMap;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.fog=source.fog;return this}};var MeshNormalMaterial=class extends Material{constructor(parameters){super();this.isMeshNormalMaterial=true;this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.flatShading=false;this.setValues(parameters)}copy(source){super.copy(source);this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.flatShading=source.flatShading;return this}};var MeshLambertMaterial=class extends Material{constructor(parameters){super();this.isMeshLambertMaterial=true;this.type="MeshLambertMaterial";this.color=new Color(16777215);this.map=null;this.lightMap=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new Color(0);this.emissiveIntensity=1;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap="round";this.wireframeLinejoin="round";this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.fog=source.fog;return this}};var MeshMatcapMaterial=class extends Material{constructor(parameters){super();this.isMeshMatcapMaterial=true;this.defines={"MATCAP":""};this.type="MeshMatcapMaterial";this.color=new Color(16777215);this.matcap=null;this.map=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.flatShading=false;this.fog=true;this.setValues(parameters)}copy(source){super.copy(source);this.defines={"MATCAP":""};this.color.copy(source.color);this.matcap=source.matcap;this.map=source.map;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.flatShading=source.flatShading;this.fog=source.fog;return this}};var LineDashedMaterial=class extends LineBasicMaterial{constructor(parameters){super();this.isLineDashedMaterial=true;this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(parameters)}copy(source){super.copy(source);this.scale=source.scale;this.dashSize=source.dashSize;this.gapSize=source.gapSize;return this}};function arraySlice(array,from,to){if(isTypedArray2(array)){return new array.constructor(array.subarray(from,to!==void 0?to:array.length))}return array.slice(from,to)}function convertArray(array,type,forceClone){if(!array||!forceClone&&array.constructor===type)return array;if(typeof type.BYTES_PER_ELEMENT==="number"){return new type(array)}return Array.prototype.slice.call(array)}function isTypedArray2(object){return ArrayBuffer.isView(object)&&!(object instanceof DataView)}function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j]}const n=times.length;const result=new Array(n);for(let i=0;i!==n;++i)result[i]=i;result.sort(compareTime);return result}function sortedArray(values,stride,order){const nValues=values.length;const result=new values.constructor(nValues);for(let i=0,dstOffset=0;dstOffset!==nValues;++i){const srcOffset=order[i]*stride;for(let j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j]}}return result}function flattenJSON(jsonKeys,times,values,valuePropertyName){let i=1,key=jsonKeys[0];while(key!==void 0&&key[valuePropertyName]===void 0){key=jsonKeys[i++]}if(key===void 0)return;let value=key[valuePropertyName];if(value===void 0)return;if(Array.isArray(value)){do{value=key[valuePropertyName];if(value!==void 0){times.push(key.time);values.push.apply(values,value)}key=jsonKeys[i++]}while(key!==void 0)}else if(value.toArray!==void 0){do{value=key[valuePropertyName];if(value!==void 0){times.push(key.time);value.toArray(values,values.length)}key=jsonKeys[i++]}while(key!==void 0)}else{do{value=key[valuePropertyName];if(value!==void 0){times.push(key.time);values.push(value)}key=jsonKeys[i++]}while(key!==void 0)}}function subclip(sourceClip,name,startFrame,endFrame,fps=30){const clip=sourceClip.clone();clip.name=name;const tracks=[];for(let i=0;i=endFrame)continue;times.push(track.times[j]);for(let k=0;kclip.tracks[i].times[0]){minStartTime=clip.tracks[i].times[0]}}for(let i=0;i=referenceTrack.times[lastIndex]){const startIndex=lastIndex*referenceValueSize+referenceOffset;const endIndex=startIndex+referenceValueSize-referenceOffset;referenceValue=arraySlice(referenceTrack.values,startIndex,endIndex)}else{const interpolant=referenceTrack.createInterpolant();const startIndex=referenceOffset;const endIndex=referenceValueSize-referenceOffset;interpolant.evaluate(referenceTime);referenceValue=arraySlice(interpolant.resultBuffer,startIndex,endIndex)}if(referenceTrackType==="quaternion"){const referenceQuat=new Quaternion().fromArray(referenceValue).normalize().conjugate();referenceQuat.toArray(referenceValue)}const numTimes=targetTrack.times.length;for(let j=0;j=t0)){const t1global=pp[1];if(t=t0){break seek}}right=i1;i1=0;break linear_scan}break validate_interval}while(i1>>1;if(tendTime){--to}++to;if(from!==0||to!==nKeys){if(from>=to){to=Math.max(to,1);from=to-1}const stride=this.getValueSize();this.times=arraySlice(times,from,to);this.values=arraySlice(this.values,from*stride,to*stride)}return this}validate(){let valid=true;const valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error("THREE.KeyframeTrack: Invalid value size in track.",this);valid=false}const times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error("THREE.KeyframeTrack: Track is empty.",this);valid=false}let prevTime=null;for(let i=0;i!==nKeys;i++){const currTime=times[i];if(typeof currTime==="number"&&isNaN(currTime)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,i,currTime);valid=false;break}if(prevTime!==null&&prevTime>currTime){console.error("THREE.KeyframeTrack: Out of order keys.",this,i,currTime,prevTime);valid=false;break}prevTime=currTime}if(values!==void 0){if(isTypedArray2(values)){for(let i=0,n=values.length;i!==n;++i){const value=values[i];if(isNaN(value)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,i,value);valid=false;break}}}}return valid}optimize(){const times=arraySlice(this.times),values=arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,lastIndex=times.length-1;let writeIndex=1;for(let i=1;i0){times[writeIndex]=times[lastIndex];for(let readOffset=lastIndex*stride,writeOffset=writeIndex*stride,j=0;j!==stride;++j){values[writeOffset+j]=values[readOffset+j]}++writeIndex}if(writeIndex!==times.length){this.times=arraySlice(times,0,writeIndex);this.values=arraySlice(values,0,writeIndex*stride)}else{this.times=times;this.values=values}return this}clone(){const times=arraySlice(this.times,0);const values=arraySlice(this.values,0);const TypedKeyframeTrack=this.constructor;const track=new TypedKeyframeTrack(this.name,times,values);track.createInterpolant=this.createInterpolant;return track}};KeyframeTrack.prototype.TimeBufferType=Float32Array;KeyframeTrack.prototype.ValueBufferType=Float32Array;KeyframeTrack.prototype.DefaultInterpolation=InterpolateLinear;var BooleanKeyframeTrack=class extends KeyframeTrack{};BooleanKeyframeTrack.prototype.ValueTypeName="bool";BooleanKeyframeTrack.prototype.ValueBufferType=Array;BooleanKeyframeTrack.prototype.DefaultInterpolation=InterpolateDiscrete;BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0;BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;var ColorKeyframeTrack=class extends KeyframeTrack{};ColorKeyframeTrack.prototype.ValueTypeName="color";var NumberKeyframeTrack=class extends KeyframeTrack{};NumberKeyframeTrack.prototype.ValueTypeName="number";var QuaternionLinearInterpolant=class extends Interpolant{constructor(parameterPositions,sampleValues,sampleSize,resultBuffer){super(parameterPositions,sampleValues,sampleSize,resultBuffer)}interpolate_(i1,t0,t,t1){const result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,alpha=(t-t0)/(t1-t0);let offset=i1*stride;for(let end=offset+stride;offset!==end;offset+=4){Quaternion.slerpFlat(result,0,values,offset-stride,values,offset,alpha)}return result}};var QuaternionKeyframeTrack=class extends KeyframeTrack{InterpolantFactoryMethodLinear(result){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),result)}};QuaternionKeyframeTrack.prototype.ValueTypeName="quaternion";QuaternionKeyframeTrack.prototype.DefaultInterpolation=InterpolateLinear;QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;var StringKeyframeTrack=class extends KeyframeTrack{};StringKeyframeTrack.prototype.ValueTypeName="string";StringKeyframeTrack.prototype.ValueBufferType=Array;StringKeyframeTrack.prototype.DefaultInterpolation=InterpolateDiscrete;StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear=void 0;StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth=void 0;var VectorKeyframeTrack=class extends KeyframeTrack{};VectorKeyframeTrack.prototype.ValueTypeName="vector";var AnimationClip=class{constructor(name,duration=-1,tracks,blendMode=NormalAnimationBlendMode){this.name=name;this.tracks=tracks;this.duration=duration;this.blendMode=blendMode;this.uuid=generateUUID();if(this.duration<0){this.resetDuration()}}static parse(json){const tracks=[],jsonTracks=json.tracks,frameTime=1/(json.fps||1);for(let i=0,n=jsonTracks.length;i!==n;++i){tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime))}const clip=new this(json.name,json.duration,tracks,json.blendMode);clip.uuid=json.uuid;return clip}static toJSON(clip){const tracks=[],clipTracks=clip.tracks;const json={"name":clip.name,"duration":clip.duration,"tracks":tracks,"uuid":clip.uuid,"blendMode":clip.blendMode};for(let i=0,n=clipTracks.length;i!==n;++i){tracks.push(KeyframeTrack.toJSON(clipTracks[i]))}return json}static CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){const numMorphTargets=morphTargetSequence.length;const tracks=[];for(let i=0;i1){const name=parts[1];let animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[]}animationMorphTargets.push(morphTarget)}}const clips=[];for(const name in animationToMorphTargets){clips.push(this.CreateFromMorphTargetSequence(name,animationToMorphTargets[name],fps,noLoop))}return clips}static parseAnimation(animation,bones){if(!animation){console.error("THREE.AnimationClip: No animation in JSONLoader data.");return null}const addNonemptyTrack=function(trackType,trackName,animationKeys,propertyName,destTracks){if(animationKeys.length!==0){const times=[];const values=[];flattenJSON(animationKeys,times,values,propertyName);if(times.length!==0){destTracks.push(new trackType(trackName,times,values))}}};const tracks=[];const clipName=animation.name||"default";const fps=animation.fps||30;const blendMode=animation.blendMode;let duration=animation.length||-1;const hierarchyTracks=animation.hierarchy||[];for(let h=0;h{if(onLoad)onLoad(cached);this.manager.itemEnd(url)},0);return cached}if(loading[url]!==void 0){loading[url].push({onLoad,onProgress,onError});return}loading[url]=[];loading[url].push({onLoad,onProgress,onError});const req=new Request(url,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"});const mimeType=this.mimeType;const responseType=this.responseType;fetch(req).then(response=>{if(response.status===200||response.status===0){if(response.status===0){console.warn("THREE.FileLoader: HTTP Status 0 received.")}if(typeof ReadableStream==="undefined"||response.body===void 0||response.body.getReader===void 0){return response}const callbacks=loading[url];const reader=response.body.getReader();const contentLength=response.headers.get("Content-Length");const total=contentLength?parseInt(contentLength):0;const lengthComputable=total!==0;let loaded=0;const stream=new ReadableStream({start(controller){readData();function readData(){reader.read().then(({done,value})=>{if(done){controller.close()}else{loaded+=value.byteLength;const event=new ProgressEvent("progress",{lengthComputable,loaded,total});for(let i=0,il=callbacks.length;i{switch(responseType){case"arraybuffer":return response.arrayBuffer();case"blob":return response.blob();case"document":return response.text().then(text=>{const parser=new DOMParser;return parser.parseFromString(text,mimeType)});case"json":return response.json();default:if(mimeType===void 0){return response.text()}else{const re=/charset="?([^;"\s]*)"?/i;const exec=re.exec(mimeType);const label=exec&&exec[1]?exec[1].toLowerCase():void 0;const decoder=new TextDecoder(label);return response.arrayBuffer().then(ab=>decoder.decode(ab))}}}).then(data=>{Cache.add(url,data);const callbacks=loading[url];delete loading[url];for(let i=0,il=callbacks.length;i{const callbacks=loading[url];if(callbacks===void 0){this.manager.itemError(url);throw err}delete loading[url];for(let i=0,il=callbacks.length;i{this.manager.itemEnd(url)});this.manager.itemStart(url)}setResponseType(value){this.responseType=value;return this}setMimeType(value){this.mimeType=value;return this}};var AnimationLoader=class extends Loader{constructor(manager){super(manager)}load(url,onLoad,onProgress,onError){const scope=this;const loader=new FileLoader(this.manager);loader.setPath(this.path);loader.setRequestHeader(this.requestHeader);loader.setWithCredentials(this.withCredentials);loader.load(url,function(text){try{onLoad(scope.parse(JSON.parse(text)))}catch(e){if(onError){onError(e)}else{console.error(e)}scope.manager.itemError(url)}},onProgress,onError)}parse(json){const animations=[];for(let i=0;i0?true:false}else{material.vertexColors=json.vertexColors}}if(json.uniforms!==void 0){for(const name in json.uniforms){const uniform=json.uniforms[name];material.uniforms[name]={};switch(uniform.type){case"t":material.uniforms[name].value=getTexture(uniform.value);break;case"c":material.uniforms[name].value=new Color().setHex(uniform.value);break;case"v2":material.uniforms[name].value=new Vector2().fromArray(uniform.value);break;case"v3":material.uniforms[name].value=new Vector3().fromArray(uniform.value);break;case"v4":material.uniforms[name].value=new Vector4().fromArray(uniform.value);break;case"m3":material.uniforms[name].value=new Matrix3().fromArray(uniform.value);break;case"m4":material.uniforms[name].value=new Matrix4().fromArray(uniform.value);break;default:material.uniforms[name].value=uniform.value}}}if(json.defines!==void 0)material.defines=json.defines;if(json.vertexShader!==void 0)material.vertexShader=json.vertexShader;if(json.fragmentShader!==void 0)material.fragmentShader=json.fragmentShader;if(json.extensions!==void 0){for(const key in json.extensions){material.extensions[key]=json.extensions[key]}}if(json.shading!==void 0)material.flatShading=json.shading===1;if(json.size!==void 0)material.size=json.size;if(json.sizeAttenuation!==void 0)material.sizeAttenuation=json.sizeAttenuation;if(json.map!==void 0)material.map=getTexture(json.map);if(json.matcap!==void 0)material.matcap=getTexture(json.matcap);if(json.alphaMap!==void 0)material.alphaMap=getTexture(json.alphaMap);if(json.bumpMap!==void 0)material.bumpMap=getTexture(json.bumpMap);if(json.bumpScale!==void 0)material.bumpScale=json.bumpScale;if(json.normalMap!==void 0)material.normalMap=getTexture(json.normalMap);if(json.normalMapType!==void 0)material.normalMapType=json.normalMapType;if(json.normalScale!==void 0){let normalScale=json.normalScale;if(Array.isArray(normalScale)===false){normalScale=[normalScale,normalScale]}material.normalScale=new Vector2().fromArray(normalScale)}if(json.displacementMap!==void 0)material.displacementMap=getTexture(json.displacementMap);if(json.displacementScale!==void 0)material.displacementScale=json.displacementScale;if(json.displacementBias!==void 0)material.displacementBias=json.displacementBias;if(json.roughnessMap!==void 0)material.roughnessMap=getTexture(json.roughnessMap);if(json.metalnessMap!==void 0)material.metalnessMap=getTexture(json.metalnessMap);if(json.emissiveMap!==void 0)material.emissiveMap=getTexture(json.emissiveMap);if(json.emissiveIntensity!==void 0)material.emissiveIntensity=json.emissiveIntensity;if(json.specularMap!==void 0)material.specularMap=getTexture(json.specularMap);if(json.specularIntensityMap!==void 0)material.specularIntensityMap=getTexture(json.specularIntensityMap);if(json.specularColorMap!==void 0)material.specularColorMap=getTexture(json.specularColorMap);if(json.envMap!==void 0)material.envMap=getTexture(json.envMap);if(json.envMapIntensity!==void 0)material.envMapIntensity=json.envMapIntensity;if(json.reflectivity!==void 0)material.reflectivity=json.reflectivity;if(json.refractionRatio!==void 0)material.refractionRatio=json.refractionRatio;if(json.lightMap!==void 0)material.lightMap=getTexture(json.lightMap);if(json.lightMapIntensity!==void 0)material.lightMapIntensity=json.lightMapIntensity;if(json.aoMap!==void 0)material.aoMap=getTexture(json.aoMap);if(json.aoMapIntensity!==void 0)material.aoMapIntensity=json.aoMapIntensity;if(json.gradientMap!==void 0)material.gradientMap=getTexture(json.gradientMap);if(json.clearcoatMap!==void 0)material.clearcoatMap=getTexture(json.clearcoatMap);if(json.clearcoatRoughnessMap!==void 0)material.clearcoatRoughnessMap=getTexture(json.clearcoatRoughnessMap);if(json.clearcoatNormalMap!==void 0)material.clearcoatNormalMap=getTexture(json.clearcoatNormalMap);if(json.clearcoatNormalScale!==void 0)material.clearcoatNormalScale=new Vector2().fromArray(json.clearcoatNormalScale);if(json.iridescenceMap!==void 0)material.iridescenceMap=getTexture(json.iridescenceMap);if(json.iridescenceThicknessMap!==void 0)material.iridescenceThicknessMap=getTexture(json.iridescenceThicknessMap);if(json.transmissionMap!==void 0)material.transmissionMap=getTexture(json.transmissionMap);if(json.thicknessMap!==void 0)material.thicknessMap=getTexture(json.thicknessMap);if(json.sheenColorMap!==void 0)material.sheenColorMap=getTexture(json.sheenColorMap);if(json.sheenRoughnessMap!==void 0)material.sheenRoughnessMap=getTexture(json.sheenRoughnessMap);return material}setTextures(value){this.textures=value;return this}static createMaterialFromType(type){const materialLib={ShadowMaterial,SpriteMaterial,RawShaderMaterial,ShaderMaterial,PointsMaterial,MeshPhysicalMaterial,MeshStandardMaterial,MeshPhongMaterial,MeshToonMaterial,MeshNormalMaterial,MeshLambertMaterial,MeshDepthMaterial,MeshDistanceMaterial,MeshBasicMaterial,MeshMatcapMaterial,LineDashedMaterial,LineBasicMaterial,Material};return new materialLib[type]}};var LoaderUtils=class{static decodeText(array){if(typeof TextDecoder!=="undefined"){return new TextDecoder().decode(array)}let s="";for(let i=0,il=array.length;i0){const manager=new LoadingManager(onLoad);loader=new ImageLoader(manager);loader.setCrossOrigin(this.crossOrigin);for(let i=0,il=json.length;i0){loader=new ImageLoader(this.manager);loader.setCrossOrigin(this.crossOrigin);for(let i=0,il=json.length;i0){this.source.connect(this.filters[0]);for(let i=1,l=this.filters.length;i0){this.source.disconnect(this.filters[0]);for(let i=1,l=this.filters.length;i0){this._mixBufferRegionAdditive(buffer,offset,this._addIndex*stride,1,stride)}for(let i=stride,e=stride+stride;i!==e;++i){if(buffer[i]!==buffer[i+stride]){binding.setValue(buffer,offset);break}}}saveOriginalState(){const binding=this.binding;const buffer=this.buffer,stride=this.valueSize,originalValueOffset=stride*this._origIndex;binding.getValue(buffer,originalValueOffset);for(let i=stride,e=originalValueOffset;i!==e;++i){buffer[i]=buffer[originalValueOffset+i%stride]}this._setIdentity();this.cumulativeWeight=0;this.cumulativeWeightAdditive=0}restoreOriginalState(){const originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset)}_setAdditiveIdentityNumeric(){const startIndex=this._addIndex*this.valueSize;const endIndex=startIndex+this.valueSize;for(let i=startIndex;i=.5){for(let i=0;i!==stride;++i){buffer[dstOffset+i]=buffer[srcOffset+i]}}}_slerp(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t)}_slerpAdditive(buffer,dstOffset,srcOffset,t,stride){const workOffset=this._workIndex*stride;Quaternion.multiplyQuaternionsFlat(buffer,workOffset,buffer,dstOffset,buffer,srcOffset);Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,workOffset,t)}_lerp(buffer,dstOffset,srcOffset,t,stride){const s=1-t;for(let i=0;i!==stride;++i){const j=dstOffset+i;buffer[j]=buffer[j]*s+buffer[srcOffset+i]*t}}_lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(let i=0;i!==stride;++i){const j=dstOffset+i;buffer[j]=buffer[j]+buffer[srcOffset+i]*t}}};var _RESERVED_CHARS_RE="\\[\\]\\.:\\/";var _reservedRe=new RegExp("["+_RESERVED_CHARS_RE+"]","g");var _wordChar="[^"+_RESERVED_CHARS_RE+"]";var _wordCharOrDot="[^"+_RESERVED_CHARS_RE.replace("\\.","")+"]";var _directoryRe=/((?:WC+[\/:])*)/.source.replace("WC",_wordChar);var _nodeRe=/(WCOD+)?/.source.replace("WCOD",_wordCharOrDot);var _objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",_wordChar);var _propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",_wordChar);var _trackRe=new RegExp("^"+_directoryRe+_nodeRe+_objectRe+_propertyRe+"$");var _supportedObjectNames=["material","materials","bones"];var Composite=class{constructor(targetGroup,path,optionalParsedPath){const parsedPath=optionalParsedPath||PropertyBinding.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath)}getValue(array,offset){this.bind();const firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];if(binding!==void 0)binding.getValue(array,offset)}setValue(array,offset){const bindings=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].setValue(array,offset)}}bind(){const bindings=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].bind()}}unbind(){const bindings=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=bindings.length;i!==n;++i){bindings[i].unbind()}}};var PropertyBinding=class{constructor(rootNode,path,parsedPath){this.path=path;this.parsedPath=parsedPath||PropertyBinding.parseTrackName(path);this.node=PropertyBinding.findNode(rootNode,this.parsedPath.nodeName)||rootNode;this.rootNode=rootNode;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}static create(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding(root,path,parsedPath)}else{return new PropertyBinding.Composite(root,path,parsedPath)}}static sanitizeNodeName(name){return name.replace(/\s/g,"_").replace(_reservedRe,"")}static parseTrackName(trackName){const matches=_trackRe.exec(trackName);if(matches===null){throw new Error("PropertyBinding: Cannot parse trackName: "+trackName)}const results={nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],propertyIndex:matches[6]};const lastDot=results.nodeName&&results.nodeName.lastIndexOf(".");if(lastDot!==void 0&&lastDot!==-1){const objectName=results.nodeName.substring(lastDot+1);if(_supportedObjectNames.indexOf(objectName)!==-1){results.nodeName=results.nodeName.substring(0,lastDot);results.objectName=objectName}}if(results.propertyName===null||results.propertyName.length===0){throw new Error("PropertyBinding: can not parse propertyName from trackName: "+trackName)}return results}static findNode(root,nodeName){if(nodeName===void 0||nodeName===""||nodeName==="."||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root}if(root.skeleton){const bone=root.skeleton.getBoneByName(nodeName);if(bone!==void 0){return bone}}if(root.children){const searchNodeSubtree=function(children){for(let i=0;i=nCachedObjects){const lastCachedIndex=nCachedObjects++,firstActiveObject=objects2[lastCachedIndex];indicesByUUID[firstActiveObject.uuid]=index;objects2[index]=firstActiveObject;indicesByUUID[uuid]=lastCachedIndex;objects2[lastCachedIndex]=object;for(let j=0,m=nBindings;j!==m;++j){const bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding}}}this.nCachedObjects_=nCachedObjects}uncache(){const objects2=this._objects,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;let nCachedObjects=this.nCachedObjects_,nObjects=objects2.length;for(let i=0,n=arguments.length;i!==n;++i){const object=arguments[i],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==void 0){delete indicesByUUID[uuid];if(index0){indicesByUUID[lastObject.uuid]=index}objects2[index]=lastObject;objects2.pop();for(let j=0,m=nBindings;j!==m;++j){const bindingsForPath=bindings[j];bindingsForPath[index]=bindingsForPath[lastIndex];bindingsForPath.pop()}}}}this.nCachedObjects_=nCachedObjects}subscribe_(path,parsedPath){const indicesByPath=this._bindingsIndicesByPath;let index=indicesByPath[path];const bindings=this._bindings;if(index!==void 0)return bindings[index];const paths=this._paths,parsedPaths=this._parsedPaths,objects2=this._objects,nObjects=objects2.length,nCachedObjects=this.nCachedObjects_,bindingsForPath=new Array(nObjects);index=bindings.length;indicesByPath[path]=index;paths.push(path);parsedPaths.push(parsedPath);bindings.push(bindingsForPath);for(let i=nCachedObjects,n=objects2.length;i!==n;++i){const object=objects2[i];bindingsForPath[i]=new PropertyBinding(object,path,parsedPath)}return bindingsForPath}unsubscribe_(path){const indicesByPath=this._bindingsIndicesByPath,index=indicesByPath[path];if(index!==void 0){const paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,lastBindingsIndex=bindings.length-1,lastBindings=bindings[lastBindingsIndex],lastBindingsPath=path[lastBindingsIndex];indicesByPath[lastBindingsPath]=index;bindings[index]=lastBindings;bindings.pop();parsedPaths[index]=parsedPaths[lastBindingsIndex];parsedPaths.pop();paths[index]=paths[lastBindingsIndex];paths.pop()}}};var AnimationAction=class{constructor(mixer,clip,localRoot=null,blendMode=clip.blendMode){this._mixer=mixer;this._clip=clip;this._localRoot=localRoot;this.blendMode=blendMode;const tracks=clip.tracks,nTracks=tracks.length,interpolants=new Array(nTracks);const interpolantSettings={endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding};for(let i=0;i!==nTracks;++i){const interpolant=tracks[i].createInterpolant(null);interpolants[i]=interpolant;interpolant.settings=interpolantSettings}this._interpolantSettings=interpolantSettings;this._interpolants=interpolants;this._propertyBindings=new Array(nTracks);this._cacheIndex=null;this._byClipCacheIndex=null;this._timeScaleInterpolant=null;this._weightInterpolant=null;this.loop=LoopRepeat;this._loopCount=-1;this._startTime=null;this.time=0;this.timeScale=1;this._effectiveTimeScale=1;this.weight=1;this._effectiveWeight=1;this.repetitions=Infinity;this.paused=false;this.enabled=true;this.clampWhenFinished=false;this.zeroSlopeAtStart=true;this.zeroSlopeAtEnd=true}play(){this._mixer._activateAction(this);return this}stop(){this._mixer._deactivateAction(this);return this.reset()}reset(){this.paused=false;this.enabled=true;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(time){this._startTime=time;return this}setLoop(mode,repetitions){this.loop=mode;this.repetitions=repetitions;return this}setEffectiveWeight(weight){this.weight=weight;this._effectiveWeight=this.enabled?weight:0;return this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(duration){return this._scheduleFading(duration,0,1)}fadeOut(duration){return this._scheduleFading(duration,1,0)}crossFadeFrom(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){const fadeInDuration=this._clip.duration,fadeOutDuration=fadeOutAction._clip.duration,startEndRatio=fadeOutDuration/fadeInDuration,endStartRatio=fadeInDuration/fadeOutDuration;fadeOutAction.warp(1,startEndRatio,duration);this.warp(endStartRatio,1,duration)}return this}crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp)}stopFading(){const weightInterpolant=this._weightInterpolant;if(weightInterpolant!==null){this._weightInterpolant=null;this._mixer._takeBackControlInterpolant(weightInterpolant)}return this}setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping()}syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping()}halt(duration){return this.warp(this._effectiveTimeScale,0,duration)}warp(startTimeScale,endTimeScale,duration){const mixer=this._mixer,now2=mixer.time,timeScale=this.timeScale;let interpolant=this._timeScaleInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant}const times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now2;times[1]=now2+duration;values[0]=startTimeScale/timeScale;values[1]=endTimeScale/timeScale;return this}stopWarping(){const timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant)}return this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(time,deltaTime,timeDirection,accuIndex){if(!this.enabled){this._updateWeight(time);return}const startTime=this._startTime;if(startTime!==null){const timeRunning=(time-startTime)*timeDirection;if(timeRunning<0||timeDirection===0){return}this._startTime=null;deltaTime=timeDirection*timeRunning}deltaTime*=this._updateTimeScale(time);const clipTime=this._updateTime(deltaTime);const weight=this._updateWeight(time);if(weight>0){const interpolants=this._interpolants;const propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode:for(let j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight)}break;case NormalAnimationBlendMode:default:for(let j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulate(accuIndex,weight)}}}}_updateWeight(time){let weight=0;if(this.enabled){weight=this.weight;const interpolant=this._weightInterpolant;if(interpolant!==null){const interpolantValue=interpolant.evaluate(time)[0];weight*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopFading();if(interpolantValue===0){this.enabled=false}}}}this._effectiveWeight=weight;return weight}_updateTimeScale(time){let timeScale=0;if(!this.paused){timeScale=this.timeScale;const interpolant=this._timeScaleInterpolant;if(interpolant!==null){const interpolantValue=interpolant.evaluate(time)[0];timeScale*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopWarping();if(timeScale===0){this.paused=true}else{this.timeScale=timeScale}}}}this._effectiveTimeScale=timeScale;return timeScale}_updateTime(deltaTime){const duration=this._clip.duration;const loop2=this.loop;let time=this.time+deltaTime;let loopCount=this._loopCount;const pingPong=loop2===LoopPingPong;if(deltaTime===0){if(loopCount===-1)return time;return pingPong&&(loopCount&1)===1?duration-time:time}if(loop2===LoopOnce){if(loopCount===-1){this._loopCount=0;this._setEndings(true,true,false)}handle_stop:{if(time>=duration){time=duration}else if(time<0){time=0}else{this.time=time;break handle_stop}if(this.clampWhenFinished)this.paused=true;else this.enabled=false;this.time=time;this._mixer.dispatchEvent({type:"finished",action:this,direction:deltaTime<0?-1:1})}}else{if(loopCount===-1){if(deltaTime>=0){loopCount=0;this._setEndings(true,this.repetitions===0,pingPong)}else{this._setEndings(this.repetitions===0,true,pingPong)}}if(time>=duration||time<0){const loopDelta=Math.floor(time/duration);time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);const pending=this.repetitions-loopCount;if(pending<=0){if(this.clampWhenFinished)this.paused=true;else this.enabled=false;time=deltaTime>0?duration:0;this.time=time;this._mixer.dispatchEvent({type:"finished",action:this,direction:deltaTime>0?1:-1})}else{if(pending===1){const atStart=deltaTime<0;this._setEndings(atStart,!atStart,pingPong)}else{this._setEndings(false,false,pingPong)}this._loopCount=loopCount;this.time=time;this._mixer.dispatchEvent({type:"loop",action:this,loopDelta})}}else{this.time=time}if(pingPong&&(loopCount&1)===1){return duration-time}}return time}_setEndings(atStart,atEnd,pingPong){const settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding;settings.endingEnd=ZeroSlopeEnding}else{if(atStart){settings.endingStart=this.zeroSlopeAtStart?ZeroSlopeEnding:ZeroCurvatureEnding}else{settings.endingStart=WrapAroundEnding}if(atEnd){settings.endingEnd=this.zeroSlopeAtEnd?ZeroSlopeEnding:ZeroCurvatureEnding}else{settings.endingEnd=WrapAroundEnding}}}_scheduleFading(duration,weightNow,weightThen){const mixer=this._mixer,now2=mixer.time;let interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant}const times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now2;values[0]=weightNow;times[1]=now2+duration;values[1]=weightThen;return this}};var _controlInterpolantsResultBuffer=new Float32Array(1);var AnimationMixer=class extends EventDispatcher2{constructor(root){super();this._root=root;this._initMemoryManager();this._accuIndex=0;this.time=0;this.timeScale=1}_bindAction(action,prototypeAction){const root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName;let bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===void 0){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName}for(let i=0;i!==nTracks;++i){const track=tracks[i],trackName=track.name;let binding=bindingsByName[trackName];if(binding!==void 0){++binding.referenceCount;bindings[i]=binding}else{binding=bindings[i];if(binding!==void 0){if(binding._cacheIndex===null){++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName)}continue}const path=prototypeAction&&prototypeAction._propertyBindings[i].binding.parsedPath;binding=new PropertyMixer(PropertyBinding.create(root,trackName,path),track.ValueTypeName,track.getValueSize());++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);bindings[i]=binding}interpolants[i].resultBuffer=binding.buffer}}_activateAction(action){if(!this._isActiveAction(action)){if(action._cacheIndex===null){const rootUuid=(action._localRoot||this._root).uuid,clipUuid=action._clip.uuid,actionsForClip=this._actionsByClip[clipUuid];this._bindAction(action,actionsForClip&&actionsForClip.knownActions[0]);this._addInactiveAction(action,clipUuid,rootUuid)}const bindings=action._propertyBindings;for(let i=0,n=bindings.length;i!==n;++i){const binding=bindings[i];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState()}}this._lendAction(action)}}_deactivateAction(action){if(this._isActiveAction(action)){const bindings=action._propertyBindings;for(let i=0,n=bindings.length;i!==n;++i){const binding=bindings[i];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding)}}this._takeBackAction(action)}}_initMemoryManager(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;const scope=this;this.stats={actions:{get total(){return scope._actions.length},get inUse(){return scope._nActiveActions}},bindings:{get total(){return scope._bindings.length},get inUse(){return scope._nActiveBindings}},controlInterpolants:{get total(){return scope._controlInterpolants.length},get inUse(){return scope._nActiveControlInterpolants}}}}_isActiveAction(action){const index=action._cacheIndex;return index!==null&&index=0;--i){actions[i].stop()}return this}update(deltaTime){deltaTime*=this.timeScale;const actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;for(let i=0;i!==nActions;++i){const action=actions[i];action._update(time,deltaTime,timeDirection,accuIndex)}const bindings=this._bindings,nBindings=this._nActiveBindings;for(let i=0;i!==nBindings;++i){bindings[i].apply(accuIndex)}return this}setTime(timeInSeconds){this.time=0;for(let i=0;ithis.max.x||point.ythis.max.y?false:true}containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y}getParameter(point,target){return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(box){return box.max.xthis.max.x||box.max.ythis.max.y?false:true}clampPoint(point,target){return target.copy(point).clamp(this.min,this.max)}distanceToPoint(point){const clampedPoint=_vector$4.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length()}intersect(box){this.min.max(box.min);this.max.min(box.max);return this}union(box){this.min.min(box.min);this.max.max(box.max);return this}translate(offset){this.min.add(offset);this.max.add(offset);return this}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max)}};var _startP=new Vector3;var _startEnd=new Vector3;var Line3=class{constructor(start=new Vector3,end=new Vector3){this.start=start;this.end=end}set(start,end){this.start.copy(start);this.end.copy(end);return this}copy(line){this.start.copy(line.start);this.end.copy(line.end);return this}getCenter(target){return target.addVectors(this.start,this.end).multiplyScalar(.5)}delta(target){return target.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,target){return this.delta(target).multiplyScalar(t).add(this.start)}closestPointToPointParameter(point,clampToLine){_startP.subVectors(point,this.start);_startEnd.subVectors(this.end,this.start);const startEnd2=_startEnd.dot(_startEnd);const startEnd_startP=_startEnd.dot(_startP);let t=startEnd_startP/startEnd2;if(clampToLine){t=clamp(t,0,1)}return t}closestPointToPoint(point,clampToLine,target){const t=this.closestPointToPointParameter(point,clampToLine);return this.delta(target).multiplyScalar(t).add(this.start)}applyMatrix4(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this}equals(line){return line.start.equals(this.start)&&line.end.equals(this.end)}clone(){return new this.constructor().copy(this)}};var _vector$3=new Vector3;var SpotLightHelper=class extends Object3D{constructor(light,color){super();this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;const geometry=new BufferGeometry;const positions=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let i=0,j=1,l=32;i.99999){this.quaternion.set(0,0,0,1)}else if(dir.y<-.99999){this.quaternion.set(1,0,0,0)}else{_axis.set(dir.z,0,-dir.x).normalize();const radians=Math.acos(dir.y);this.quaternion.setFromAxisAngle(_axis,radians)}}setLength(length,headLength=length*.2,headWidth=headLength*.2){this.line.scale.set(1,Math.max(1e-4,length-headLength),1);this.line.updateMatrix();this.cone.scale.set(headWidth,headLength,headWidth);this.cone.position.y=length;this.cone.updateMatrix()}setColor(color){this.line.material.color.set(color);this.cone.material.color.set(color)}copy(source){super.copy(source,false);this.line.copy(source.line);this.cone.copy(source.cone);return this}};var AxesHelper=class extends LineSegments{constructor(size=1){const vertices=[0,0,0,size,0,0,0,0,0,0,size,0,0,0,0,0,0,size];const colors=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1];const geometry=new BufferGeometry;geometry.setAttribute("position",new Float32BufferAttribute(vertices,3));geometry.setAttribute("color",new Float32BufferAttribute(colors,3));const material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type="AxesHelper"}setColors(xAxisColor,yAxisColor,zAxisColor){const color=new Color;const array=this.geometry.attributes.color.array;color.set(xAxisColor);color.toArray(array,0);color.toArray(array,3);color.set(yAxisColor);color.toArray(array,6);color.toArray(array,9);color.set(zAxisColor);color.toArray(array,12);color.toArray(array,15);this.geometry.attributes.color.needsUpdate=true;return this}dispose(){this.geometry.dispose();this.material.dispose()}};var ShapePath=class{constructor(){this.type="ShapePath";this.color=new Color;this.subPaths=[];this.currentPath=null}moveTo(x2,y2){this.currentPath=new Path;this.subPaths.push(this.currentPath);this.currentPath.moveTo(x2,y2);return this}lineTo(x2,y2){this.currentPath.lineTo(x2,y2);return this}quadraticCurveTo(aCPx,aCPy,aX,aY){this.currentPath.quadraticCurveTo(aCPx,aCPy,aX,aY);return this}bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){this.currentPath.bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY);return this}splineThru(pts){this.currentPath.splineThru(pts);return this}toShapes(isCCW,noHoles){function toShapesNoHoles(inSubpaths){const shapes2=[];for(let i=0,l=inSubpaths.length;iNumber.EPSILON){if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy}if(inPt.yedgeHighPt.y)continue;if(inPt.y===edgeLowPt.y){if(inPt.x===edgeLowPt.x)return true}else{const perpEdge=edgeDy*(inPt.x-edgeLowPt.x)-edgeDx*(inPt.y-edgeLowPt.y);if(perpEdge===0)return true;if(perpEdge<0)continue;inside=!inside}}else{if(inPt.y!==edgeLowPt.y)continue;if(edgeHighPt.x<=inPt.x&&inPt.x<=edgeLowPt.x||edgeLowPt.x<=inPt.x&&inPt.x<=edgeHighPt.x)return true}}return inside}const isClockWise=ShapeUtils.isClockWise;const subPaths=this.subPaths;if(subPaths.length===0)return[];if(noHoles===true)return toShapesNoHoles(subPaths);let solid,tmpPath,tmpShape;const shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape;tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes}let holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;const betterShapeHoles=[];const newShapes=[];let newShapeHoles=[];let mainIdx=0;let tmpPoints;newShapes[mainIdx]=void 0;newShapeHoles[mainIdx]=[];for(let i=0,l=subPaths.length;i1){let ambiguous=false;let toChange=0;for(let sIdx=0,sLen=newShapes.length;sIdx0&&ambiguous===false){newShapeHoles=betterShapeHoles}}let tmpHoles;for(let i=0,il=newShapes.length;i>-e-14;baseTable[i|256]=1024>>-e-14|32768;shiftTable[i]=-e-1;shiftTable[i|256]=-e-1}else if(e<=15){baseTable[i]=e+15<<10;baseTable[i|256]=e+15<<10|32768;shiftTable[i]=13;shiftTable[i|256]=13}else if(e<128){baseTable[i]=31744;baseTable[i|256]=64512;shiftTable[i]=24;shiftTable[i|256]=24}else{baseTable[i]=31744;baseTable[i|256]=64512;shiftTable[i]=13;shiftTable[i|256]=13}}const mantissaTable=new Uint32Array(2048);const exponentTable=new Uint32Array(64);const offsetTable=new Uint32Array(64);for(let i=1;i<1024;++i){let m=i<<13;let e=0;while((m&8388608)===0){m<<=1;e-=8388608}m&=~8388608;e+=947912704;mantissaTable[i]=m|e}for(let i=1024;i<2048;++i){mantissaTable[i]=939524096+(i-1024<<13)}for(let i=1;i<31;++i){exponentTable[i]=i<<23}exponentTable[31]=1199570944;exponentTable[32]=2147483648;for(let i=33;i<63;++i){exponentTable[i]=2147483648+(i-32<<23)}exponentTable[63]=3347054592;for(let i=1;i<64;++i){if(i!==32){offsetTable[i]=1024}}return{floatView,uint32View,baseTable,shiftTable,mantissaTable,exponentTable,offsetTable}}function toHalfFloat(val){if(Math.abs(val)>65504)console.warn("THREE.DataUtils.toHalfFloat(): Value out of range.");val=clamp(val,-65504,65504);_tables.floatView[0]=val;const f=_tables.uint32View[0];const e=f>>23&511;return _tables.baseTable[e]+((f&8388607)>>_tables.shiftTable[e])}function fromHalfFloat(val){const m=val>>10;_tables.uint32View[0]=_tables.mantissaTable[_tables.offsetTable[m]+(val&1023)]+_tables.exponentTable[m];return _tables.floatView[0]}var DataUtils=Object.freeze({__proto__:null,toHalfFloat,fromHalfFloat});var ParametricGeometry=class extends BufferGeometry{constructor(){console.error("THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js");super()}};var TextGeometry=class extends BufferGeometry{constructor(){console.error("THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js");super()}};function FontLoader(){console.error("THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js")}function Font(){console.error("THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js")}function ImmediateRenderObject(){console.error("THREE.ImmediateRenderObject has been removed.")}var WebGLMultisampleRenderTarget=class extends WebGLRenderTarget{constructor(width,height,options){console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');super(width,height,options);this.samples=4}};var DataTexture2DArray=class extends DataArrayTexture{constructor(data,width,height,depth){console.warn("THREE.DataTexture2DArray has been renamed to DataArrayTexture.");super(data,width,height,depth)}};var DataTexture3D=class extends Data3DTexture{constructor(data,width,height,depth){console.warn("THREE.DataTexture3D has been renamed to Data3DTexture.");super(data,width,height,depth)}};if(typeof __THREE_DEVTOOLS__!=="undefined"){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:REVISION}}))}if(typeof window!=="undefined"){if(window.__THREE__){console.warn("WARNING: Multiple instances of Three.js being imported.")}else{window.__THREE__=REVISION}}var _changeEvent={type:"change"};var _startEvent={type:"start"};var _endEvent={type:"end"};var OrbitControls=class extends EventDispatcher2{constructor(object,domElement){super();if(domElement===void 0)console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');if(domElement===document)console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');this.object=object;this.domElement=domElement;this.domElement.style.touchAction="none";this.enabled=true;this.target=new Vector3;this.minDistance=0;this.maxDistance=Infinity;this.minZoom=0;this.maxZoom=Infinity;this.minPolarAngle=0;this.maxPolarAngle=Math.PI;this.minAzimuthAngle=-Infinity;this.maxAzimuthAngle=Infinity;this.enableDamping=false;this.dampingFactor=.05;this.enableZoom=true;this.zoomSpeed=1;this.enableRotate=true;this.rotateSpeed=1;this.enablePan=true;this.panSpeed=1;this.screenSpacePanning=true;this.keyPanSpeed=7;this.autoRotate=false;this.autoRotateSpeed=2;this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"};this.mouseButtons={LEFT:MOUSE.ROTATE,MIDDLE:MOUSE.DOLLY,RIGHT:MOUSE.PAN};this.touches={ONE:TOUCH.ROTATE,TWO:TOUCH.DOLLY_PAN};this.target0=this.target.clone();this.position0=this.object.position.clone();this.zoom0=this.object.zoom;this._domElementKeyEvents=null;this.getPolarAngle=function(){return spherical.phi};this.getAzimuthalAngle=function(){return spherical.theta};this.getDistance=function(){return this.object.position.distanceTo(this.target)};this.listenToKeyEvents=function(domElement2){domElement2.addEventListener("keydown",onKeyDown);this._domElementKeyEvents=domElement2};this.saveState=function(){scope.target0.copy(scope.target);scope.position0.copy(scope.object.position);scope.zoom0=scope.object.zoom};this.reset=function(){scope.target.copy(scope.target0);scope.object.position.copy(scope.position0);scope.object.zoom=scope.zoom0;scope.object.updateProjectionMatrix();scope.dispatchEvent(_changeEvent);scope.update();state=STATE.NONE};this.update=function(){const offset=new Vector3;const quat=new Quaternion().setFromUnitVectors(object.up,new Vector3(0,1,0));const quatInverse=quat.clone().invert();const lastPosition=new Vector3;const lastQuaternion=new Quaternion;const twoPI=2*Math.PI;return function update(){const position=scope.object.position;offset.copy(position).sub(scope.target);offset.applyQuaternion(quat);spherical.setFromVector3(offset);if(scope.autoRotate&&state===STATE.NONE){rotateLeft(getAutoRotationAngle())}if(scope.enableDamping){spherical.theta+=sphericalDelta.theta*scope.dampingFactor;spherical.phi+=sphericalDelta.phi*scope.dampingFactor}else{spherical.theta+=sphericalDelta.theta;spherical.phi+=sphericalDelta.phi}let min=scope.minAzimuthAngle;let max=scope.maxAzimuthAngle;if(isFinite(min)&&isFinite(max)){if(min<-Math.PI)min+=twoPI;else if(min>Math.PI)min-=twoPI;if(max<-Math.PI)max+=twoPI;else if(max>Math.PI)max-=twoPI;if(min<=max){spherical.theta=Math.max(min,Math.min(max,spherical.theta))}else{spherical.theta=spherical.theta>(min+max)/2?Math.max(min,spherical.theta):Math.min(max,spherical.theta)}}spherical.phi=Math.max(scope.minPolarAngle,Math.min(scope.maxPolarAngle,spherical.phi));spherical.makeSafe();spherical.radius*=scale;spherical.radius=Math.max(scope.minDistance,Math.min(scope.maxDistance,spherical.radius));if(scope.enableDamping===true){scope.target.addScaledVector(panOffset,scope.dampingFactor)}else{scope.target.add(panOffset)}offset.setFromSpherical(spherical);offset.applyQuaternion(quatInverse);position.copy(scope.target).add(offset);scope.object.lookAt(scope.target);if(scope.enableDamping===true){sphericalDelta.theta*=1-scope.dampingFactor;sphericalDelta.phi*=1-scope.dampingFactor;panOffset.multiplyScalar(1-scope.dampingFactor)}else{sphericalDelta.set(0,0,0);panOffset.set(0,0,0)}scale=1;if(zoomChanged||lastPosition.distanceToSquared(scope.object.position)>EPS||8*(1-lastQuaternion.dot(scope.object.quaternion))>EPS){scope.dispatchEvent(_changeEvent);lastPosition.copy(scope.object.position);lastQuaternion.copy(scope.object.quaternion);zoomChanged=false;return true}return false}}();this.dispose=function(){scope.domElement.removeEventListener("contextmenu",onContextMenu);scope.domElement.removeEventListener("pointerdown",onPointerDown);scope.domElement.removeEventListener("pointercancel",onPointerCancel);scope.domElement.removeEventListener("wheel",onMouseWheel);scope.domElement.removeEventListener("pointermove",onPointerMove);scope.domElement.removeEventListener("pointerup",onPointerUp);if(scope._domElementKeyEvents!==null){scope._domElementKeyEvents.removeEventListener("keydown",onKeyDown)}};const scope=this;const STATE={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let state=STATE.NONE;const EPS=1e-6;const spherical=new Spherical;const sphericalDelta=new Spherical;let scale=1;const panOffset=new Vector3;let zoomChanged=false;const rotateStart=new Vector2;const rotateEnd=new Vector2;const rotateDelta=new Vector2;const panStart=new Vector2;const panEnd=new Vector2;const panDelta=new Vector2;const dollyStart=new Vector2;const dollyEnd=new Vector2;const dollyDelta=new Vector2;const pointers=[];const pointerPositions={};function getAutoRotationAngle(){return 2*Math.PI/60/60*scope.autoRotateSpeed}function getZoomScale(){return Math.pow(.95,scope.zoomSpeed)}function rotateLeft(angle){sphericalDelta.theta-=angle}function rotateUp(angle){sphericalDelta.phi-=angle}const panLeft=function(){const v=new Vector3;return function panLeft2(distance,objectMatrix){v.setFromMatrixColumn(objectMatrix,0);v.multiplyScalar(-distance);panOffset.add(v)}}();const panUp=function(){const v=new Vector3;return function panUp2(distance,objectMatrix){if(scope.screenSpacePanning===true){v.setFromMatrixColumn(objectMatrix,1)}else{v.setFromMatrixColumn(objectMatrix,0);v.crossVectors(scope.object.up,v)}v.multiplyScalar(distance);panOffset.add(v)}}();const pan=function(){const offset=new Vector3;return function pan2(deltaX,deltaY){const element=scope.domElement;if(scope.object.isPerspectiveCamera){const position=scope.object.position;offset.copy(position).sub(scope.target);let targetDistance=offset.length();targetDistance*=Math.tan(scope.object.fov/2*Math.PI/180);panLeft(2*deltaX*targetDistance/element.clientHeight,scope.object.matrix);panUp(2*deltaY*targetDistance/element.clientHeight,scope.object.matrix)}else if(scope.object.isOrthographicCamera){panLeft(deltaX*(scope.object.right-scope.object.left)/scope.object.zoom/element.clientWidth,scope.object.matrix);panUp(deltaY*(scope.object.top-scope.object.bottom)/scope.object.zoom/element.clientHeight,scope.object.matrix)}else{console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");scope.enablePan=false}}}();function dollyOut(dollyScale){if(scope.object.isPerspectiveCamera){scale/=dollyScale}else if(scope.object.isOrthographicCamera){scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom*dollyScale));scope.object.updateProjectionMatrix();zoomChanged=true}else{console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");scope.enableZoom=false}}function dollyIn(dollyScale){if(scope.object.isPerspectiveCamera){scale*=dollyScale}else if(scope.object.isOrthographicCamera){scope.object.zoom=Math.max(scope.minZoom,Math.min(scope.maxZoom,scope.object.zoom/dollyScale));scope.object.updateProjectionMatrix();zoomChanged=true}else{console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");scope.enableZoom=false}}function handleMouseDownRotate(event){rotateStart.set(event.clientX,event.clientY)}function handleMouseDownDolly(event){dollyStart.set(event.clientX,event.clientY)}function handleMouseDownPan(event){panStart.set(event.clientX,event.clientY)}function handleMouseMoveRotate(event){rotateEnd.set(event.clientX,event.clientY);rotateDelta.subVectors(rotateEnd,rotateStart).multiplyScalar(scope.rotateSpeed);const element=scope.domElement;rotateLeft(2*Math.PI*rotateDelta.x/element.clientHeight);rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight);rotateStart.copy(rotateEnd);scope.update()}function handleMouseMoveDolly(event){dollyEnd.set(event.clientX,event.clientY);dollyDelta.subVectors(dollyEnd,dollyStart);if(dollyDelta.y>0){dollyOut(getZoomScale())}else if(dollyDelta.y<0){dollyIn(getZoomScale())}dollyStart.copy(dollyEnd);scope.update()}function handleMouseMovePan(event){panEnd.set(event.clientX,event.clientY);panDelta.subVectors(panEnd,panStart).multiplyScalar(scope.panSpeed);pan(panDelta.x,panDelta.y);panStart.copy(panEnd);scope.update()}function handleMouseWheel(event){if(event.deltaY<0){dollyIn(getZoomScale())}else if(event.deltaY>0){dollyOut(getZoomScale())}scope.update()}function handleKeyDown(event){let needsUpdate=false;switch(event.code){case scope.keys.UP:pan(0,scope.keyPanSpeed);needsUpdate=true;break;case scope.keys.BOTTOM:pan(0,-scope.keyPanSpeed);needsUpdate=true;break;case scope.keys.LEFT:pan(scope.keyPanSpeed,0);needsUpdate=true;break;case scope.keys.RIGHT:pan(-scope.keyPanSpeed,0);needsUpdate=true;break}if(needsUpdate){event.preventDefault();scope.update()}}function handleTouchStartRotate(){if(pointers.length===1){rotateStart.set(pointers[0].pageX,pointers[0].pageY)}else{const x2=.5*(pointers[0].pageX+pointers[1].pageX);const y2=.5*(pointers[0].pageY+pointers[1].pageY);rotateStart.set(x2,y2)}}function handleTouchStartPan(){if(pointers.length===1){panStart.set(pointers[0].pageX,pointers[0].pageY)}else{const x2=.5*(pointers[0].pageX+pointers[1].pageX);const y2=.5*(pointers[0].pageY+pointers[1].pageY);panStart.set(x2,y2)}}function handleTouchStartDolly(){const dx=pointers[0].pageX-pointers[1].pageX;const dy=pointers[0].pageY-pointers[1].pageY;const distance=Math.sqrt(dx*dx+dy*dy);dollyStart.set(0,distance)}function handleTouchStartDollyPan(){if(scope.enableZoom)handleTouchStartDolly();if(scope.enablePan)handleTouchStartPan()}function handleTouchStartDollyRotate(){if(scope.enableZoom)handleTouchStartDolly();if(scope.enableRotate)handleTouchStartRotate()}function handleTouchMoveRotate(event){if(pointers.length==1){rotateEnd.set(event.pageX,event.pageY)}else{const position=getSecondPointerPosition(event);const x2=.5*(event.pageX+position.x);const y2=.5*(event.pageY+position.y);rotateEnd.set(x2,y2)}rotateDelta.subVectors(rotateEnd,rotateStart).multiplyScalar(scope.rotateSpeed);const element=scope.domElement;rotateLeft(2*Math.PI*rotateDelta.x/element.clientHeight);rotateUp(2*Math.PI*rotateDelta.y/element.clientHeight);rotateStart.copy(rotateEnd)}function handleTouchMovePan(event){if(pointers.length===1){panEnd.set(event.pageX,event.pageY)}else{const position=getSecondPointerPosition(event);const x2=.5*(event.pageX+position.x);const y2=.5*(event.pageY+position.y);panEnd.set(x2,y2)}panDelta.subVectors(panEnd,panStart).multiplyScalar(scope.panSpeed);pan(panDelta.x,panDelta.y);panStart.copy(panEnd)}function handleTouchMoveDolly(event){const position=getSecondPointerPosition(event);const dx=event.pageX-position.x;const dy=event.pageY-position.y;const distance=Math.sqrt(dx*dx+dy*dy);dollyEnd.set(0,distance);dollyDelta.set(0,Math.pow(dollyEnd.y/dollyStart.y,scope.zoomSpeed));dollyOut(dollyDelta.y);dollyStart.copy(dollyEnd)}function handleTouchMoveDollyPan(event){if(scope.enableZoom)handleTouchMoveDolly(event);if(scope.enablePan)handleTouchMovePan(event)}function handleTouchMoveDollyRotate(event){if(scope.enableZoom)handleTouchMoveDolly(event);if(scope.enableRotate)handleTouchMoveRotate(event)}function onPointerDown(event){if(scope.enabled===false)return;if(pointers.length===0){scope.domElement.setPointerCapture(event.pointerId);scope.domElement.addEventListener("pointermove",onPointerMove);scope.domElement.addEventListener("pointerup",onPointerUp)}addPointer(event);if(event.pointerType==="touch"){onTouchStart(event)}else{onMouseDown(event)}}function onPointerMove(event){if(scope.enabled===false)return;if(event.pointerType==="touch"){onTouchMove(event)}else{onMouseMove(event)}}function onPointerUp(event){removePointer(event);if(pointers.length===0){scope.domElement.releasePointerCapture(event.pointerId);scope.domElement.removeEventListener("pointermove",onPointerMove);scope.domElement.removeEventListener("pointerup",onPointerUp)}scope.dispatchEvent(_endEvent);state=STATE.NONE}function onPointerCancel(event){removePointer(event)}function onMouseDown(event){let mouseAction;switch(event.button){case 0:mouseAction=scope.mouseButtons.LEFT;break;case 1:mouseAction=scope.mouseButtons.MIDDLE;break;case 2:mouseAction=scope.mouseButtons.RIGHT;break;default:mouseAction=-1}switch(mouseAction){case MOUSE.DOLLY:if(scope.enableZoom===false)return;handleMouseDownDolly(event);state=STATE.DOLLY;break;case MOUSE.ROTATE:if(event.ctrlKey||event.metaKey||event.shiftKey){if(scope.enablePan===false)return;handleMouseDownPan(event);state=STATE.PAN}else{if(scope.enableRotate===false)return;handleMouseDownRotate(event);state=STATE.ROTATE}break;case MOUSE.PAN:if(event.ctrlKey||event.metaKey||event.shiftKey){if(scope.enableRotate===false)return;handleMouseDownRotate(event);state=STATE.ROTATE}else{if(scope.enablePan===false)return;handleMouseDownPan(event);state=STATE.PAN}break;default:state=STATE.NONE}if(state!==STATE.NONE){scope.dispatchEvent(_startEvent)}}function onMouseMove(event){switch(state){case STATE.ROTATE:if(scope.enableRotate===false)return;handleMouseMoveRotate(event);break;case STATE.DOLLY:if(scope.enableZoom===false)return;handleMouseMoveDolly(event);break;case STATE.PAN:if(scope.enablePan===false)return;handleMouseMovePan(event);break}}function onMouseWheel(event){if(scope.enabled===false||scope.enableZoom===false||state!==STATE.NONE)return;event.preventDefault();scope.dispatchEvent(_startEvent);handleMouseWheel(event);scope.dispatchEvent(_endEvent)}function onKeyDown(event){if(scope.enabled===false||scope.enablePan===false)return;handleKeyDown(event)}function onTouchStart(event){trackPointer(event);switch(pointers.length){case 1:switch(scope.touches.ONE){case TOUCH.ROTATE:if(scope.enableRotate===false)return;handleTouchStartRotate();state=STATE.TOUCH_ROTATE;break;case TOUCH.PAN:if(scope.enablePan===false)return;handleTouchStartPan();state=STATE.TOUCH_PAN;break;default:state=STATE.NONE}break;case 2:switch(scope.touches.TWO){case TOUCH.DOLLY_PAN:if(scope.enableZoom===false&&scope.enablePan===false)return;handleTouchStartDollyPan();state=STATE.TOUCH_DOLLY_PAN;break;case TOUCH.DOLLY_ROTATE:if(scope.enableZoom===false&&scope.enableRotate===false)return;handleTouchStartDollyRotate();state=STATE.TOUCH_DOLLY_ROTATE;break;default:state=STATE.NONE}break;default:state=STATE.NONE}if(state!==STATE.NONE){scope.dispatchEvent(_startEvent)}}function onTouchMove(event){trackPointer(event);switch(state){case STATE.TOUCH_ROTATE:if(scope.enableRotate===false)return;handleTouchMoveRotate(event);scope.update();break;case STATE.TOUCH_PAN:if(scope.enablePan===false)return;handleTouchMovePan(event);scope.update();break;case STATE.TOUCH_DOLLY_PAN:if(scope.enableZoom===false&&scope.enablePan===false)return;handleTouchMoveDollyPan(event);scope.update();break;case STATE.TOUCH_DOLLY_ROTATE:if(scope.enableZoom===false&&scope.enableRotate===false)return;handleTouchMoveDollyRotate(event);scope.update();break;default:state=STATE.NONE}}function onContextMenu(event){if(scope.enabled===false)return;event.preventDefault()}function addPointer(event){pointers.push(event)}function removePointer(event){delete pointerPositions[event.pointerId];for(let i=0;i end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + // We correct the previous (-0.25, -0.125) offset we applied: + texcoord.x += 0.25 * resolution.x; + + // The searches are bias by 1, so adjust the coords accordingly: + texcoord.x += resolution.x; + + // Disambiguate the length added by the last step: + texcoord.x += 2.0 * resolution.x; // Undo last step + texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5); + + return texcoord.x; + } + + float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + texcoord.x -= 0.25 * resolution.x; + texcoord.x -= resolution.x; + texcoord.x -= 2.0 * resolution.x; + texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 ); + + return texcoord.x; + } + + float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y; // WebGL port note: Changed sign + texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y; // WebGL port note: Changed sign + texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) { + // Rounding prevents precision errors of bilinear filtering: + vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist; + + // We do a scale and bias for mapping to texel space: + texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE ); + + // Move to proper place, according to the subpixel offset: + texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + + return texture2D( areaTex, texcoord, 0.0 ).rg; + } + + vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) { + vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 ); + + vec2 e = texture2D( edgesTex, texcoord ).rg; + + if ( e.g > 0.0 ) { // Edge at north + vec2 d; + + // Find the distance to the left: + vec2 coords; + coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x ); + coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) + d.x = coords.x; + + // Now fetch the left crossing edges, two at a time using bilinear + // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to + // discern what value each edge has: + float e1 = texture2D( edgesTex, coords, 0.0 ).r; + + // Find the distance to the right: + coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y ); + d.y = coords.x; + + // We want the distances to be in pixel units (doing this here allow to + // better interleave arithmetic and memory accesses): + d = d / resolution.x - pixcoord.x; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the right crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r; + + // Ok, we know how this pattern looks like, now it is time for getting + // the actual area: + weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) ); + } + + if ( e.r > 0.0 ) { // Edge at west + vec2 d; + + // Find the distance to the top: + vec2 coords; + + coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z ); + coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x; + d.x = coords.y; + + // Fetch the top crossing edges: + float e1 = texture2D( edgesTex, coords, 0.0 ).g; + + // Find the distance to the bottom: + coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w ); + d.y = coords.y; + + // We want the distances to be in pixel units: + d = d / resolution.y - pixcoord.y; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the bottom crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g; + + // Get the area for this direction: + weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) ); + } + + return weights; + } + + void main() { + + gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) ); + + }`};var SMAABlendShader={uniforms:{"tDiffuse":{value:null},"tColor":{value:null},"resolution":{value:new Vector2(1/1024,1/512)}},vertexShader:` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + void SMAANeighborhoodBlendingVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAANeighborhoodBlendingVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`,fragmentShader:` + + uniform sampler2D tDiffuse; + uniform sampler2D tColor; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) { + // Fetch the blending weights for current pixel: + vec4 a; + a.xz = texture2D( blendTex, texcoord ).xz; + a.y = texture2D( blendTex, offset[ 1 ].zw ).g; + a.w = texture2D( blendTex, offset[ 1 ].xy ).a; + + // Is there any blending weight with a value greater than 0.0? + if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) { + return texture2D( colorTex, texcoord, 0.0 ); + } else { + // Up to 4 lines can be crossing a pixel (one through each edge). We + // favor blending by choosing the line with the maximum weight for each + // direction: + vec2 offset; + offset.x = a.a > a.b ? a.a : -a.b; // left vs. right + offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs + + // Then we go in the direction that has the maximum weight: + if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical + offset.y = 0.0; + } else { + offset.x = 0.0; + } + + // Fetch the opposite color and lerp by hand: + vec4 C = texture2D( colorTex, texcoord, 0.0 ); + texcoord += sign( offset ) * resolution; + vec4 Cop = texture2D( colorTex, texcoord, 0.0 ); + float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y ); + + // WebGL port note: Added gamma correction + C.xyz = pow(C.xyz, vec3(2.2)); + Cop.xyz = pow(Cop.xyz, vec3(2.2)); + vec4 mixed = mix(C, Cop, s); + mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2)); + + return mixed; + } + } + + void main() { + + gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse ); + + }`};var SMAAPass=class extends Pass{constructor(width,height){super();this.edgesRT=new WebGLRenderTarget(width,height,{depthBuffer:false});this.edgesRT.texture.name="SMAAPass.edges";this.weightsRT=new WebGLRenderTarget(width,height,{depthBuffer:false});this.weightsRT.texture.name="SMAAPass.weights";const scope=this;const areaTextureImage=new Image;areaTextureImage.src=this.getAreaTexture();areaTextureImage.onload=function(){scope.areaTexture.needsUpdate=true};this.areaTexture=new Texture;this.areaTexture.name="SMAAPass.area";this.areaTexture.image=areaTextureImage;this.areaTexture.minFilter=LinearFilter;this.areaTexture.generateMipmaps=false;this.areaTexture.flipY=false;const searchTextureImage=new Image;searchTextureImage.src=this.getSearchTexture();searchTextureImage.onload=function(){scope.searchTexture.needsUpdate=true};this.searchTexture=new Texture;this.searchTexture.name="SMAAPass.search";this.searchTexture.image=searchTextureImage;this.searchTexture.magFilter=NearestFilter;this.searchTexture.minFilter=NearestFilter;this.searchTexture.generateMipmaps=false;this.searchTexture.flipY=false;if(SMAAEdgesShader===void 0){console.error("THREE.SMAAPass relies on SMAAShader")}this.uniformsEdges=UniformsUtils.clone(SMAAEdgesShader.uniforms);this.uniformsEdges["resolution"].value.set(1/width,1/height);this.materialEdges=new ShaderMaterial({defines:Object.assign({},SMAAEdgesShader.defines),uniforms:this.uniformsEdges,vertexShader:SMAAEdgesShader.vertexShader,fragmentShader:SMAAEdgesShader.fragmentShader});this.uniformsWeights=UniformsUtils.clone(SMAAWeightsShader.uniforms);this.uniformsWeights["resolution"].value.set(1/width,1/height);this.uniformsWeights["tDiffuse"].value=this.edgesRT.texture;this.uniformsWeights["tArea"].value=this.areaTexture;this.uniformsWeights["tSearch"].value=this.searchTexture;this.materialWeights=new ShaderMaterial({defines:Object.assign({},SMAAWeightsShader.defines),uniforms:this.uniformsWeights,vertexShader:SMAAWeightsShader.vertexShader,fragmentShader:SMAAWeightsShader.fragmentShader});this.uniformsBlend=UniformsUtils.clone(SMAABlendShader.uniforms);this.uniformsBlend["resolution"].value.set(1/width,1/height);this.uniformsBlend["tDiffuse"].value=this.weightsRT.texture;this.materialBlend=new ShaderMaterial({uniforms:this.uniformsBlend,vertexShader:SMAABlendShader.vertexShader,fragmentShader:SMAABlendShader.fragmentShader});this.needsSwap=false;this.fsQuad=new FullScreenQuad(null)}render(renderer,writeBuffer,readBuffer){this.uniformsEdges["tDiffuse"].value=readBuffer.texture;this.fsQuad.material=this.materialEdges;renderer.setRenderTarget(this.edgesRT);if(this.clear)renderer.clear();this.fsQuad.render(renderer);this.fsQuad.material=this.materialWeights;renderer.setRenderTarget(this.weightsRT);if(this.clear)renderer.clear();this.fsQuad.render(renderer);this.uniformsBlend["tColor"].value=readBuffer.texture;this.fsQuad.material=this.materialBlend;if(this.renderToScreen){renderer.setRenderTarget(null);this.fsQuad.render(renderer)}else{renderer.setRenderTarget(writeBuffer);if(this.clear)renderer.clear();this.fsQuad.render(renderer)}}setSize(width,height){this.edgesRT.setSize(width,height);this.weightsRT.setSize(width,height);this.materialEdges.uniforms["resolution"].value.set(1/width,1/height);this.materialWeights.uniforms["resolution"].value.set(1/width,1/height);this.materialBlend.uniforms["resolution"].value.set(1/width,1/height)}getAreaTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K+e0N11yNfkKvwUdwdlUAXPHHL38oa15f/i/46Ih6SuMSPmLAYAwyRKn7dfMGH97jaMFBYCJUgotIC2YAdu+LyW9vvubxAP8kAL8H/koAuOKP3+q6+xGnd5kdYCeECnGIJViwGJMAkQKfDvB3WZxjLKGh8VSCCzhwEWBpMc5/kBbjawT4HnwJfhr+pPBIu7uu+OOTo9vsmtQcniMBGkKFd4jDWMSCRUpLjJYNJkM+IRzQ+PQvIeAMTrBS2LEiaiR9b/5PuT6Ap/AcfAFO4Y3dA3DFH7/VS+M8k4baEAQfMI4QfbVDDGIRg7GKaIY52qAjTAgTvGBAPGIIghOCYAUrGFNgzA7Q3QhgCwfwAnwe5vDejgG44o/fbm1C5ZlYQvQDARPAIQGxCWBM+wWl37ZQESb4gImexGMDouhGLx1Cst0Saa4b4AqO4Hk4gxo+3DHAV/nx27p3JziPM2pVgoiia5MdEzCGULprIN7gEEeQ5IQxEBBBQnxhsDb5auGmAAYcHMA9eAAz8PBol8/xij9+C4Djlim4gJjWcwZBhCBgMIIYxGAVIkH3ZtcBuLdtRFMWsPGoY9rN+HoBji9VBYdwD2ZQg4cnO7OSq/z4rU5KKdwVbFAjNojCQzTlCLPFSxtamwh2jMUcEgg2Wm/6XgErIBhBckQtGN3CzbVacERgCnfgLswhnvqf7QyAq/z4rRZm1YglYE3affGITaZsdIe2FmMIpnOCap25I6jt2kCwCW0D1uAD9sZctNGXcQIHCkINDQgc78aCr+zjtw3BU/ijdpw3zhCwcaONwBvdeS2YZKkJNJsMPf2JKEvC28RXxxI0ASJyzQCjCEQrO4Q7sFArEzjZhaFc4cdv+/JFdKULM4px0DfUBI2hIsy06BqLhGTQEVdbfAIZXYMPesq6VoCHICzUyjwInO4Y411//LYLs6TDa9wvg2CC2rElgAnpTBziThxaL22MYhzfkghz6GAs2VHbbdM91VZu1MEEpupMMwKyVTb5ij9+u4VJG/5EgEMMmFF01cFai3isRbKbzb+YaU/MQbAm2XSMoUPAmvZzbuKYRIFApbtlrfFuUGd6vq2hXNnH78ZLh/iFhsQG3T4D1ib7k5CC6vY0DCbtrohgLEIClXiGtl10zc0CnEGIhhatLBva7NP58Tvw0qE8yWhARLQ8h4+AhQSP+I4F5xoU+VilGRJs6wnS7ruti/4KvAY/CfdgqjsMy4pf8fodQO8/gnuX3f/3xi3om1/h7THr+co3x93PP9+FBUfbNUjcjEmhcrkT+8K7ml7V10Jo05mpIEFy1NmCJWx9SIKKt+EjAL4Ez8EBVOB6havuT/rByPvHXK+9zUcfcbb254+9fydJknYnRr1oGfdaiAgpxu1Rx/Rek8KISftx3L+DfsLWAANn8Hvw0/AFeAGO9DFV3c6D+CcWbL8Dj9e7f+T1k8AZv/d7+PXWM/Z+VvdCrIvuAKO09RpEEQJM0Ci6+B4xhTWr4cZNOvhktabw0ta0rSJmqz3Yw5/AKXwenod7cAhTmBSPKf6JBdvH8IP17h95pXqw50/+BFnj88fev4NchyaK47OPhhtI8RFSvAfDSNh0Ck0p2gLxGkib5NJj/JWCr90EWQJvwBzO4AHcgztwAFN1evHPUVGwfXON+0debT1YeGON9Yy9/63X+OguiwmhIhQhD7l4sMqlG3D86Suc3qWZ4rWjI1X7u0Ytw6x3rIMeIOPDprfe2XzNgyj6PahhBjO4C3e6puDgXrdg+/5l948vF3bqwZetZ+z9Rx9zdIY5pInPK4Nk0t+l52xdK2B45Qd87nM8fsD5EfUhIcJcERw4RdqqH7Yde5V7m1vhNmtedkz6EDzUMF/2jJYWbC+4fzzA/Y+/8PPH3j9dcBAPIRP8JLXd5BpAu03aziOL3VVHZzz3CXWDPWd+SH2AnxIqQoTZpo9Ckc6HIrFbAbzNmlcg8Ag8NFDDAhbJvTBZXbC94P7t68EXfv6o+21gUtPETU7bbkLxvNKRFG2+KXzvtObonPP4rBvsgmaKj404DlshFole1Glfh02fE7bYR7dZ82oTewIBGn1Md6CG6YUF26X376oevOLzx95vhUmgblI6LBZwTCDY7vMq0op5WVXgsObOXJ+1x3qaBl9j1FeLxbhU9w1F+Wiba6s1X/TBz1LnUfuYDi4r2C69f1f14BWfP+p+W2GFKuC9phcELMYRRLur9DEZTUdEH+iEqWdaM7X4WOoPGI+ZYD2+wcQ+y+ioHUZ9dTDbArzxmi/bJI9BND0Ynd6lBdve/butBw8+f/T9D3ABa3AG8W3VPX4hBin+bj8dMMmSpp5pg7fJ6xrBFE2WQQEWnV8Qg3FbAWzYfM1rREEnmvkN2o1+acG2d/9u68GDzx91v3mAjb1zkpqT21OipPKO0b9TO5W0nTdOmAQm0TObts3aBKgwARtoPDiCT0gHgwnbArzxmtcLc08HgF1asN0C4Ms/fvD5I+7PhfqyXE/b7RbbrGyRQRT9ARZcwAUmgdoz0ehJ9Fn7QAhUjhDAQSw0bV3T3WbNa59jzmiP6GsWbGXDX2ytjy8+f9T97fiBPq9YeLdBmyuizZHaqXITnXiMUEEVcJ7K4j3BFPurtB4bixW8wTpweL8DC95szWMOqucFYGsWbGU7p3TxxxefP+r+oTVktxY0v5hbq3KiOKYnY8ddJVSBxuMMVffNbxwIOERShst73HZ78DZrHpmJmH3K6sGz0fe3UUj0eyRrSCGTTc+rjVNoGzNSv05srAxUBh8IhqChiQgVNIIBH3AVPnrsnXQZbLTm8ammv8eVXn/vWpaTem5IXRlt+U/LA21zhSb9cye6jcOfCnOwhIAYXAMVTUNV0QhVha9xjgA27ODJbLbmitt3tRN80lqG6N/khgot4ZVlOyO4WNg3OIMzhIZQpUEHieg2im6F91hB3I2tubql6BYNN9Hj5S7G0G2tahslBWKDnOiIvuAEDzakDQKDNFQT6gbn8E2y4BBubM230YIpBnDbMa+y3dx0n1S0BtuG62lCCXwcY0F72T1VRR3t2ONcsmDjbmzNt9RFs2LO2hQNyb022JisaI8rAWuw4HI3FuAIhZdOGIcdjLJvvObqlpqvWTJnnQbyi/1M9O8UxWhBs//H42I0q1Yb/XPGONzcmm+ri172mHKvZBpHkJaNJz6v9jxqiklDj3U4CA2ugpAaYMWqNXsdXbmJNd9egCnJEsphXNM+MnK3m0FCJ5S1kmJpa3DgPVbnQnPGWIDspW9ozbcO4K/9LkfaQO2KHuqlfFXSbdNzcEcwoqNEFE9zcIXu9/6n/ym/BC/C3aJLzEKPuYVlbFnfhZ8kcWxV3dbv4bKl28566wD+8C53aw49lTABp9PWbsB+knfc/Li3eVizf5vv/xmvnPKg5ihwKEwlrcHqucuVcVOxEv8aH37E3ZqpZypUulrHEtIWKUr+txHg+ojZDGlwnqmkGlzcVi1dLiNSJiHjfbRNOPwKpx9TVdTn3K05DBx4psIk4Ei8aCkJahRgffk4YnEXe07T4H2RR1u27E6wfQsBDofUgjFUFnwC2AiVtA+05J2zpiDK2Oa0c5fmAecN1iJzmpqFZxqYBCYhFTCsUNEmUnIcZ6aEA5rQVhEywG6w7HSW02XfOoBlQmjwulOFQAg66SvJblrTEX1YtJ3uG15T/BH1OfOQeuR8g/c0gdpT5fx2SKbs9EfHTKdM8A1GaJRHLVIwhcGyydZsbifAFVKl5EMKNU2Hryo+06BeTgqnxzYjThVySDikbtJPieco75lYfKAJOMEZBTjoITuWHXXZVhcUDIS2hpiXHV9Ku4u44bN5OYLDOkJo8w+xJSMbhBRHEdEs9JZUCkQrPMAvaHyLkxgkEHxiNkx/x2YB0mGsQ8EUWj/stW5YLhtS5SMu+/YBbNPDCkGTUybN8krRLBGPlZkVOA0j+a1+rkyQKWGaPHPLZOkJhioQYnVZ2hS3zVxMtgC46KuRwbJNd9nV2PHgb36F194ecf/Yeu2vAFe5nm/bRBFrnY4BauE8ERmZRFUn0k8hbftiVYSKMEme2dJCJSCGYAlNqh87bXOPdUkGy24P6d1ll21MBqqx48Fvv8ZHH8HZFY7j/uAq1xMJUFqCSUlJPmNbIiNsmwuMs/q9CMtsZsFO6SprzCS1Z7QL8xCQClEelpjTduDMsmWD8S1PT152BtvmIGvUeDA/yRn83u/x0/4qxoPHjx+PXY9pqX9bgMvh/Nz9kpP4pOe1/fYf3axUiMdHLlPpZCNjgtNFAhcHEDxTumNONhHrBduW+vOyY++70WWnPXj98eA4kOt/mj/5E05l9+O4o8ePx67HFqyC+qSSnyselqjZGaVK2TadbFLPWAQ4NBhHqDCCV7OTpo34AlSSylPtIdd2AJZlyzYQrDJ5lcWGNceD80CunPLGGzsfD+7wRb95NevJI5docQ3tgCyr5bGnyaPRlmwNsFELViOOx9loebGNq2moDOKpHLVP5al2cymWHbkfzGXL7kfRl44H9wZy33tvt+PB/Xnf93e+nh5ZlU18wCiRUa9m7kib9LYuOk+hudQNbxwm0AQqbfloimaB2lM5fChex+ylMwuTbfmXQtmWlenZljbdXTLuOxjI/fDDHY4Hjx8/Hrse0zXfPFxbUN1kKqSCCSk50m0Ajtx3ub9XHBKHXESb8iO6E+qGytF4nO0OG3SXzbJlhxBnKtKyl0NwybjvYCD30aMdjgePHz8eu56SVTBbgxJMliQ3Oauwg0QHxXE2Ez/EIReLdQj42Gzb4CLS0YJD9xUx7bsi0vJi5mUbW1QzL0h0PFk17rtiIPfJk52MB48fPx67npJJwyrBa2RCCQRTbGZSPCxTPOiND4G2pYyOQ4h4jINIJh5wFU1NFZt+IsZ59LSnDqBjZ2awbOku+yInunLcd8VA7rNnOxkPHj9+PGY9B0MWJJNozOJmlglvDMXDEozdhQWbgs/U6oBanGzLrdSNNnZFjOkmbi5bNt1lX7JLLhn3vXAg9/h4y/Hg8ePHI9dzQMEkWCgdRfYykYKnkP7D4rIujsujaKPBsB54vE2TS00ccvFY/Tth7JXeq1hz+qgVy04sAJawTsvOknHfCwdyT062HA8eP348Zj0vdoXF4pilKa2BROed+9fyw9rWRXeTFXESMOanvDZfJuJaSXouQdMdDJZtekZcLLvEeK04d8m474UDuaenW44Hjx8/Xns9YYqZpszGWB3AN/4VHw+k7WSFtJ3Qicuqb/NlVmgXWsxh570xg2UwxUw3WfO6B5nOuO8aA7lnZxuPB48fPx6znm1i4bsfcbaptF3zNT78eFPtwi1OaCNOqp1x3zUGcs/PN++AGD1+fMXrSVm2baTtPhPahbPhA71wIHd2bXzRa69nG+3CraTtPivahV/55tXWg8fyRY/9AdsY8VbSdp8V7cKrrgdfM//z6ILQFtJ2nxHtwmuoB4/kf74+gLeRtvvMaBdeSz34+vifx0YG20jbfTa0C6+tHrwe//NmOG0L8EbSdp8R7cLrrQe/996O+ai3ujQOskpTNULa7jOjXXj99eCd8lHvoFiwsbTdZ0a78PrrwTvlo966pLuRtB2fFe3Cm6oHP9kNH/W2FryxtN1nTLvwRurBO+Kj3pWXHidtx2dFu/Bm68Fb81HvykuPlrb7LGkX3mw9eGs+6h1Y8MbSdjegXcguQLjmevDpTQLMxtJ2N6NdyBZu9AbrwVvwUW+LbteULUpCdqm0HTelXbhNPe8G68Gb8lFvVfYfSNuxvrTdTWoXbozAzdaDZzfkorOj1oxVxlIMlpSIlpLrt8D4hrQL17z+c3h6hU/wv4Q/utps4+bm+6P/hIcf0JwQ5oQGPBL0eKPTYEXTW+eL/2DKn73J9BTXYANG57hz1cEMviVf/4tf5b/6C5pTQkMIWoAq7hTpOJjtAM4pxKu5vg5vXeUrtI09/Mo/5H+4z+Mp5xULh7cEm2QbRP2tFIKR7WM3fPf/jZ3SWCqLM2l4NxID5zB72HQXv3jj/8mLR5xXNA5v8EbFQEz7PpRfl1+MB/hlAN65qgDn3wTgH13hK7T59bmP+NIx1SHHU84nLOITt3iVz8mNO+lPrjGAnBFqmioNn1mTyk1ta47R6d4MrX7tjrnjYUpdUbv2rVr6YpVfsGG58AG8Ah9eyUN8CX4WfgV+G8LVWPDGb+Zd4cU584CtqSbMKxauxTg+dyn/LkVgA+IR8KHtejeFKRtTmLLpxN6mYVLjYxwXf5x2VofiZcp/lwKk4wGOpYDnoIZPdg/AAbwMfx0+ge9dgZvYjuqKe4HnGnykYo5TvJbG0Vj12JagRhwKa44H95ShkZa5RyLGGdfYvG7aw1TsF6iapPAS29mNS3NmsTQZCmgTzFwgL3upCTgtBTRwvGMAKrgLn4evwin8+afJRcff+8izUGUM63GOOuAs3tJkw7J4kyoNreqrpO6cYLQeFUd7TTpr5YOTLc9RUUogUOVJQ1GYJaFLAW0oTmKyYS46ZooP4S4EON3xQ5zC8/CX4CnM4c1PE8ApexpoYuzqlP3d4S3OJP8ZDK7cKWNaTlqmgDiiHwl1YsE41w1zT4iRTm3DBqxvOUsbMKKDa/EHxagtnta072ejc3DOIh5ojvh8l3tk1JF/AV6FU6jh3U8HwEazLgdCLYSQ+MYiAI2ltomkzttUb0gGHdSUUgsIYjTzLG3mObX4FBRaYtpDVNZrih9TgTeYOBxsEnN1gOCTM8Bsw/ieMc75w9kuAT6A+/AiHGvN/+Gn4KRkiuzpNNDYhDGFndWRpE6SVfm8U5bxnSgVV2jrg6JCKmneqey8VMFgq2+AM/i4L4RUbfSi27lNXZ7R7W9RTcq/q9fk4Xw3AMQd4I5ifAZz8FcVtm9SAom/dyN4lczJQW/kC42ZrHgcCoIf1oVMKkVItmMBi9cOeNHGLqOZk+QqQmrbc5YmYgxELUUN35z2iohstgfLIFmcMV7s4CFmI74L9+EFmGsi+tGnAOD4Yk9gIpo01Y4cA43BWGygMdr4YZekG3OBIUXXNukvJS8tqa06e+lSDCtnqqMFu6hWHXCF+WaYt64m9QBmNxi7Ioy7D+fa1yHw+FMAcPt7SysFLtoG4PXAk7JOA3aAxBRqUiAdU9Yp5lK3HLSRFtOim0sa8euEt08xvKjYjzeJ2GU7YawexrnKI9tmobInjFXCewpwriY9+RR4aaezFhMhGCppKwom0ChrgFlKzyPKkGlTW1YQrE9HJqu8hKGgMc6hVi5QRq0PZxNfrYNgE64utmRv6KKHRpxf6VDUaOvNP5jCEx5q185My/7RKz69UQu2im5k4/eownpxZxNLwiZ1AZTO2ZjWjkU9uaB2HFn6Q3u0JcsSx/qV9hTEApRzeBLDJQXxYmTnq7bdLa3+uqFrxLJ5w1TehnNHx5ECvCh2g2c3hHH5YsfdaSKddztfjQ6imKFGSyFwlLzxEGPp6r5IevVjk1AMx3wMqi1NxDVjLBiPs9tbsCkIY5we5/ML22zrCScFxnNtzsr9Wcc3CnD+pYO+4VXXiDE0oc/vQQ/fDK3oPESJMYXNmJa/DuloJZkcTpcYE8lIH8Dz8DJMiynNC86Mb2lNaaqP/+L7f2fcE/yP7/Lde8xfgSOdMxvOixZf/9p3+M4hT1+F+zApxg9XfUvYjc8qX2lfOOpK2gNRtB4flpFu9FTKCp2XJRgXnX6olp1zyYjTKJSkGmLE2NjUr1bxFM4AeAAHBUFIeSLqXR+NvH/M9fOnfHzOD2vCSyQJKzfgsCh+yi/Mmc35F2fUrw7miW33W9hBD1vpuUojFphIyvg7aTeoymDkIkeW3XLHmguMzbIAJejN6B5MDrhipE2y6SoFRO/AK/AcHHZHNIfiWrEe/C6cr3f/yOvrQKB+zMM55/GQdLDsR+ifr5Fiuu+/y+M78LzOE5dsNuXC3PYvYWd8NXvphLSkJIasrlD2/HOqQ+RjcRdjKTGWYhhVUm4yxlyiGPuMsZR7sMCHUBeTuNWA7if+ifXgc/hovftHXs/DV+Fvwe+f8shzMiMcweFgBly3//vwJfg5AN4450fn1Hd1Rm1aBLu22Dy3y3H2+OqMemkbGZ4jozcDjJf6596xOLpC0eMTHbKnxLxH27uZ/bMTGs2jOaMOY4m87CfQwF0dw53oa1k80JRuz/XgS+8fX3N9Af4qPIMfzKgCp4H5TDGe9GGeFPzSsZz80SlPTxXjgwJmC45njzgt2vbQ4b4OAdUK4/vWhO8d8v6EE8fMUsfakXbPpFJeLs2ubM/qdm/la3WP91uWhxXHjoWhyRUq2iJ/+5mA73zwIIo+LoZ/SgvIRjAd1IMvvn98PfgOvAJfhhm8scAKVWDuaRaK8aQ9f7vuPDH6Bj47ZXau7rqYJ66mTDwEDU6lLbCjCK0qTXyl5mnDoeNRxanj3FJbaksTk0faXxHxLrssgPkWB9LnA/MFleXcJozzjwsUvUG0X/QCve51qkMDXp9mtcyOy3rwBfdvVJK7D6/ACSzg3RoruIq5UDeESfEmVclDxnniU82vxMLtceD0hGZWzBNPMM/jSPne2OVatiTKUpY5vY7gc0LdUAWeWM5tH+O2I66AOWw9xT2BuyRVLGdoDHUsVRXOo/c+ZdRXvFfnxWyIV4upFLCl9eAL7h8Zv0QH8Ry8pA2cHzQpGesctVA37ZtklBTgHjyvdSeKY/RZw/kJMk0Y25cSNRWSigQtlULPTw+kzuJPeYEkXjQRpoGZobYsLF79pyd1dMRHInbgFTZqNLhDqiIsTNpoex2WLcy0/X6rHcdMMQvFSd5dWA++4P7xv89deACnmr36uGlL69bRCL6BSZsS6c0TU2TKK5gtWCzgAOOwQcurqk9j8whvziZSMLcq5hbuwBEsYjopUBkqw1yYBGpLA97SRElEmx5MCInBY5vgLk94iKqSWmhIGmkJ4Bi9m4L645J68LyY4wsFYBfUg5feP/6gWWm58IEmKQM89hq7KsZNaKtP5TxxrUZZVkNmMJtjbKrGxLNEbHPJxhqy7lAmbC32ZqeF6lTaknRWcYaFpfLUBh/rwaQycCCJmW15Kstv6jRHyJFry2C1ahkkIW0LO75s61+owxK1y3XqweX9m5YLM2DPFeOjn/iiqCKJ+yKXF8t5Yl/kNsqaSCryxPq5xWTFIaP8KSW0RYxqupaUf0RcTNSSdJZGcKYdYA6kdtrtmyBckfKXwqk0pHpUHlwWaffjNRBYFPUDWa8e3Lt/o0R0CdisKDM89cX0pvRHEfM8ca4t0s2Xx4kgo91MPQJ/0c9MQYq0co8MBh7bz1fio0UUHLR4aAIOvOmoYO6kwlEVODSSTliWtOtH6sPkrtctF9ZtJ9GIerBskvhdVS5cFNv9s1BU0AbdUgdK4FG+dRnjFmDTzniRMdZO1QhzMK355vigbdkpz9P6qjUGE5J2qAcXmwJ20cZUiAD0z+pGMx6xkzJkmEf40Hr4qZfVg2XzF9YOyoV5BjzVkUJngKf8lgNYwKECEHrCNDrWZzMlflS3yBhr/InyoUgBc/lKT4pxVrrC6g1YwcceK3BmNxZcAtz3j5EIpqguh9H6wc011YN75cKDLpFDxuwkrPQmUwW4KTbj9mZTwBwLq4aQMUZbHm1rylJ46dzR0dua2n3RYCWZsiHROeywyJGR7mXKlpryyCiouY56sFkBWEnkEB/raeh/Sw4162KeuAxMQpEkzy5alMY5wamMsWKKrtW2WpEWNnReZWONKWjrdsKZarpFjqCslq773PLmEhM448Pc3+FKr1+94vv/rfw4tEcu+lKTBe4kZSdijBrykwv9vbCMPcLQTygBjzVckSLPRVGslqdunwJ4oegtFOYb4SwxNgWLCmD7T9kVjTv5YDgpo0XBmN34Z/rEHp0sgyz7lngsrm4lvMm2Mr1zNOJYJ5cuxuQxwMGJq/TP5emlb8fsQBZviK4t8hFL+zbhtlpwaRSxQRWfeETjuauPsdGxsBVdO7nmP4xvzSoT29pRl7kGqz+k26B3Oy0YNV+SXbbQas1ctC/GarskRdFpKczVAF1ZXnLcpaMuzVe6lZ2g/1ndcvOVgRG3sdUAY1bKD6achijMPdMxV4muKVorSpiDHituH7rSTs7n/4y5DhRXo4FVBN4vO/zbAcxhENzGbHCzU/98Mcx5e7a31kWjw9FCe/zNeYyQjZsWb1uc7U33pN4Mji6hCLhivqfa9Ss6xLg031AgfesA/l99m9fgvnaF9JoE6bYKmkGNK3aPbHB96w3+DnxFm4hs0drLsk7U8kf/N/CvwQNtllna0rjq61sH8L80HAuvwH1tvBy2ChqWSCaYTaGN19sTvlfzFD6n+iKTbvtayfrfe9ueWh6GJFoxLdr7V72a5ZpvHcCPDzma0wTO4EgbLyedxstO81n57LYBOBzyfsOhUKsW1J1BB5vr/tz8RyqOFylQP9Tvst2JALsC5lsH8PyQ40DV4ANzYa4dedNiKNR1s+x2wwbR7q4/4cTxqEk4LWDebfisuo36JXLiWFjOtLrlNWh3K1rRS4xvHcDNlFnNmWBBAl5SWaL3oPOfnvbr5pdjVnEaeBJSYjuLEkyLLsWhKccadmOphZkOPgVdalj2QpSmfOsADhMWE2ZBu4+EEJI4wKTAuCoC4xwQbWXBltpxbjkXJtKxxabo9e7tyhlgb6gNlSbUpMh+l/FaqzVwewGu8BW1Zx7pTpQDJUjb8tsUTW6+GDXbMn3mLbXlXJiGdggxFAoUrtPS3wE4Nk02UZG2OOzlk7fRs7i95QCLo3E0jtrjnM7SR3uS1p4qtS2nJ5OwtQVHgOvArLBFijZUV9QtSl8dAY5d0E0hM0w3HS2DpIeB6m/A1+HfhJcGUq4sOxH+x3f5+VO+Ds9rYNI7zPXOYWPrtf8bYMx6fuOAX5jzNR0PdsuON+X1f7EERxMJJoU6GkTEWBvVolVlb5lh3tKCg6Wx1IbaMDdJ+9sUCc5KC46hKGCk3IVOS4TCqdBNfUs7Kd4iXf2RjnT/LLysJy3XDcHLh/vde3x8DoGvwgsa67vBk91G5Pe/HbOe7xwym0NXbtiuuDkGO2IJDh9oQvJ4cY4vdoqLDuoH9Zl2F/ofsekn8lkuhIlhQcffUtSjytFyp++p6NiE7Rqx/lodgKVoceEp/CP4FfjrquZaTtj2AvH5K/ywpn7M34K/SsoYDAdIN448I1/0/wveW289T1/lX5xBzc8N5IaHr0XMOQdHsIkDuJFifj20pBm5jzwUv9e2FhwRsvhAbalCIuIw3bhJihY3p6nTFFIZgiSYjfTf3aXuOjmeGn4bPoGvwl+CFzTRczBIuHBEeImHc37/lGfwZR0cXzVDOvaKfNHvwe+suZ771K/y/XcBlsoN996JpBhoE2toYxOznNEOS5TJc6Id5GEXLjrWo+LEWGNpPDU4WAwsIRROu+1vM+0oW37z/MBN9kqHnSArwPfgFJ7Cq/Ai3Ie7g7ncmI09v8sjzw9mzOAEXoIHxURueaAce5V80f/DOuuZwHM8vsMb5wBzOFWM7wymTXPAEvm4vcFpZ2ut0VZRjkiP2MlmLd6DIpbGSiHOjdnUHN90hRYmhTnmvhzp1iKDNj+b7t5hi79lWGwQ+HN9RsfFMy0FXbEwhfuczKgCbyxYwBmcFhhvo/7a44v+i3XWcwDP86PzpGQYdWh7csP5dBvZ1jNzdxC8pBGuxqSW5vw40nBpj5JhMwvOzN0RWqERHMr4Lv1kWX84xLR830G3j6yqZ1a8UstTlW+qJPOZ+sZ7xZPKTJLhiNOAFd6tk+jrTH31ncLOxid8+nzRb128HhUcru/y0Wn6iT254YPC6FtVSIMoW2sk727AhvTtrWKZTvgsmckfXYZWeNRXx/3YQ2OUxLDrbHtN11IwrgXT6c8dATDwLniYwxzO4RzuQqTKSC5gAofMZ1QBK3zQ4JWobFbcvJm87FK+6JXrKahLn54m3p+McXzzYtP8VF/QpJuh1OwieElEoI1pRxPS09FBrkq2tWCU59+HdhNtTIqKm8EBrw2RTOEDpG3IKo2Y7mFdLm3ZeVjYwVw11o/oznceMve4CgMfNym/utA/d/ILMR7gpXzRy9eDsgLcgbs8O2Va1L0zzIdwGGemTBuwROHeoMShkUc7P+ISY3KH5ZZeWqO8mFTxQYeXTNuzvvK5FGPdQfuu00DwYFY9dyhctEt+OJDdnucfpmyhzUJzfsJjr29l8S0bXBfwRS9ZT26tmMIdZucch5ZboMz3Nio3nIOsYHCGoDT4kUA9MiXEp9Xsui1S8th/kbWIrMBxDGLodWUQIWcvnXy+9M23xPiSMOiRPqM+YMXkUN3gXFrZJwXGzUaMpJfyRS9ZT0lPe8TpScuRlbMHeUmlaKDoNuy62iWNTWNFYjoxFzuJs8oR+RhRx7O4SVNSXpa0ZJQ0K1LAHDQ+D9IepkMXpcsq5EVCvClBUIzDhDoyKwDw1Lc59GbTeORivugw1IcuaEOaGWdNm+Ps5fQ7/tm0DjMegq3yM3vb5j12qUId5UZD2oxDSEWOZMSqFl/W+5oynWDa/aI04tJRQ2eTXusg86SQVu/nwSYwpW6wLjlqIzwLuxGIvoAvul0PS+ZNz0/akp/pniO/8JDnGyaCkzbhl6YcqmK/69prxPqtpx2+Km9al9sjL+rwMgHw4jE/C8/HQ3m1vBuL1fldbzd8mOueVJ92syqdEY4KJjSCde3mcRw2TA6szxedn+zwhZMps0XrqEsiUjnC1hw0TELC2Ek7uAAdzcheXv1BYLagspxpzSAoZZUsIzIq35MnFQ9DOrlNB30jq3L4pkhccKUAA8/ocvN1Rzx9QyOtERs4CVsJRK/DF71kPYrxYsGsm6RMh4cps5g1DOmM54Ly1ii0Hd3Y/BMk8VWFgBVmhqrkJCPBHAolwZaWzLR9Vb7bcWdX9NyUYE+uB2BKfuaeBUcjDljbYVY4DdtsVWvzRZdWnyUzDpjNl1Du3aloAjVJTNDpcIOVVhrHFF66lLfJL1zJr9PQ2nFJSBaKoDe+sAvLufZVHVzYh7W0h/c6AAZ+7Tvj6q9j68G/cTCS/3n1vLKHZwNi+P+pS0WkZNMBMUl+LDLuiE4omZy71r3UFMwNJV+VJ/GC5ixVUkBStsT4gGKh0Gm4Oy3qvq7Lbmq24nPdDuDR9deR11XzP4vFu3TYzfnIyiSVmgizUYGqkIXNdKTY9pgb9D2Ix5t0+NHkVzCdU03suWkkVZAoCONCn0T35gAeW38de43mf97sMOpSvj4aa1KYUm58USI7Wxxes03bAZdRzk6UtbzMaCQ6IxO0dy7X+XsjoD16hpsBeGz9dfzHj+R/Hp8nCxZRqkEDTaCKCSywjiaoMJ1TITE9eg7Jqnq8HL6gDwiZb0u0V0Rr/rmvqjxKuaLCX7ZWXTvAY+uvm3z8CP7nzVpngqrJpZKwWnCUjIviYVlirlGOzPLI3SMVyp/elvBUjjDkNhrtufFFErQ8pmdSlbK16toBHlt/HV8uHMX/vEGALkV3RJREiSlopxwdMXOZPLZ+ix+kAHpMKIk8UtE1ygtquttwxNhphrIZ1IBzjGF3IIGxGcBj6q8bHJBG8T9vdsoWrTFEuebEZuVxhhClH6P5Zo89OG9fwHNjtNQTpD0TG9PJLEYqvEY6Rlxy+ZZGfL0Aj62/bnQCXp//eeM4KzfQVJbgMQbUjlMFIm6TpcfWlZje7NBSV6IsEVmumWIbjiloUzQX9OzYdo8L1wjw2PrrpimONfmfNyzKklrgnEkSzT5QWYQW40YShyzqsRmMXbvVxKtGuYyMKaU1ugenLDm5Ily4iT14fP11Mx+xJv+zZ3MvnfdFqxU3a1W/FTB4m3Qfsyc1XUcdVhDeUDZXSFHHLQj/Y5jtC7ZqM0CXGwB4bP11i3LhOvzPGygYtiUBiwQV/4wFO0majijGsafHyRLu0yG6q35cL1rOpVxr2s5cM2jJYMCdc10Aj6q/blRpWJ//+dmm5psMl0KA2+AFRx9jMe2WbC4jQxnikd4DU8TwUjRVacgdlhmr3bpddzuJ9zXqr2xnxJfzP29RexdtjDVZqzkqa6PyvcojGrfkXiJ8SEtml/nYskicv0ivlxbqjemwUjMw5evdg8fUX9nOiC/lf94Q2i7MURk9nW1MSj5j8eAyV6y5CN2S6qbnw3vdA1Iwq+XOSCl663udN3IzLnrt+us25cI1+Z83SXQUldqQq0b5XOT17bGpLd6ssN1VMPf8c+jG8L3NeCnMdF+Ra3fRa9dft39/LuZ/3vwHoHrqGmQFafmiQw6eyzMxS05K4bL9uA+SKUQzCnSDkqOGokXyJvbgJ/BHI+qvY69//4rl20NsmK2ou2dTsyIALv/91/8n3P2Aao71WFGi8KKv1fRC5+J67Q/507/E/SOshqN5TsmYIjVt+kcjAx98iz/4SaojbIV1rexE7/C29HcYD/DX4a0rBOF5VTu7omsb11L/AWcVlcVZHSsqGuXLLp9ha8I//w3Mv+T4Ew7nTBsmgapoCrNFObIcN4pf/Ob/mrvHTGqqgAupL8qWjWPS9m/31jAe4DjA+4+uCoQoT/zOzlrNd3qd4SdphFxsUvYwGWbTWtISc3wNOWH+kHBMfc6kpmpwPgHWwqaSUG2ZWWheYOGQGaHB+eQ/kn6b3pOgLV+ODSn94wDvr8Bvb70/LLuiPPEr8OGVWfDmr45PZyccEmsVXZGe1pRNX9SU5+AVQkNTIVPCHF/jGmyDC9j4R9LfWcQvfiETmgMMUCMN1uNCakkweZsowdYobiMSlnKA93u7NzTXlSfe+SVbfnPQXmg9LpYAQxpwEtONyEyaueWM4FPjjyjG3uOaFmBTWDNgBXGEiQpsaWhnAqIijB07Dlsy3fUGeP989xbWkyf+FF2SNEtT1E0f4DYYVlxFlbaSMPIRMk/3iMU5pME2SIWJvjckciebkQuIRRyhUvkHg/iUljG5kzVog5hV7vIlCuBrmlhvgPfNHQM8lCf+FEGsYbMIBC0qC9a0uuy2wLXVbLBaP5kjHokCRxapkQyzI4QEcwgYHRZBp+XEFTqXFuNVzMtjXLJgX4gAid24Hjwc4N3dtVSe+NNiwTrzH4WVUOlDobUqr1FuAgYllc8pmzoVrELRHSIW8ViPxNy4xwjBpyR55I6J220qQTZYR4guvUICJiSpr9gFFle4RcF/OMB7BRiX8sSfhpNSO3lvEZCQfLUVTKT78Ek1LRLhWN+yLyTnp8qWUZ46b6vxdRGXfHVqx3eI75YaLa4iNNiK4NOW7wPW6lhbSOF9/M9qw8e/aoB3d156qTzxp8pXx5BKAsYSTOIIiPkp68GmTq7sZtvyzBQaRLNxIZ+paozHWoLFeExIhRBrWitHCAHrCF7/thhD8JhYz84wg93QRV88wLuLY8zF8sQ36qF1J455bOlgnELfshKVxYOXKVuKx0jaj22sczTQqPqtV/XDgpswmGTWWMSDw3ssyUunLLrVPGjYRsH5ggHeHSWiV8kT33ycFSfMgkoOK8apCye0J6VW6GOYvffgU9RWsukEi2kUV2nl4dOYUzRik9p7bcA4ggdJ53LxKcEe17B1R8eqAd7dOepV8sTXf5lhejoL85hUdhDdknPtKHFhljOT+bdq0hxbm35p2nc8+Ja1Iw+tJykgp0EWuAAZYwMVwac5KzYMslhvgHdHRrxKnvhTYcfKsxTxtTETkjHO7rr3zjoV25lAQHrqpV7bTiy2aXMmUhTBnKS91jhtR3GEoF0oLnWhWNnYgtcc4N0FxlcgT7yz3TgNIKkscx9jtV1ZKpWW+Ub1tc1eOv5ucdgpx+FJy9pgbLE7xDyXb/f+hLHVGeitHOi6A7ybo3sF8sS7w7cgdk0nJaOn3hLj3uyD0Zp5pazFIUXUpuTTU18d1EPkDoX8SkmWTnVIozEdbTcZjoqxhNHf1JrSS/AcvHjZ/SMHhL/7i5z+POsTUh/8BvNfYMTA8n+yU/MlTZxSJDRStqvEuLQKWwDctMTQogUDyQRoTQG5Kc6oQRE1yV1jCA7ri7jdZyK0sYTRjCR0Hnnd+y7nHxNgTULqw+8wj0mQKxpYvhjm9uSUxg+TTy7s2GtLUGcywhXSKZN275GsqlclX90J6bRI1aouxmgL7Q0Nen5ziM80SqMIo8cSOo+8XplT/5DHNWsSUr/6lLN/QQ3rDyzLruEW5enpf7KqZoShEduuSFOV7DLX7Ye+GmXb6/hnNNqKsVXuMDFpb9Y9eH3C6NGEzuOuI3gpMH/I6e+zDiH1fXi15t3vA1czsLws0TGEtmPEJdiiFPwlwKbgLHAFk4P6ZyPdymYYHGE0dutsChQBl2JcBFlrEkY/N5bQeXQ18gjunuMfMfsBlxJSx3niO485fwO4fGD5T/+3fPQqkneWVdwnw/3bMPkW9Wbqg+iC765Zk+xcT98ibKZc2EdgHcLoF8cSOo/Oc8fS+OyEULF4g4sJqXVcmfMfsc7A8v1/yfGXmL9I6Fn5pRwZhsPv0TxFNlAfZCvG+Oohi82UC5f/2IsJo0cTOm9YrDoKhFPEUr/LBYTUNht9zelHXDqwfPCIw4owp3mOcIQcLttWXFe3VZ/j5H3cIc0G6oPbCR+6Y2xF2EC5cGUm6wKC5tGEzhsWqw5hNidUiKX5gFWE1GXh4/Qplw4sVzOmx9QxU78g3EF6wnZlEN4FzJ1QPSLEZz1KfXC7vd8ssGdIbNUYpVx4UapyFUHzJoTOo1McSkeNn1M5MDQfs4qQuhhX5vQZFw8suwWTcyYTgioISk2YdmkhehG4PkE7w51inyAGGaU+uCXADabGzJR1fn3lwkty0asIo8cROm9Vy1g0yDxxtPvHDAmpu+PKnM8Ix1wwsGw91YJqhteaWgjYBmmQiebmSpwKKzE19hx7jkzSWOm66oPbzZ8Yj6kxVSpYjVAuvLzYMCRo3oTQecOOjjgi3NQ4l9K5/hOGhNTdcWVOTrlgYNkEXINbpCkBRyqhp+LdRB3g0OU6rMfW2HPCFFMV9nSp+uB2woepdbLBuJQyaw/ZFysXrlXwHxI0b0LovEkiOpXGA1Ijagf+KUNC6rKNa9bQnLFqYNkEnMc1uJrg2u64ELPBHpkgWbmwKpJoDhMwNbbGzAp7Yg31wS2T5rGtzit59PrKhesWG550CZpHEzpv2NGRaxlNjbMqpmEIzygJqQfjypycs2pg2cS2RY9r8HUqkqdEgKTWtWTKoRvOBPDYBltja2SO0RGjy9UHtxwRjA11ujbKF+ti5cIR9eCnxUg6owidtyoU5tK4NLji5Q3HCtiyF2IqLGYsHViOXTXOYxucDqG0HyttqYAKqYo3KTY1ekyDXRAm2AWh9JmsVh/ccg9WJ2E8YjG201sPq5ULxxX8n3XLXuMInbft2mk80rRGjCGctJ8/GFdmEQ9Ug4FlE1ll1Y7jtiraqm5Fe04VV8lvSVBL8hiPrfFVd8+7QH3Qbu2ipTVi8cvSGivc9cj8yvH11YMHdNSERtuOslM97feYFOPKzGcsI4zW0YGAbTAOaxCnxdfiYUmVWslxiIblCeAYr9VYR1gM7GmoPrilunSxxeT3DN/2eBQ9H11+nk1adn6VK71+5+Jfct4/el10/7KBZfNryUunWSCPxPECk1rdOv1WVSrQmpC+Tl46YD3ikQYcpunSQgzVB2VHFhxHVGKDgMEY5GLlQnP7FMDzw7IacAWnO6sBr12u+XanW2AO0wQ8pknnFhsL7KYIqhkEPmEXFkwaN5KQphbkUmG72wgw7WSm9RiL9QT925hkjiVIIhphFS9HKI6/8QAjlpXqg9W2C0apyaVDwKQwrwLY3j6ADR13ZyUNByQXHQu6RY09Hu6zMqXRaNZGS/KEJs0cJEe9VH1QdvBSJv9h09eiRmy0V2uJcqHcShcdvbSNg5fxkenkVprXM9rDVnX24/y9MVtncvbKY706anNl3ASll9a43UiacVquXGhvq4s2FP62NGKfQLIQYu9q1WmdMfmUrDGt8eDS0cXozH/fjmUH6Jruvm50hBDSaEU/2Ru2LEN/dl006TSc/g7tfJERxGMsgDUEr104pfWH9lQaN+M4KWQjwZbVc2rZVNHsyHal23wZtIs2JJqtIc/WLXXRFCpJkfE9jvWlfFbsNQ9pP5ZBS0zKh4R0aMFj1IjTcTnvi0Zz2rt7NdvQb2mgbju1plsH8MmbnEk7KbK0b+wC2iy3aX3szW8xeZvDwET6hWZYwqTXSSG+wMETKum0Dq/q+x62gt2ua2ppAo309TRk9TPazfV3qL9H8z7uhGqGqxNVg/FKx0HBl9OVUORn8Q8Jx9gFttGQUDr3tzcXX9xGgN0EpzN9mdZ3GATtPhL+CjxFDmkeEU6x56kqZRusLzALXVqkCN7zMEcqwjmywDQ6OhyUe0Xao1Qpyncrg6wKp9XfWDsaZplElvQ/b3sdweeghorwBDlHzgk1JmMc/wiERICVy2VJFdMjFuLQSp3S0W3+sngt2njwNgLssFGVQdJ0tu0KH4ky1LW4yrbkuaA6Iy9oz/qEMMXMMDWyIHhsAyFZc2peV9hc7kiKvfULxCl9iddfRK1f8kk9qvbdOoBtOg7ZkOZ5MsGrSHsokgLXUp9y88smniwWyuFSIRVmjplga3yD8Uij5QS1ZiM4U3Qw5QlSm2bXjFe6jzzBFtpg+/YBbLAWG7OPynNjlCw65fukGNdkJRf7yM1fOxVzbxOJVocFoYIaGwH22mIQkrvu1E2nGuebxIgW9U9TSiukPGU+Lt++c3DJPKhyhEEbXCQLUpae2exiKy6tMPe9mDRBFCEMTWrtwxN8qvuGnt6MoihKWS5NSyBhbH8StXoAz8PLOrRgLtOT/+4vcu+7vDLnqNvztOq7fmd8sMmY9Xzn1zj8Dq8+XVdu2Nv0IIySgEdQo3xVHps3Q5i3fLFsV4aiqzAiBhbgMDEd1uh8qZZ+lwhjkgokkOIv4xNJmyncdfUUzgB4oFMBtiu71Xumpz/P+cfUP+SlwFExwWW62r7b+LSPxqxn/gvMZ5z9C16t15UbNlq+jbGJtco7p8wbYlL4alSyfWdeuu0j7JA3JFNuVAwtst7F7FhWBbPFNKIUORndWtLraFLmMu7KFVDDOzqkeaiN33YAW/r76wR4XDN/yN1z7hejPau06EddkS/6XThfcz1fI/4K736fO48vlxt2PXJYFaeUkFS8U15XE3428xdtn2kc8GQlf1vkIaNRRnOMvLTWrZbElEHeLWi1o0dlKPAh1MVgbbVquPJ5+Cr8LU5/H/+I2QlHIU2ClXM9G8v7Rr7oc/hozfUUgsPnb3D+I+7WF8kNO92GY0SNvuxiE+2Bt8prVJTkzE64sfOstxuwfxUUoyk8VjcTlsqe2qITSFoSj6Epd4KsT6BZOWmtgE3hBfir8IzZDwgV4ZTZvD8VvPHERo8v+vL1DASHTz/i9OlKueHDjK5Rnx/JB1Vb1ioXdBra16dmt7dgik10yA/FwJSVY6XjA3oy4SqM2frqDPPSRMex9qs3XQtoWxMj7/Er8GWYsXgjaVz4OYumP2+9kbxvny/6kvWsEBw+fcb5bInc8APdhpOSs01tEqIkoiZjbAqKMruLbJYddHuHFRIyJcbdEdbl2sVLaySygunutBg96Y2/JjKRCdyHV+AEFtTvIpbKIXOamknYSiB6KV/0JetZITgcjjk5ZdaskBtWO86UF0ap6ozGXJk2WNiRUlCPFir66lzdm/SLSuK7EUdPz8f1z29Skq6F1fXg8+5UVR6bszncP4Tn4KUkkdJ8UFCY1zR1i8RmL/qQL3rlei4THG7OODlnKko4oI01kd3CaM08Ia18kC3GNoVaO9iDh+hWxSyTXFABXoau7Q6q9OxYg/OVEMw6jdbtSrJ9cBcewGmaZmg+bvkUnUUaGr+ZfnMH45Ivevl61hMcXsxYLFTu1hTm2zViCp7u0o5l+2PSUh9bDj6FgYypufBDhqK2+oXkiuHFHR3zfj+9PtA8oR0xnqX8qn+sx3bFODSbbF0X8EUvWQ8jBIcjo5bRmLOljDNtcqNtOe756h3l0VhKa9hDd2l1eqmsnh0MNMT/Cqnx6BInumhLT8luljzQ53RiJeA/0dxe5NK0o2fA1+GLXr6eNQWHNUOJssQaTRlGpLHKL9fD+IrQzTOMZS9fNQD4AnRNVxvTdjC+fJdcDDWQcyB00B0t9BDwTxXgaAfzDZ/DBXzRnfWMFRwuNqocOmX6OKNkY63h5n/fFcB28McVHqnXZVI27K0i4rDLNE9lDKV/rT+udVbD8dFFu2GGZ8mOt0kAXcoX3ZkIWVtw+MNf5NjR2FbivROHmhV1/pj2egv/fMGIOWTIWrV3Av8N9imV9IWml36H6cUjqEWNv9aNc+veb2sH46PRaHSuMBxvtW+twxctq0z+QsHhux8Q7rCY4Ct8lqsx7c6Sy0dl5T89rIeEuZKoVctIk1hNpfavER6yyH1Vvm3MbsUHy4ab4hWr/OZPcsRBphnaV65/ZcdYPNNwsjN/djlf9NqCw9U5ExCPcdhKxUgLSmfROpLp4WSUr8ojdwbncbvCf+a/YzRaEc6QOvXcGO256TXc5Lab9POvB+AWY7PigWYjzhifbovuunzRawsO24ZqQQAqguBtmpmPB7ysXJfyDDaV/aPGillgz1MdQg4u5MYaEtBNNHFjkRlSpd65lp4hd2AVPTfbV7FGpyIOfmNc/XVsPfg7vzaS/3nkvLL593ANLvMuRMGpQIhiF7kUEW9QDpAUbTWYBcbp4WpacHHY1aacqQyjGZS9HI3yCBT9kUZJhVOD+zUDvEH9ddR11fzPcTDQ5TlgB0KwqdXSavk9BC0pKp0WmcuowSw07VXmXC5guzSa4p0UvRw2lbDiYUx0ExJJRzWzi6Gm8cnEkfXXsdcG/M/jAJa0+bmCgdmQ9CYlNlSYZOKixmRsgiFxkrmW4l3KdFKv1DM8tk6WxPYJZhUUzcd8Kdtgrw/gkfXXDT7+avmfVak32qhtkg6NVdUS5wgkru1YzIkSduTW1FDwVWV3JQVJVuieTc0y4iDpFwc7/BvSalvKdQM8sv662cevz/+8sQVnjVAT0W2wLllw1JiMhJRxgDjCjLQsOzSFSgZqx7lAW1JW0e03yAD3asC+GD3NbQhbe+mN5GXH1F83KDOM4n/e5JIuH4NpdQARrFPBVptUNcjj4cVMcFSRTE2NpR1LEYbYMmfWpXgP9KejaPsLUhuvLCsVXznAG9dfx9SR1ud/3hZdCLHb1GMdPqRJgqDmm76mHbvOXDtiO2QPUcKo/TWkQ0i2JFXpBoo7vij1i1Lp3ADAo+qvG3V0rM//vFnnTE4hxd5Ka/Cor5YEdsLVJyKtDgVoHgtW11pWSjolPNMnrlrVj9Fv2Qn60twMwKPqr+N/wvr8z5tZcDsDrv06tkqyzESM85Ycv6XBWA2birlNCXrI6VbD2lx2L0vQO0QVTVVLH4SE67fgsfVXv8n7sz7/85Z7cMtbE6f088wSaR4kCkCm10s6pKbJhfqiUNGLq+0gLWC6eUAZFPnLjwqtKd8EwGvWX59t7iPW4X/eAN1svgRVSY990YZg06BD1ohLMtyFTI4pKTJsS9xREq9EOaPWiO2gpms7397x6nQJkbh+Fz2q/rqRROX6/M8bJrqlVW4l6JEptKeUFuMYUbtCQ7CIttpGc6MY93x1r1vgAnRXvY5cvwWPqb9uWQm+lP95QxdNMeWhOq1x0Db55C7GcUv2ZUuN6n8iKzsvOxibC//Yfs9Na8r2Rlz02vXXDT57FP/zJi66/EJSmsJKa8QxnoqW3VLQ+jZVUtJwJ8PNX1NQCwfNgdhhHD9on7PdRdrdGPF28rJr1F+3LBdeyv+8yYfLoMYet1vX4upNAjVvwOUWnlNXJXlkzk5Il6kqeoiL0C07qno+/CYBXq/+utlnsz7/Mzvy0tmI4zm4ag23PRN3t/CWryoUVJGm+5+K8RJ0V8Hc88/XHUX/HfiAq7t+BH+x6v8t438enWmdJwFA6ZINriLGKv/95f8lT9/FnyA1NMVEvQyaXuu+gz36f/DD73E4pwqpLcvm/o0Vle78n//+L/NPvoefp1pTJye6e4A/D082FERa5/opeH9zpvh13cNm19/4v/LDe5xMWTi8I0Ta0qKlK27AS/v3/r+/x/2GO9K2c7kVMonDpq7//jc5PKCxeNPpFVzaRr01wF8C4Pu76hXuX18H4LduTr79guuFD3n5BHfI+ZRFhY8w29TYhbbLi/bvBdqKE4fUgg1pBKnV3FEaCWOWyA+m3WpORZr/j+9TKJtW8yBTF2/ZEODI9/QavHkVdGFp/Pjn4Q+u5hXapsP5sOH+OXXA1LiKuqJxiMNbhTkbdJTCy4llEt6NnqRT4dhg1V3nbdrm6dYMecA1yTOL4PWTE9L5VzPFlLBCvlG58AhehnN4uHsAYinyJ+AZ/NkVvELbfOBUuOO5syBIEtiqHU1k9XeISX5bsimrkUUhnGDxourN8SgUsCZVtKyGbyGzHXdjOhsAvOAswSRyIBddRdEZWP6GZhNK/yjwew9ehBo+3jEADu7Ay2n8mDc+TS7awUHg0OMzR0LABhqLD4hJEh/BEGyBdGlSJoXYXtr+3HS4ijzVpgi0paWXtdruGTknXBz+11qT1Q2inxaTzQCO46P3lfLpyS4fou2PH/PupwZgCxNhGlj4IvUuWEsTkqMWm6i4xCSMc9N1RDQoCVcuGItJ/MRWefais+3synowi/dESgJjkilnWnBTGvRWmaw8oR15257t7CHmCf8HOn7cwI8+NQBXMBEmAa8PMRemrNCEhLGEhDQKcGZWS319BX9PFBEwGTbRBhLbDcaV3drFcDqk5kCTd2JF1Wp0HraqBx8U0wwBTnbpCadwBA/gTH/CDrcCs93LV8E0YlmmcyQRQnjBa8JESmGUfIjK/7fkaDJpmD2QptFNVJU1bbtIAjjWQizepOKptRjbzR9Kag6xZmMLLjHOtcLT3Tx9o/0EcTT1XN3E45u24AiwEypDJXihKjQxjLprEwcmRKclaDNZCVqr/V8mYWyFADbusiY5hvgFoU2vio49RgJLn5OsReRFN6tabeetiiy0V7KFHT3HyZLx491u95sn4K1QQSPKM9hNT0wMVvAWbzDSVdrKw4zRjZMyJIHkfq1VAVCDl/bUhNKlGq0zGr05+YAceXVPCttVk0oqjVwMPt+BBefx4yPtGVkUsqY3CHDPiCM5ngupUwCdbkpd8kbPrCWHhkmtIKLEetF2499eS1jZlIPGYnlcPXeM2KD9vLS0bW3ktYNqUllpKLn5ZrsxlIzxvDu5eHxzGLctkZLEY4PgSOg2IUVVcUONzUDBEpRaMoXNmUc0tFZrTZquiLyKxrSm3DvIW9Fil+AkhXu5PhEPx9mUNwqypDvZWdKlhIJQY7vn2OsnmBeOWnYZ0m1iwbbw1U60by5om47iHRV6fOgzjMf/DAZrlP40Z7syxpLK0lJ0gqaAK1c2KQKu7tabTXkLFz0sCftuwX++MyNeNn68k5Buq23YQhUh0SNTJa1ioQ0p4nUG2y0XilF1JqODqdImloPS4Bp111DEWT0jJjVv95uX9BBV7eB3bUWcu0acSVM23YZdd8R8UbQUxJ9wdu3oMuhdt929ME+mh6JXJ8di2RxbTi6TbrDquqV4aUKR2iwT6aZbyOwEXN3DUsWr8Hn4EhwNyHuXHh7/pdaUjtR7vnDh/d8c9xD/s5f501eQ1+CuDiCvGhk1AN/4Tf74RfxPwD3toLarR0zNtsnPzmS64KIRk861dMWCU8ArasG9T9H0ZBpsDGnjtAOM2+/LuIb2iIUGXNgl5ZmKD/Tw8TlaAuihaFP5yrw18v4x1898zIdP+DDAX1bM3GAMvPgRP/cJn3zCW013nrhHkrITyvYuwOUkcHuKlRSW5C6rzIdY4ppnF7J8aAJbQepgbJYBjCY9usGXDKQxq7RZfh9eg5d1UHMVATRaD/4BHK93/1iAgYZ/+jqPn8Dn4UExmWrpa3+ZOK6MvM3bjwfzxNWA2dhs8+51XHSPJiaAhGSpWevEs5xHLXcEGFXYiCONySH3fPWq93JIsBiSWvWyc3CAN+EcXoT7rCSANloPPoa31rt/5PUA/gp8Q/jDD3hyrjzlR8VkanfOvB1XPubt17vzxAfdSVbD1pzAnfgyF3ycadOTOTXhpEUoLC1HZyNGW3dtmjeXgr2r56JNmRwdNNWaQVBddd6rh4MhviEB9EFRD/7RGvePvCbwAL4Mx/D6M541hHO4D3e7g6PafdcZVw689z7NGTwo5om7A8sPhccT6qKcl9NJl9aM/9kX+e59Hh1yPqGuCCZxuITcsmNaJ5F7d0q6J3H48TO1/+M57085q2icdu2U+W36Ldllz9Agiv4YGljoEN908EzvDOrBF98/vtJwCC/BF2AG75xxEmjmMIcjxbjoaxqOK3/4hPOZzhMPBpYPG44CM0dTVm1LjLtUWWVz1Bcf8tEx0zs8O2A2YVHRxKYOiy/aOVoAaMu0i7ubu43njjmd4ibMHU1sIDHaQNKrZND/FZYdk54oCXetjq7E7IVl9eAL7t+oHnwXXtLx44czzoRFHBztYVwtH1d+NOMkupZ5MTM+gUmq90X+Bh9zjRlmaQ+m7YMqUL/veemcecAtOJ0yq1JnVlN27di2E0+Klp1tAJ4KRw1eMI7aJjsO3R8kPSI3fUFXnIOfdQe86sIIVtWDL7h//Ok6vj8vwDk08NEcI8zz7OhBy+WwalzZeZ4+0XniRfst9pAJqQHDGLzVQ2pheZnnv1OWhwO43/AgcvAEXEVVpa4db9sGvNK8wjaENHkfFQ4Ci5i7dqnQlPoLQrHXZDvO3BIXZbJOBrOaEbML6sFL798I4FhKihjHMsPjBUZYCMFr6nvaArxqXPn4lCa+cHfSa2cP27g3Z3ziYTRrcbQNGLQmGF3F3cBdzzzX7AILx0IB9rbwn9kx2G1FW3Inic+ZLIsVvKR8Zwfj0l1fkqo8LWY1M3IX14OX3r9RKTIO+d9XzAI8qRPGPn/4NC2n6o4rN8XJ82TOIvuVA8zLKUHRFgBCetlDZlqR1gLKjS39xoE7Bt8UvA6BxuEDjU3tFsEijgA+615tmZkXKqiEENrh41iLDDZNq4pKTWR3LZfnos81LOuNa15cD956vLMsJd1rqYp51gDUQqMYm2XsxnUhD2jg1DM7SeuJxxgrmpfISSXVIJIS5qJJSvJPEQ49DQTVIbYWJ9QWa/E2+c/oPK1drmC7WSfJRNKBO5Yjvcp7Gc3dmmI/Xh1kDTEuiSnWqQf37h+fTMhGnDf6dsS8SQfQWlqqwXXGlc/PEZ/SC5mtzIV0nAshlQdM/LvUtYutrEZ/Y+EAFtq1k28zQhOwLr1AIeANzhF8t9qzTdZf2qRKO6MWE9ohBYwibbOmrFtNmg3mcS+tB28xv2uKd/agYCvOP+GkSc+0lr7RXzyufL7QbkUpjLjEWFLqOIkAGu2B0tNlO9Eau2W1qcOUvVRgKzypKIQZ5KI3q0MLzqTNRYqiZOqmtqloIRlmkBHVpHmRYV6/HixbO6UC47KOFJnoMrVyr7wYz+SlW6GUaghYbY1I6kkxA2W1fSJokUdSh2LQ1GAimRGm0MT+uu57H5l7QgOWxERpO9moLRPgTtquWCfFlGlIjQaRly9odmzMOWY+IBO5tB4sW/0+VWGUh32qYk79EidWKrjWuiLpiVNGFWFRJVktyeXWmbgBBzVl8anPuXyNJlBJOlKLTgAbi/EYHVHxWiDaVR06GnHQNpJcWcK2jJtiCfG2sEHLzuI66sGrMK47nPIInPnu799935aOK2cvmvubrE38ZzZjrELCmXM2hM7UcpXD2oC3+ECVp7xtIuxptJ0jUr3sBmBS47TVxlvJ1Sqb/E0uLdvLj0lLr29ypdd/eMX3f6lrxGlKwKQxEGvw0qHbkbwrF3uHKwVENbIV2wZ13kNEF6zD+x24aLNMfDTCbDPnEikZFyTNttxWBXDaBuM8KtI2rmaMdUY7cXcUPstqTGvBGSrFWIpNMfbdea990bvAOC1YX0qbc6smDS1mPxSJoW4fwEXvjMmhlijDRq6qale6aJEuFGoppYDoBELQzLBuh/mZNx7jkinv0EtnUp50lO9hbNK57lZaMAWuWR5Yo9/kYwcYI0t4gWM47Umnl3YmpeBPqSyNp3K7s2DSAS/39KRuEN2bS4xvowV3dFRMx/VFcp2Yp8w2nTO9hCXtHG1kF1L4KlrJr2wKfyq77R7MKpFKzWlY9UkhYxyHWW6nBWPaudvEAl3CGcNpSXPZ6R9BbBtIl6cHL3gIBi+42CYXqCx1gfGWe7Ap0h3luyXdt1MKy4YUT9xSF01G16YEdWsouW9mgDHd3veyA97H+Ya47ZmEbqMY72oPztCGvK0onL44AvgC49saZKkWRz4veWljE1FHjbRJaWv6ZKKtl875h4CziFCZhG5rx7tefsl0aRT1bMHZjm8dwL/6u7wCRysaQblQoG5yAQN5zpatMNY/+yf8z+GLcH/Qn0iX2W2oEfXP4GvwQHuIL9AYGnaO3zqAX6946nkgqZNnUhx43DIdQtMFeOPrgy/y3Yd85HlJWwjLFkU3kFwq28xPnuPhMWeS+tDLV9Otllq7pQCf3uXJDN9wFDiUTgefHaiYbdfi3b3u8+iY6TnzhgehI1LTe8lcd7s1wJSzKbahCRxKKztTLXstGAiu3a6rPuQs5pk9TWAan5f0BZmGf7Ylxzzk/A7PAs4QPPPAHeFQ2hbFHszlgZuKZsJcUmbDC40sEU403cEjczstOEypa+YxevL4QBC8oRYqWdK6b7sK25tfE+oDZgtOQ2Jg8T41HGcBE6fTWHn4JtHcu9S7uYgU5KSCkl/mcnq+5/YBXOEr6lCUCwOTOM1taOI8mSxx1NsCXBEmLKbMAg5MkwbLmpBaFOPrNSlO2HnLiEqW3tHEwd8AeiQLmn+2gxjC3k6AxREqvKcJbTEzlpLiw4rNZK6oJdidbMMGX9FULKr0AkW+2qDEPBNNm5QAt2Ik2nftNWHetubosHLo2nG4vQA7GkcVCgVCgaDixHqo9UUn1A6OshapaNR/LPRYFV8siT1cCtJE0k/3WtaNSuUZYKPnsVIW0xXWnMUxq5+En4Kvw/MqQmVXnAXj9Z+9zM98zM/Agy7F/qqj2Nh67b8HjFnPP3iBn/tkpdzwEJX/whIcQUXOaikeliCRGUk7tiwF0rItwMEhjkZ309hikFoRAmLTpEXWuHS6y+am/KB/fM50aLEhGnSMwkpxzOov4H0AvgovwJ1iGzDLtJn/9BU+fAINfwUe6FHSLhu83viV/+/HrOePX+STT2B9uWGbrMHHLldRBlhS/CJQmcRxJFqZica01XixAZsYiH1uolZxLrR/SgxVIJjkpQP4PE9sE59LKLr7kltSBogS5tyszzH8Fvw8/AS8rNOg0xUS9fIaHwb+6et8Q/gyvKRjf5OusOzGx8evA/BP4IP11uN/grca5O0lcsPLJ5YjwI4QkJBOHa0WdMZYGxPbh2W2nR9v3WxEWqgp/G3+6VZbRLSAAZ3BhdhAaUL33VUSw9yjEsvbaQ9u4A/gGXwZXoEHOuU1GSj2chf+Mo+f8IcfcAxfIKVmyunRbYQVnoevwgfw3TXXcw++xNuP4fhyueEUNttEduRVaDttddoP0eSxLe2LENk6itYxlrxBNBYrNNKSQmeaLcm9c8UsaB5WyO6675yyQIAWSDpBVoA/gxmcwEvwoDv0m58UE7gHn+fJOa8/Ywan8EKRfjsopF83eCglX/Sfr7OeaRoQfvt1CGvIDccH5BCvw1sWIzRGC/66t0VTcLZQZtm6PlAasbOJ9iwWtUo7biktTSIPxnR24jxP1ZKaqq+2RcXM9OrBAm/AAs7hDJ5bNmGb+KIfwCs8a3jnjBrOFeMjHSCdbKr+2uOLfnOd9eiA8Hvvwwq54VbP2OqwkB48Ytc4YEOiH2vTXqodabfWEOzso4qxdbqD5L6tbtNPECqbhnA708DZH4QOJUXqScmUlks7Ot6FBuZw3n2mEbaUX7kDzxHOOQk8nKWMzAzu6ZZ8sOFw4RK+6PcuXo9tB4SbMz58ApfKDXf3szjNIIbGpD5TKTRxGkEMLjLl+K3wlWXBsCUxIDU+jbOiysESqAy1MGUJpXgwbTWzNOVEziIXZrJ+VIztl1PUBxTSo0dwn2bOmfDRPD3TRTGlfbCJvO9KvuhL1hMHhB9wPuPRLGHcdOWG2xc0U+5bQtAJT0nRTewXL1pgk2+rZAdeWmz3jxAqfNQQdzTlbF8uJ5ecEIWvTkevAHpwz7w78QujlD/Lr491bD8/1vhM2yrUQRrWXNQY4fGilfctMWYjL72UL/qS9eiA8EmN88nbNdour+PBbbAjOjIa4iBhfFg6rxeKdEGcL6p3EWR1Qq2Qkhs2DrnkRnmN9tG2EAqmgPw6hoL7Oza7B+3SCrR9tRftko+Lsf2F/mkTndN2LmzuMcKTuj/mX2+4Va3ki16+nnJY+S7MefpkidxwnV+4wkXH8TKnX0tsYzYp29DOOoSW1nf7nTh2akYiWmcJOuTidSaqESrTYpwjJJNVGQr+rLI7WsqerHW6Kp/oM2pKuV7T1QY9gjqlZp41/WfKpl56FV/0kvXQFRyeQ83xaTu5E8p5dNP3dUF34ihyI3GSpeCsywSh22ZJdWto9winhqifb7VRvgktxp13vyjrS0EjvrRfZ62uyqddSWaWYlwTPAtJZ2oZ3j/Sgi/mi+6vpzesfAcWNA0n8xVyw90GVFGuZjTXEQy+6GfLGLMLL523f5E0OmxVjDoOuRiH91RKU+vtoCtH7TgmvBLvtFXWLW15H9GTdVw8ow4IlRLeHECN9ym1e9K0I+Cbnhgv4Yu+aD2HaQJ80XDqOzSGAV4+4yCqBxrsJAX6ZTIoX36QnvzhhzzMfFW2dZVLOJfo0zbce5OvwXMFaZ81mOnlTVXpDZsQNuoYWveketKb5+6JOOsgX+NTm7H49fUTlx+WLuWL7qxnOFh4BxpmJx0p2gDzA/BUARuS6phR+pUsY7MMboAHx5xNsSVfVZcYSwqCKrqon7zM+8ecCkeS4nm3rINuaWvVNnMRI1IRpxTqx8PZUZ0Br/UEduo3B3hNvmgZfs9gQPj8vIOxd2kndir3awvJ6BLvoUuOfFWNYB0LR1OQJoUySKb9IlOBx74q1+ADC2G6rOdmFdJcD8BkfualA+BdjOOzP9uUhGUEX/TwhZsUduwRr8wNuXKurCixLBgpQI0mDbJr9dIqUuV+92ngkJZ7xduCk2yZKbfWrH1VBiTg9VdzsgRjW3CVXCvAwDd+c1z9dWw9+B+8MJL/eY15ZQ/HqvTwVdsZn5WQsgRRnMaWaecu3jFvMBEmgg+FJFZsnSl0zjB9OqPYaBD7qmoVyImFvzi41usesV0julaAR9dfR15Xzv9sEruRDyk1nb+QaLU67T885GTls6YgcY+UiMa25M/pwGrbCfzkvR3e0jjtuaFtnwuagHTSb5y7boBH119HXhvwP487jJLsLJ4XnUkHX5sLbS61dpiAXRoZSCrFJ+EjpeU3puVfitngYNo6PJrAigKktmwjyQdZpfq30mmtulaAx9Zfx15Xzv+cyeuiBFUs9zq8Kq+XB9a4PVvph3GV4E3y8HENJrN55H1X2p8VyqSKwVusJDKzXOZzplWdzBUFK9e+B4+uv468xvI/b5xtSAkBHQaPvtqWzllVvEOxPbuiE6+j2pvjcKsbvI7txnRErgfH7LdXqjq0IokKzga14GzQ23SSbCQvO6r+Or7SMIr/efOkkqSdMnj9mBx2DRsiY29Uj6+qK9ZrssCKaptR6HKURdwUYeUWA2kPzVKQO8ku2nU3Anhs/XWkBx3F/7wJtCTTTIKftthue1ty9xvNYLY/zo5KSbIuKbXpbEdSyeRyYdAIwKY2neyoc3+k1XUaufYga3T9daMUx/r8z1s10ITknIO0kuoMt+TB8jK0lpayqqjsJ2qtXAYwBU932zinimgmd6mTRDnQfr88q36NAI+tv24E8Pr8zxtasBqx0+xHH9HhlrwsxxNUfKOHQaZBITNf0uccj8GXiVmXAuPEAKSdN/4GLHhs/XWj92dN/uetNuBMnVR+XWDc25JLjo5Mg5IZIq226tmCsip2zZliL213YrTlL2hcFjpCduyim3M7/eB16q/blQsv5X/esDRbtJeabLIosWy3ycavwLhtxdWzbMmHiBTiVjJo6lCLjXZsi7p9PEPnsq6X6wd4bP11i0rD5fzPm/0A6brrIsllenZs0lCJlU4abakR59enZKrKe3BZihbTxlyZ2zl1+g0wvgmA166/bhwDrcn/7Ddz0eWZuJvfSESug6NzZsox3Z04FIxz0mUjMwVOOVTq1CQ0AhdbBGVdjG/CgsfUX7esJl3K/7ytWHRv683praW/8iDOCqWLLhpljDY1ZpzK75QiaZoOTpLKl60auHS/97oBXrv+umU9+FL+5+NtLFgjqVLCdbmj7pY5zPCPLOHNCwXGOcLquOhi8CmCWvbcuO73XmMUPab+ug3A6/A/78Bwe0bcS2+tgHn4J5pyS2WbOck0F51Vq3LcjhLvZ67p1ABbaL2H67bg78BfjKi/jr3+T/ABV3ilLmNXTI2SpvxWBtt6/Z//D0z/FXaGbSBgylzlsEGp+5//xrd4/ae4d8DUUjlslfIYS3t06HZpvfQtvv0N7AHWqtjP2pW08QD/FLy//da38vo8PNlKHf5y37Dxdfe/oj4kVIgFq3koLReSR76W/bx//n9k8jonZxzWTANVwEniDsg87sOSd/z7//PvMp3jQiptGVWFX2caezzAXwfgtzYUvbr0iozs32c3Uge7varH+CNE6cvEYmzbPZ9hMaYDdjK4V2iecf6EcEbdUDVUARda2KzO/JtCuDbNQB/iTeL0EG1JSO1jbXS+nLxtPMDPw1fh5+EPrgSEKE/8Gry5A73ui87AmxwdatyMEBCPNOCSKUeRZ2P6Myb5MRvgCHmA9ywsMifU+AYXcB6Xa5GibUC5TSyerxyh0j6QgLVpdyhfArRTTLqQjwe4HOD9s92D4Ap54odXAPBWLAwB02igG5Kkc+piN4lvODIFGAZgT+EO4Si1s7fjSR7vcQETUkRm9O+MXyo9OYhfe4xt9STQ2pcZRLayCV90b4D3jR0DYAfyxJ+eywg2IL7NTMXna7S/RpQ63JhWEM8U41ZyQGjwsVS0QBrEKLu8xwZsbi4wLcCT+OGidPIOCe1PiSc9Qt+go+vYqB7cG+B9d8cAD+WJPz0Am2gxXgU9IneOqDpAAXOsOltVuMzpdakJXrdPCzXiNVUpCeOos5cxnpQT39G+XVLhs1osQVvJKPZyNq8HDwd4d7pNDuWJPxVX7MSzqUDU6gfadKiNlUFTzLeFHHDlzO4kpa7aiKhBPGKwOqxsBAmYkOIpipyXcQSPlRTf+Tii0U3EJGaZsDER2qoB3h2hu0qe+NNwUooYU8y5mILbJe6OuX+2FTKy7bieTDAemaQyQ0CPthljSWO+xmFDIYiESjM5xKd6Ik5lvLq5GrQ3aCMLvmCA9wowLuWJb9xF59hVVP6O0CrBi3ZjZSNOvRy+I6klNVRJYRBaEzdN+imiUXQ8iVF8fsp+W4JXw7WISW7fDh7lptWkCwZ4d7QTXyBPfJMYK7SijjFppGnlIVJBJBYj7eUwtiP1IBXGI1XCsjNpbjENVpSAJ2hq2LTywEly3hUYazt31J8w2+aiLx3g3fohXixPfOMYm6zCGs9LVo9MoW3MCJE7R5u/WsOIjrqBoHUO0bJE9vxBpbhsd3+Nb4/vtPCZ4oZYCitNeYuC/8UDvDvy0qvkiW/cgqNqRyzqSZa/s0mqNGjtKOoTm14zZpUauiQgVfqtQiZjq7Q27JNaSK5ExRcrGCXO1FJYh6jR6CFqK7bZdQZ4t8g0rSlPfP1RdBtqaa9diqtzJkQ9duSryi2brQXbxDwbRUpFMBHjRj8+Nt7GDKgvph9okW7LX47gu0SpGnnFQ1S1lYldOsC7hYteR574ZuKs7Ei1lBsfdz7IZoxzzCVmmVqaSySzQbBVAWDek+N4jh9E/4VqZrJjPwiv9BC1XcvOWgO8275CVyBPvAtTVlDJfZkaZGU7NpqBogAj/xEHkeAuJihWYCxGN6e8+9JtSegFXF1TrhhLGP1fak3pebgPz192/8gB4d/6WT7+GdYnpH7hH/DJzzFiYPn/vjW0SgNpTNuPIZoAEZv8tlGw4+RLxy+ZjnKa5NdFoC7UaW0aduoYse6+bXg1DLg6UfRYwmhGEjqPvF75U558SANrElK/+MdpXvmqBpaXOa/MTZaa1DOcSiLaw9j0NNNst3c+63c7EKTpkvKHzu6bPbP0RkuHAVcbRY8ijP46MIbQeeT1mhA+5PV/inyDdQipf8LTvMXbwvoDy7IruDNVZKTfV4CTSRUYdybUCnGU7KUTDxLgCknqUm5aAW6/1p6eMsOYsphLzsHrE0Y/P5bQedx1F/4yPHnMB3/IOoTU9+BL8PhtjuFKBpZXnYNJxTuv+2XqolKR2UQgHhS5novuxVySJhBNRF3SoKK1XZbbXjVwWNyOjlqWJjrWJIy+P5bQedyldNScP+HZ61xKSK3jyrz+NiHG1hcOLL/+P+PDF2gOkekKGiNWKgJ+8Z/x8Iv4DdQHzcpZyF4v19I27w9/yPGDFQvmEpKtqv/TLiWMfn4sofMm9eAH8Ao0zzh7h4sJqYtxZd5/D7hkYPneDzl5idlzNHcIB0jVlQ+8ULzw/nc5/ojzl2juE0apD7LRnJxe04dMz2iOCFNtGFpTuXA5AhcTRo8mdN4kz30nVjEC4YTZQy4gpC7GlTlrePKhGsKKgeXpCYeO0MAd/GH7yKQUlXPLOasOH3FnSphjHuDvEu4gB8g66oNbtr6eMbFIA4fIBJkgayoXriw2XEDQPJrQeROAlY6aeYOcMf+IVYTU3XFlZufMHinGywaW3YLpObVBAsbjF4QJMsVUSayjk4voPsHJOQfPWDhCgDnmDl6XIRerD24HsGtw86RMHOLvVSHrKBdeVE26gKB5NKHzaIwLOmrqBWJYZDLhASG16c0Tn+CdRhWDgWXnqRZUTnPIHuMJTfLVpkoYy5CzylHVTGZMTwkGAo2HBlkQplrJX6U+uF1wZz2uwS1SQ12IqWaPuO4baZaEFBdukksJmkcTOm+YJSvoqPFzxFA/YUhIvWxcmSdPWTWwbAKVp6rxTtPFUZfKIwpzm4IoMfaYQLWgmlG5FME2gdBgm+J7J+rtS/XBbaVLsR7bpPQnpMFlo2doWaVceHk9+MkyguZNCJ1He+kuHTWyQAzNM5YSUg/GlTk9ZunAsg1qELVOhUSAK0LABIJHLKbqaEbHZLL1VA3VgqoiOKXYiS+HRyaEKgsfIqX64HYWbLRXy/qWoylIV9gudL1OWBNgBgTNmxA6b4txDT4gi3Ri7xFSLxtXpmmYnzAcWDZgY8d503LFogz5sbonDgkKcxGsWsE1OI+rcQtlgBBCSOKD1mtqYpIU8cTvBmAT0yZe+zUzeY92fYjTtGipXLhuR0ePoHk0ofNWBX+lo8Z7pAZDk8mEw5L7dVyZZoE/pTewbI6SNbiAL5xeygW4xPRuLCGbhcO4RIeTMFYHEJkYyEO9HmJfXMDEj/LaH781wHHZEtqSQ/69UnGpzH7LKIAZEDSPJnTesJTUa+rwTepI9dLJEawYV+ZkRn9g+QirD8vF8Mq0jFQ29js6kCS3E1+jZIhgPNanHdHFqFvPJLHqFwQqbIA4jhDxcNsOCCQLDomaL/dr5lyJaJU6FxPFjO3JOh3kVMcROo8u+C+jo05GjMF3P3/FuDLn5x2M04xXULPwaS6hBYki+MrMdZJSgPHlcB7nCR5bJ9Kr5ACUn9jk5kivdd8tk95SOGrtqu9lr2IhK65ZtEl7ZKrp7DrqwZfRUSN1el7+7NJxZbywOC8neNKTch5vsTEMNsoCCqHBCqIPRjIPkm0BjvFODGtto99rCl+d3wmHkW0FPdpZtC7MMcVtGFQjJLX5bdQ2+x9ypdc313uj8xlsrfuLgWXz1cRhZvJYX0iNVBRcVcmCXZs6aEf3RQF2WI/TcCbKmGU3IOoDJGDdDub0+hYckt6PlGu2BcxmhbTdj/klhccLGJMcqRjMJP1jW2ETqLSWJ/29MAoORluJ+6LPffBZbi5gqi5h6catQpmOT7/OFf5UorRpLzCqcMltBLhwd1are3kztrSzXO0LUbXRQcdLh/RdSZ+swRm819REDrtqzC4es6Gw4JCKlSnjYVpo0xeq33PrADbFLL3RuCmObVmPN+24kfa+AojDuM4umKe2QwCf6EN906HwjujaitDs5o0s1y+k3lgbT2W2i7FJdnwbLXhJUBq/9liTctSmFC/0OqUinb0QddTWamtjbHRFuWJJ6NpqZ8vO3fZJ37Db+2GkaPYLGHs7XTTdiFQJ68SkVJFVmY6McR5UycflNCsccHFaV9FNbR4NttLxw4pQ7wJd066Z0ohVbzihaxHVExd/ay04oxUKWt+AsdiQ9OUyZ2krzN19IZIwafSTFgIBnMV73ADj7V/K8u1MaY2sJp2HWm0f41tqwajEvdHWOJs510MaAqN4aoSiPCXtN2KSi46dUxHdaMquar82O1x5jqhDGvqmoE9LfxcY3zqA7/x3HA67r9ZG4O6Cuxu12/+TP+eLP+I+HErqDDCDVmBDO4larujNe7x8om2rMug0MX0rL1+IWwdwfR+p1TNTyNmVJ85ljWzbWuGv8/C7HD/izjkHNZNYlhZcUOKVzKFUxsxxN/kax+8zPWPSFKw80rJr9Tizyj3o1gEsdwgWGoxPezDdZ1TSENE1dLdNvuKL+I84nxKesZgxXVA1VA1OcL49dFlpFV5yJMhzyCmNQ+a4BqusPJ2bB+xo8V9u3x48VVIEPS/mc3DvAbXyoYr6VgDfh5do5hhHOCXMqBZUPhWYbWZECwVJljLgMUWOCB4MUuMaxGNUQDVI50TQ+S3kFgIcu2qKkNSHVoM0SHsgoZxP2d5HH8B9woOk4x5bPkKtAHucZsdykjxuIpbUrSILgrT8G7G5oCW+K0990o7E3T6AdW4TilH5kDjds+H64kS0mz24grtwlzDHBJqI8YJQExotPvoC4JBq0lEjjQkyBZ8oH2LnRsQ4Hu1QsgDTJbO8fQDnllitkxuVskoiKbRF9VwzMDvxHAdwB7mD9yCplhHFEyUWHx3WtwCbSMMTCUCcEmSGlg4gTXkHpZXWQ7kpznK3EmCHiXInqndkQjunG5kxTKEeGye7jWz9cyMR2mGiFQ15ENRBTbCp+Gh86vAyASdgmJq2MC6hoADQ3GosP0QHbnMHjyBQvQqfhy/BUbeHd5WY/G/9LK/8Ka8Jd7UFeNWEZvzPb458Dn8DGLOe3/wGL/4xP+HXlRt+M1PE2iLhR8t+lfgxsuh7AfO2AOf+owWhSZRYQbd622hbpKWKuU+XuvNzP0OseRDa+mObgDHJUSc/pKx31QdKffQ5OIJpt8GWjlgTwMc/w5MPCR/yl1XC2a2Yut54SvOtMev55Of45BOat9aWG27p2ZVORRvnEk1hqWMVUmqa7S2YtvlIpspuF1pt0syuZS2NV14mUidCSfzQzg+KqvIYCMljIx2YK2AO34fX4GWdu5xcIAb8MzTw+j/lyWM+Dw/gjs4GD6ehNgA48kX/AI7XXM/XAN4WHr+9ntywqoCakCqmKP0rmQrJJEErG2Upg1JObr01lKQy4jskWalKYfJ/EDLMpjNSHFEUAde2fltaDgmrNaWQ9+AAb8I5vKjz3L1n1LriB/BXkG/wwR9y/oRX4LlioHA4LzP2inzRx/DWmutRweFjeP3tNeSGlaE1Fde0OS11yOpmbIp2u/jF1n2RRZviJM0yBT3IZl2HWImKjQOxIyeU325b/qWyU9Moj1o07tS0G7qJDoGHg5m8yeCxMoEH8GU45tnrNM84D2l297DQ9t1YP7jki/7RmutRweEA77/HWXOh3HCxkRgldDQkAjNTMl2Iloc1qN5JfJeeTlyTRzxURTdn1Ixv2uKjs12AbdEWlBtmVdk2k7FFwj07PCZ9XAwW3dG+8xKzNFr4EnwBZpy9Qzhh3jDXebBpYcpuo4fQ44u+fD1dweEnHzI7v0xuuOALRUV8rXpFyfSTQYkhd7IHm07jpyhlkCmI0ALYqPTpUxXS+z4jgDj1Pflvmz5ecuItpIBxyTHpSTGWd9g1ApfD/bvwUhL4nT1EzqgX7cxfCcNmb3mPL/qi9SwTHJ49oj5ZLjccbTG3pRmlYi6JCG0mQrAt1+i2UXTZ2dv9IlQpN5naMYtviaXlTrFpoMsl3bOAFEa8sqPj2WCMrx3Yjx99qFwO59Aw/wgx+HlqNz8oZvA3exRDvuhL1jMQHPaOJ0+XyA3fp1OfM3qObEVdhxjvynxNMXQV4+GJyvOEFqeQBaIbbO7i63rpxCltdZShPFxkjM2FPVkn3TG+Rp9pO3l2RzFegGfxGDHIAh8SteR0C4HopXzRF61nheDw6TFN05Ebvq8M3VKKpGjjO6r7nhudTEGMtYM92HTDaR1FDMXJ1eThsbKfywyoWwrzRSXkc51flG3vIid62h29bIcFbTGhfV+faaB+ohj7dPN0C2e2lC96+XouFByen9AsunLDJZ9z7NExiUc0OuoYW6UZkIyx2YUR2z6/TiRjyKMx5GbbjLHvHuf7YmtKghf34LJfx63Yg8vrvN2zC7lY0x0tvKezo4HmGYDU+Gab6dFL+KI761lDcNifcjLrrr9LWZJctG1FfU1uwhoQE22ObjdfkSzY63CbU5hzs21WeTddH2BaL11Gi7lVdlxP1nkxqhnKhVY6knS3EPgVGg1JpN5cP/hivujOelhXcPj8HC/LyI6MkteVjlolBdMmF3a3DbsuAYhL44dxzthWSN065xxUd55Lmf0wRbOYOqH09/o9WbO2VtFdaMb4qBgtFJoT1SqoN8wPXMoXLb3p1PUEhxfnnLzGzBI0Ku7FxrKsNJj/8bn/H8fPIVOd3rfrklUB/DOeO+nkghgSPzrlPxluCMtOnDL4Yml6dK1r3vsgMxgtPOrMFUZbEUbTdIzii5beq72G4PD0DKnwjmBULUVFmy8t+k7fZ3pKc0Q4UC6jpVRqS9Umv8bxw35flZVOU1X7qkjnhZlsMbk24qQ6Hz7QcuL6sDC0iHHki96Uh2UdvmgZnjIvExy2TeJdMDZNSbdZyAHe/Yd1xsQhHiKzjh7GxQ4yqMPaywPkjMamvqrYpmO7Knad+ZQC5msCuAPWUoxrxVhrGv7a+KLXFhyONdTMrZ7ke23qiO40ZJUyzgYyX5XyL0mV7NiUzEs9mjtbMN0dERqwyAJpigad0B3/zRV7s4PIfXSu6YV/MK7+OrYe/JvfGMn/PHJe2fyUdtnFrKRNpXV0Y2559aWPt/G4BlvjTMtXlVIWCnNyA3YQBDmYIodFz41PvXPSa6rq9lWZawZ4dP115HXV/M/tnFkkrBOdzg6aP4pID+MZnTJ1SuuB6iZlyiox4HT2y3YBtkUKWooacBQUDTpjwaDt5poBHl1/HXltwP887lKKXxNUEyPqpGTyA699UqY/lt9yGdlUKra0fFWS+36iylVWrAyd7Uw0CZM0z7xKTOduznLIjG2Hx8cDPLb+OvK6Bv7n1DYci4CxUuRxrjBc0bb4vD3rN5Zz36ntLb83eVJIB8LiIzCmn6SMPjlX+yNlTjvIGjs+QzHPf60Aj62/jrzG8j9vYMFtm1VoRWCJdmw7z9N0t+c8cxZpPeK4aTRicS25QhrVtUp7U578chk4q04Wx4YoQSjFryUlpcQ1AbxZ/XVMknIU//OGl7Q6z9Zpxi0+3yFhSkjUDpnCIUhLWVX23KQ+L9vKvFKI0ZWFQgkDLvBoylrHNVmaw10zwCPrr5tlodfnf94EWnQ0lFRWy8pW9LbkLsyUVDc2NSTHGDtnD1uMtchjbCeb1mpxFP0YbcClhzdLu6lfO8Bj6q+bdT2sz/+8SZCV7VIxtt0DUn9L7r4cLYWDSXnseEpOGFuty0qbOVlS7NNzs5FOGJUqQpl2Q64/yBpZf90sxbE+//PGdZ02HSipCbmD6NItmQ4Lk5XUrGpDMkhbMm2ZVheNYV+VbUWTcv99+2NyX1VoafSuC+AN6q9bFIMv5X/eagNWXZxEa9JjlMwNWb00akGUkSoepp1/yRuuqHGbUn3UdBSTxBU6SEVklzWRUkPndVvw2PrrpjvxOvzPmwHc0hpmq82npi7GRro8dXp0KXnUQmhZbRL7NEVp1uuZmO45vuzKsHrktS3GLWXODVjw+vXXLYx4Hf7njRPd0i3aoAGX6W29GnaV5YdyDj9TFkakje7GHYzDoObfddHtOSpoi2SmzJHrB3hM/XUDDEbxP2/oosszcRlehWXUvzHv4TpBVktHqwenFo8uLVmy4DKLa5d3RtLrmrM3aMFr1183E4sewf+85VWeg1c5ag276NZrM9IJVNcmLEvDNaV62aq+14IAOGFsBt973Ra8Xv11YzXwNfmft7Jg2oS+XOyoC8/cwzi66Dhmgk38kUmP1CUiYWOX1bpD2zWXt2FCp7uq8703APAa9dfNdscR/M/bZLIyouVxqJfeWvG9Je+JVckHQ9+CI9NWxz+blX/KYYvO5n2tAP/vrlZ7+8/h9y+9qeB/Hnt967e5mevX10rALDWK//FaAT5MXdBXdP0C/BAes792c40H+AiAp1e1oH8HgH94g/Lttx1gp63op1eyoM/Bvw5/G/7xFbqJPcCXnmBiwDPb/YKO4FX4OjyCb289db2/Noqicw4i7N6TVtoz8tNwDH+8x/i6Ae7lmaQVENzJFb3Di/BFeAwz+Is9SjeQySpPqbLFlNmyz47z5a/AF+AYFvDmHqibSXTEzoT4Gc3OALaqAP4KPFUJ6n+1x+rGAM6Zd78bgJ0a8QN4GU614vxwD9e1Amy6CcskNrczLx1JIp6HE5UZD/DBHrFr2oNlgG4Odv226BodoryjGJ9q2T/AR3vQrsOCS0ctXZi3ruLlhpFDJYl4HmYtjQCP9rhdn4suySLKDt6wLcC52h8xPlcjju1fn+yhuw4LZsAGUuo2b4Fx2UwQu77uqRHXGtg92aN3tQCbFexc0uk93vhTXbct6y7MulLycoUljx8ngDMBg1tvJjAazpEmOtxlzclvj1vQf1Tx7QlPDpGpqgtdSKz/d9/hdy1vTfFHSmC9dGDZbLiezz7Ac801HirGZsWjydfZyPvHXL/Y8Mjzg8BxTZiuwKz4Eb8sBE9zznszmjvFwHKPIWUnwhqfVRcd4Ck0K6ate48m1oOfrX3/yOtvAsJ8zsPAM89sjnddmuLuDPjX9Bu/L7x7xpMzFk6nWtyQfPg278Gn4Aekz2ZgOmU9eJ37R14vwE/BL8G3aibCiWMWWDQ0ZtkPMnlcGeAu/Ag+8ZyecU5BPuy2ILD+sQqyZhAKmn7XZd+jIMTN9eBL7x95xVLSX4On8EcNlXDqmBlqS13jG4LpmGbkF/0CnOi3H8ETOIXzmnmtb0a16Tzxj1sUvQCBiXZGDtmB3KAefPH94xcUa/6vwRn80GOFyjEXFpba4A1e8KQfFF+259tx5XS4egYn8fQsLGrqGrHbztr+uByTahWuL1NUGbDpsnrwBfePPwHHIf9X4RnM4Z2ABWdxUBlqQ2PwhuDxoS0vvqB1JzS0P4h2nA/QgTrsJFn+Y3AOjs9JFC07CGWX1oNX3T/yHOzgDjwPn1PM3g9Jk9lZrMEpxnlPmBbjyo2+KFXRU52TJM/2ALcY57RUzjObbjqxVw++4P6RAOf58pcVsw9Daje3htriYrpDOonre3CudSe6bfkTEgHBHuDiyu5MCsc7BHhYDx7ePxLjqigXZsw+ijMHFhuwBmtoTPtOxOrTvYJDnC75dnUbhfwu/ZW9AgYd+peL68HD+0emKquiXHhWjJg/UrkJYzuiaL3E9aI/ytrCvAd4GcYZMCkSQxfUg3v3j8c4e90j5ZTPdvmJJGHnOCI2nHS8081X013pHuBlV1gB2MX1YNmWLHqqGN/TWmG0y6clJWthxNUl48q38Bi8vtMKyzzpFdSDhxZ5WBA5ZLt8Jv3895DduBlgbPYAj8C4B8hO68FDkoh5lydC4FiWvBOVqjYdqjiLv92t8yPDjrDaiHdUD15qkSURSGmXJwOMSxWAXYwr3zaAufJ66l+94vv3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/wHuD9tQd4f+0B3l97gPfXHuD9tQd4f+0B3l97gG8LwP8G/AL8O/A5OCq0Ys2KIdv/qOIXG/4mvFAMF16gZD+2Xvu/B8as5+8bfllWyg0zaNO5bfXj6vfhhwD86/Aq3NfRS9t9WPnhfnvCIw/CT8GLcFTMnpntdF/z9V+PWc/vWoIH+FL3Znv57PitcdGP4R/C34avw5fgRVUInCwbsn1yyA8C8zm/BH8NXoXnVE6wVPjdeCI38kX/3+Ct9dbz1pTmHFRu+Hm4O9Ch3clr99negxfwj+ER/DR8EV6B5+DuQOnTgUw5rnkY+FbNU3gNXh0o/JYTuWOvyBf9FvzX663HH/HejO8LwAl8Hl5YLTd8q7sqA3wbjuExfAFegQdwfyDoSkWY8swzEf6o4Qyewefg+cHNbqMQruSL/u/WWc+E5g7vnnEXgDmcDeSGb/F4cBcCgT+GGRzDU3hZYburAt9TEtHgbM6JoxJ+6NMzzTcf6c2bycv2+KK/f+l6LBzw5IwfqZJhA3M472pWT/ajKxnjv4AFnMEpnBTPND6s2J7qHbPAqcMK74T2mZ4VGB9uJA465It+/eL1WKhYOD7xHOkr1ajK7d0C4+ke4Hy9qXZwpgLr+Znm/uNFw8xQOSy8H9IzjUrd9+BIfenYaylf9FsXr8fBAadnPIEDna8IBcwlxnuA0/Wv6GAWPd7dDIKjMdSWueAsBj4M7TOd06qBbwDwKr7oleuxMOEcTuEZTHWvDYUO7aHqAe0Bbq+HEFRzOz7WVoTDQkVds7A4sIIxfCQdCefFRoIOF/NFL1mPab/nvOakSL/Q1aFtNpUb/nFOVX6gzyg/1nISyDfUhsokIzaBR9Kxm80s5mK+6P56il1jXic7nhQxsxSm3OwBHl4fFdLqi64nDQZvqE2at7cWAp/IVvrN6/BFL1mPhYrGMBfOi4PyjuSGf6wBBh7p/FZTghCNWGgMzlBbrNJoPJX2mW5mwZfyRffXo7OFi5pZcS4qZUrlViptrXtw+GQoyhDPS+ANjcGBNRiLCQDPZPMHuiZfdFpPSTcQwwKYdRNqpkjm7AFeeT0pJzALgo7g8YYGrMHS0iocy+YTm2vyRUvvpXCIpQ5pe666TJrcygnScUf/p0NDs/iAI/nqDHC8TmQT8x3NF91l76oDdQGwu61Z6E0ABv7uO1dbf/37Zlv+Zw/Pbh8f1s4Avur6657/+YYBvur6657/+YYBvur6657/+YYBvur6657/+aYBvuL6657/+VMA8FXWX/f8zzcN8BXXX/f8zzcNMFdbf93zP38KLPiK6697/uebtuArrr/u+Z9vGmCusP6653/+1FjwVdZf9/zPN7oHX339dc//fNMu+irrr3v+50+Bi+Zq6697/uebA/jz8Pudf9ht/fWv517J/XUzAP8C/BAeX9WCDrUpZ3/dEMBxgPcfbtTVvsYV5Yn32u03B3Ac4P3b8I+vxNBKeeL9dRMAlwO83959qGO78sT769oB7g3w/vGVYFzKE++v6wV4OMD7F7tckFkmT7y/rhHgpQO8b+4Y46XyxPvrugBeNcB7BRiX8sT767oAvmCA9woAHsoT76+rBJjLBnh3txOvkifeX1dswZcO8G6N7sXyxPvr6i340gHe3TnqVfLE++uKAb50gHcXLnrX8sR7gNdPRqwzwLu7Y/FO5Yn3AK9jXCMGeHdgxDuVJ75VAI8ljP7PAb3/RfjcZfePHBB+79dpfpH1CanN30d+mT1h9GqAxxJGM5LQeeQ1+Tb+EQJrElLb38VHQ94TRq900aMIo8cSOo+8Dp8QfsB8zpqE1NO3OI9Zrj1h9EV78PqE0WMJnUdeU6E+Jjyk/hbrEFIfeWbvId8H9oTRFwdZaxJGvziW0Hn0gqYB/wyZ0PwRlxJST+BOw9m77Amj14ii1yGM/txYQudN0qDzGe4EqfA/5GJCagsHcPaEPWH0esekSwmjRxM6b5JEcZ4ww50ilvAOFxBSx4yLW+A/YU8YvfY5+ALC6NGEzhtmyZoFZoarwBLeZxUhtY4rc3bKnjB6TKJjFUHzJoTOozF2YBpsjcyxDgzhQ1YRUse8+J4wenwmaylB82hC5w0zoRXUNXaRBmSMQUqiWSWkLsaVqc/ZE0aPTFUuJWgeTei8SfLZQeMxNaZSIzbII4aE1Nmr13P2hNHjc9E9guYNCZ032YlNwESMLcZiLQHkE4aE1BFg0yAR4z1h9AiAGRA0jyZ03tyIxWMajMPWBIsxYJCnlITU5ShiHYdZ94TR4wCmSxg9jtB5KyPGYzymAYexWEMwAPIsAdYdV6aObmNPGD0aYLoEzaMJnTc0Ygs+YDw0GAtqxBjkuP38bMRWCHn73xNGjz75P73WenCEJnhwyVe3AEe8TtKdJcYhBl97wuhNAObK66lvD/9J9NS75v17wuitAN5fe4D31x7g/bUHeH/tAd5fe4D3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/w/toDvAd4f/24ABzZ8o+KLsSLS+Pv/TqTb3P4hKlQrTGh+fbIBT0Axqznnb+L/V2mb3HkN5Mb/nEHeK7d4IcDld6lmDW/iH9E+AH1MdOw/Jlu2T1xNmY98sv4wHnD7D3uNHu54WUuOsBTbQuvBsPT/UfzNxGYzwkP8c+Yz3C+r/i6DcyRL/rZ+utRwWH5PmfvcvYEt9jLDS/bg0/B64DWKrQM8AL8FPwS9beQCe6EMKNZYJol37jBMy35otdaz0Bw2H/C2Smc7+WGB0HWDELBmOByA3r5QONo4V+DpzR/hFS4U8wMW1PXNB4TOqYz9urxRV++ntWCw/U59Ty9ebdWbrgfRS9AYKKN63ZokZVygr8GZ/gfIhZXIXPsAlNjPOLBby5c1eOLvmQ9lwkOy5x6QV1j5TYqpS05JtUgUHUp5toHGsVfn4NX4RnMCe+AxTpwmApTYxqMxwfCeJGjpXzRF61nbcHhUBPqWze9svwcHJ+S6NPscKrEjug78Dx8Lj3T8D4YxGIdxmJcwhi34fzZUr7olevZCw5vkOhoClq5zBPZAnygD/Tl9EzDh6kl3VhsHYcDEb+hCtJSvuiV69kLDm+WycrOTArHmB5/VYyP6jOVjwgGawk2zQOaTcc1L+aLXrKeveDwZqlKrw8U9Y1p66uK8dEzdYwBeUQAY7DbyYNezBfdWQ97weEtAKYQg2xJIkuveAT3dYeLGH+ShrWNwZgN0b2YL7qznr3g8JYAo5bQBziPjx7BPZ0d9RCQp4UZbnFdzBddor4XHN4KYMrB2qHFRIzzcLAHQZ5the5ovui94PCWAPefaYnxIdzRwdHCbuR4B+tbiy96Lzi8E4D7z7S0mEPd+eqO3cT53Z0Y8SV80XvB4Z0ADJi/f7X113f+7p7/+UYBvur6657/+YYBvur6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+VMA8FXWX/f8z58OgK+y/rrnf75RgLna+uue//lTA/CV1V/3/M837aKvvv6653++UQvmauuve/7nTwfAV1N/3fM/fzr24Cuuv+75nz8FFnxl9dc9//MOr/8/glixwRuUfM4AAAAASUVORK5CYII="}getSearchTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII="}};var LuminosityHighPassShader={shaderID:"luminosityHighPass",uniforms:{"tDiffuse":{value:null},"luminosityThreshold":{value:1},"smoothWidth":{value:1},"defaultColor":{value:new Color(0)},"defaultOpacity":{value:0}},vertexShader:` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`,fragmentShader:` + + uniform sampler2D tDiffuse; + uniform vec3 defaultColor; + uniform float defaultOpacity; + uniform float luminosityThreshold; + uniform float smoothWidth; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + vec3 luma = vec3( 0.299, 0.587, 0.114 ); + + float v = dot( texel.xyz, luma ); + + vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); + + float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); + + gl_FragColor = mix( outputColor, texel, alpha ); + + }`};var UnrealBloomPass=class extends Pass{constructor(resolution,strength,radius,threshold){super();this.strength=strength!==void 0?strength:1;this.radius=radius;this.threshold=threshold;this.resolution=resolution!==void 0?new Vector2(resolution.x,resolution.y):new Vector2(256,256);this.clearColor=new Color(0,0,0);this.renderTargetsHorizontal=[];this.renderTargetsVertical=[];this.nMips=5;let resx=Math.round(this.resolution.x/2);let resy=Math.round(this.resolution.y/2);this.renderTargetBright=new WebGLRenderTarget(resx,resy);this.renderTargetBright.texture.name="UnrealBloomPass.bright";this.renderTargetBright.texture.generateMipmaps=false;for(let i=0;i + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 texSize; + uniform vec2 direction; + + float gaussianPdf(in float x, in float sigma) { + return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; + } + void main() { + vec2 invSize = 1.0 / texSize; + float fSigma = float(SIGMA); + float weightSum = gaussianPdf(0.0, fSigma); + vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum; + for( int i = 1; i < KERNEL_RADIUS; i ++ ) { + float x = float(i); + float w = gaussianPdf(x, fSigma); + vec2 uvOffset = direction * invSize * x; + vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb; + vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb; + diffuseSum += (sample1 + sample2) * w; + weightSum += 2.0 * w; + } + gl_FragColor = vec4(diffuseSum/weightSum, 1.0); + }`})}getCompositeMaterial(nMips){return new ShaderMaterial({defines:{"NUM_MIPS":nMips},uniforms:{"blurTexture1":{value:null},"blurTexture2":{value:null},"blurTexture3":{value:null},"blurTexture4":{value:null},"blurTexture5":{value:null},"bloomStrength":{value:1},"bloomFactors":{value:null},"bloomTintColors":{value:null},"bloomRadius":{value:0}},vertexShader:`varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`,fragmentShader:`varying vec2 vUv; + uniform sampler2D blurTexture1; + uniform sampler2D blurTexture2; + uniform sampler2D blurTexture3; + uniform sampler2D blurTexture4; + uniform sampler2D blurTexture5; + uniform float bloomStrength; + uniform float bloomRadius; + uniform float bloomFactors[NUM_MIPS]; + uniform vec3 bloomTintColors[NUM_MIPS]; + + float lerpBloomFactor(const in float factor) { + float mirrorFactor = 1.2 - factor; + return mix(factor, mirrorFactor, bloomRadius); + } + + void main() { + gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); + }`})}};UnrealBloomPass.BlurDirectionX=new Vector2(1,0);UnrealBloomPass.BlurDirectionY=new Vector2(0,1);var PickHelper=class{constructor(){this.raycaster=new Raycaster;this.pickedObject=null;this.pickedObjectSavedColor=0}pick(normalizedPosition,scene,camera,time){if(this.pickedObject){this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);this.pickedObject=void 0}this.raycaster.setFromCamera(normalizedPosition,camera);const intersectedObjects=this.raycaster.intersectObjects(scene.children);if(intersectedObjects.length){this.pickedObject=intersectedObjects[0].object;this.pickedObjectSavedColor=this.pickedObject.material.emissive.getHex();this.pickedObject.material.emissive.setHex(time*8%2>1?16776960:16711680)}}};if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope){const worker=new WorkerService({services:{ECSService,unsafeRoutes},tree:{...workerCanvasRoutes,receiveThreeCanvas:function(options){const ThreeProps={THREE:three_module_exports,OrbitControls,EffectComposer,RenderPass,SMAAPass,UnrealBloomPass,PickHelper};Object.assign(options,ThreeProps);console.log(this);let renderId=this.__node.graph.run("setupCanvas",options);return renderId}}});worker.run("addSystems",Systems,["boid","nbody","collision","collider","movement"]);console.log(worker)}var worker_default=self;})(); +/** + * @license + * Copyright 2010-2022 Three.js Authors + * SPDX-License-Identifier: MIT + */ diff --git a/examples/loaders/3dmodel/index.html b/examples/workerthreejs/index.html similarity index 100% rename from examples/loaders/3dmodel/index.html rename to examples/workerthreejs/index.html diff --git a/examples/services/workers/workerthreejs/index.ts b/examples/workerthreejs/index.ts similarity index 99% rename from examples/services/workers/workerthreejs/index.ts rename to examples/workerthreejs/index.ts index 078e8f24..0a924106 100644 --- a/examples/services/workers/workerthreejs/index.ts +++ b/examples/workerthreejs/index.ts @@ -6,7 +6,7 @@ import { WorkerCanvasControls, htmlloader, HTMLNodeProperties -} from '../../../../index'//'graphscript' +} from '../../index'//'graphscript' import gsworker from './worker' @@ -26,7 +26,7 @@ console.log(router) document.body.style.height = '100vh' -let ret = router.load({ +let ret = router.setTree({ 'main':{ tagName:'div', __children:{ diff --git a/examples/loaders/web_components/package-lock.json b/examples/workerthreejs/package-lock.json similarity index 55% rename from examples/loaders/web_components/package-lock.json rename to examples/workerthreejs/package-lock.json index 89434d34..38072357 100644 --- a/examples/loaders/web_components/package-lock.json +++ b/examples/workerthreejs/package-lock.json @@ -1,32 +1,18 @@ { - "name": "tinybuildapp5363", + "name": "tinybuildapp261", "version": "0.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { - "name": "tinybuildapp5363", + "name": "tinybuildapp261", "version": "0.0.0", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "graphscript": "^0.2.80" - }, - "devDependencies": {} - }, - "../../../AppData/Roaming/npm/node_modules/tinybuild": { - "version": "0.3.202", - "extraneous": true, - "license": "LGPL-3.0-or-later", - "dependencies": { - "chokidar": "~3.5.3", - "esbuild": "~0.17.10", - "ws": "^8.5.0" - }, - "bin": { - "tinybuild": "tinybuild/bin/global.js" - }, - "peerDependencies": { - "typescript": "~4.9.5" + "graphscript": "~0.1.47", + "three": "^0.143.0", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.13" } }, "node_modules/better-sse": { @@ -44,27 +30,45 @@ "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" }, "node_modules/bson-objectid": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", - "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.3.tgz", + "integrity": "sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g==" }, "node_modules/graphscript": { - "version": "0.2.80", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.80.tgz", - "integrity": "sha512-TU6LLYPqpS5acZqu3+wrkwp+IWZixloVhG/UNFFbxW8OcdLFeW7rpYesmemb307UVKqkCeod9iOwgz5Cgfsl0w==", + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", "dependencies": { - "better-sse": "^0.8.0", - "brainsatplay-math": "~0.1.0", + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.11.0" } }, + "node_modules/three": { + "version": "0.143.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.143.0.tgz", + "integrity": "sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg==" + }, "node_modules/web-worker": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" }, + "node_modules/webgl-plot": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + }, + "node_modules/webgl-plot-utils": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz", + "integrity": "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==", + "dependencies": { + "webgl-plot": "~0.7.0" + } + }, "node_modules/ws": { "version": "8.11.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", @@ -98,27 +102,45 @@ "integrity": "sha512-J2s+/4osnjVVqqKVwuCuYbr9eGhXF4eFsGq/ImPIHICx0+1hJHoUN1XVCyiC8rOM7Nf0/8mmtVknzEeayVc7sQ==" }, "bson-objectid": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.4.tgz", - "integrity": "sha512-vgnKAUzcDoa+AeyYwXCoHyF2q6u/8H46dxu5JN+4/TZeq/Dlinn0K6GvxsCLb3LHUJl0m/TLiEK31kUwtgocMQ==" + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bson-objectid/-/bson-objectid-2.0.3.tgz", + "integrity": "sha512-WYwVtY9yqk179EPMNuF3vcxufdrGLEo2XwqdRVbfLVe9X6jLt7WKZQgP+ObOcprakBGbHxzl76tgTaieqsH29g==" }, "graphscript": { - "version": "0.2.80", - "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.2.80.tgz", - "integrity": "sha512-TU6LLYPqpS5acZqu3+wrkwp+IWZixloVhG/UNFFbxW8OcdLFeW7rpYesmemb307UVKqkCeod9iOwgz5Cgfsl0w==", + "version": "0.1.52", + "resolved": "https://registry.npmjs.org/graphscript/-/graphscript-0.1.52.tgz", + "integrity": "sha512-bcpmZHhLR0aVF2ZDg3jkwqHzdOBp6fMKXsrnqeM2uf24WURdzas9SriCY7jXTNA5Eci9bGhdt0tHVeZlvyt/Sg==", "requires": { - "better-sse": "^0.8.0", - "brainsatplay-math": "~0.1.0", + "better-sse": "~0.8.0", + "brainsatplay-math": "~0.0.25", "bson-objectid": "~2.0.3", "web-worker": "~1.2.0", "ws": "~8.11.0" } }, + "three": { + "version": "0.143.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.143.0.tgz", + "integrity": "sha512-oKcAGYHhJ46TGEuHjodo2n6TY2R6lbvrkp+feKZxqsUL/WkH7GKKaeu6RHeyb2Xjfk2dPLRKLsOP0KM2VgT8Zg==" + }, "web-worker": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.2.0.tgz", "integrity": "sha512-PgF341avzqyx60neE9DD+XS26MMNMoUQRz9NOZwW32nPQrF6p77f1htcnjBSEV8BGMKZ16choqUG4hyI0Hx7mA==" }, + "webgl-plot": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/webgl-plot/-/webgl-plot-0.7.0.tgz", + "integrity": "sha512-/prs3XMFKlXcov3qvx3LxqMws0Dg68kmmHmO82Qm6FFGpeKME7c3nuVqSe9CG47BvG9mGVPxDMjRc0DP/jTc2A==" + }, + "webgl-plot-utils": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/webgl-plot-utils/-/webgl-plot-utils-0.3.13.tgz", + "integrity": "sha512-uXUK4kmau2HZYrZ3gGy3olKnmYAXNAMfEIzuzD28pxQrmerxZPm73scyxeTph65l06W9gJwAB4OTDWrD5n4MWg==", + "requires": { + "webgl-plot": "~0.7.0" + } + }, "ws": { "version": "8.11.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", diff --git a/examples/services/workers/workerthreejs/package.json b/examples/workerthreejs/package.json similarity index 87% rename from examples/services/workers/workerthreejs/package.json rename to examples/workerthreejs/package.json index a456f1fd..ccbfa559 100644 --- a/examples/services/workers/workerthreejs/package.json +++ b/examples/workerthreejs/package.json @@ -1,5 +1,5 @@ { - "name": "graphscript-workerthreejs-example", + "name": "tinybuildapp261", "version": "0.0.0", "description": "Barebones esbuild and test node server implementation. For building", "main": "index.js", @@ -20,10 +20,12 @@ "esbuild" ], "author": "", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { "graphscript": "~0.1.47", - "three": "^0.143.0" + "three": "^0.143.0", + "web-worker": "^1.2.0", + "webgl-plot-utils": "^0.3.13" }, "nodemonConfig": { "env": { diff --git a/examples/services/workers/workerthreejs/tinybuild.config.js b/examples/workerthreejs/tinybuild.config.js similarity index 96% rename from examples/services/workers/workerthreejs/tinybuild.config.js rename to examples/workerthreejs/tinybuild.config.js index 2632c80c..44161dd9 100644 --- a/examples/services/workers/workerthreejs/tinybuild.config.js +++ b/examples/workerthreejs/tinybuild.config.js @@ -20,10 +20,10 @@ const config = { debug: false, protocol: "http", //'http' or 'https'. HTTPS required for Nodejs <---> Python sockets. If using http, set production to False in python/server.py as well host: "localhost", //'localhost' or '127.0.0.1' etc. - port: 8080, //e.g. port 80, 443, 8000 + port: 8081, //e.g. port 80, 443, 8000 startpage: "index.html", //home page socket_protocol: "ws", //frontend socket protocol, wss for served, ws for localhost - hotreload: 5000, //hotreload websocket server port + hotreload: 5001, //hotreload websocket server port //watch: ['../'], //watch additional directories other than the current working directory pwa: "dist/service-worker.js", //pwa mode? Injects service worker registry code in (see pwa README.md) python: false,//7000, //quart server port (configured via the python server script file still) diff --git a/examples/services/workers/workerthreejs/worker.ts b/examples/workerthreejs/worker.ts similarity index 86% rename from examples/services/workers/workerthreejs/worker.ts rename to examples/workerthreejs/worker.ts index 6ddbd4ba..0ccda170 100644 --- a/examples/services/workers/workerthreejs/worker.ts +++ b/examples/workerthreejs/worker.ts @@ -1,14 +1,14 @@ import { WorkerService, - remoteGraphRoutes, + unsafeRoutes, workerCanvasRoutes, ECSService //GPUService -} from '../../../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' +} from '../../index'/////"../../GraphServiceRouter/index";//from 'graphscript' -import {Systems} from '../../../../src/extras/index.services' +import {Systems} from '../../extras/index.services' -import { CanvasProps } from '../../../../src/services/worker/WorkerCanvas'; +import { CanvasProps } from '../../services/worker/WorkerCanvas'; import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' @@ -25,9 +25,9 @@ if(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope services:{ //GPUService, ECSService, - remoteGraphRoutes, //allows dynamic route loading + unsafeRoutes, //allows dynamic route loading }, - roots:{ + tree:{ ...workerCanvasRoutes, receiveThreeCanvas:function(options:CanvasProps){ //modified canvas receiver that installs desired threejs modules const ThreeProps = { //e.g. install these systems to 'self', which is the worker canvas diff --git a/src/extras/.npmignore b/extras/.npmignore similarity index 100% rename from src/extras/.npmignore rename to extras/.npmignore diff --git a/extras/README.md b/extras/README.md new file mode 100644 index 00000000..fd7f3143 --- /dev/null +++ b/extras/README.md @@ -0,0 +1 @@ +Keep the bloatware here so it's out of the main NPM dist \ No newline at end of file diff --git a/src/extras/___package.json b/extras/___package.json similarity index 84% rename from src/extras/___package.json rename to extras/___package.json index 1d05fe29..1d277746 100644 --- a/src/extras/___package.json +++ b/extras/___package.json @@ -1,10 +1,10 @@ { "name": "graphscript-services.gpu", - "version": "0.3.2", + "version": "0.2.7", "description": "Extra services for graphscript.", "main": "dist/index.gpu.services.js", "module": "dist/index.gpu.services.esm.js", - "types": "dist/index.gpu.services.d.ts", + "types": "dist/extras/index.gpu.services.d.ts", "scripts": { "start": "tinybuild path=tinybuild.config.js && tinybuild path=tinybuild.gpu.config.js && tinybuild path=tinybuild.storage.config.js", "build": "tinybuild build", @@ -21,12 +21,13 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", - "webgl-plot-utils":"~0.4.2", - "gpujsutils":"~1.0.15" + "bson-objectid": "~2.0.3", + "gpujsutils": "~1.0.12", + "webgl-plot-utils":"~0.3.13" }, "nodemonConfig": { "env": { diff --git a/src/extras/__package.json b/extras/__package.json similarity index 87% rename from src/extras/__package.json rename to extras/__package.json index 32f52858..8f11058d 100644 --- a/src/extras/__package.json +++ b/extras/__package.json @@ -1,6 +1,6 @@ { "name": "graphscript-services.storage", - "version": "0.3.2", + "version": "0.2.7", "description": "Extra services for graphscript.", "main": "dist/index.storage.services.js", "module": "dist/index.storage.services.esm.js", @@ -21,11 +21,13 @@ "esbuild" ], "author": "Joshua Brewster", - "license": "LGPL-3.0-or-later", + "license": "AGPL-3.0-or-later", "dependencies": { - "brainsatplay-math": "~0.1.0", + "brainsatplay-math": "~0.0.25", "browserfs": "^1.4.3", - "webgl-plot-utils":"~0.4.2" + "bson-objectid": "~2.0.4", + "gpujsutils": "~1.0.12", + "webgl-plot-utils":"~0.3.13" }, "nodemonConfig": { "env": { diff --git a/src/extras/algorithms/accel_gyro.ts b/extras/algorithms/accel_gyro.ts similarity index 62% rename from src/extras/algorithms/accel_gyro.ts rename to extras/algorithms/accel_gyro.ts index fc1c3bff..4dd3bb81 100644 --- a/src/extras/algorithms/accel_gyro.ts +++ b/extras/algorithms/accel_gyro.ts @@ -1,21 +1,23 @@ import { Math2 } from 'brainsatplay-math'; -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; //convert accelerometer and gyro data into cartesian position changes //https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/ export const accel_gyro = { - accelConstant: 1/8192, //+/-4g mpu6050 //1/16384, //+/- 2g mpu6050 - gyroConstant: 1/65.5, //500deg/s //1/131, //250deg/s mpu6050 - gyroXAngle:0, - gyroYAngle:0, - gyroZAngle:0, - px:0, - py:0, - pz:0, - sps:100, - lastAccelTime:Date.now(), - lastGyroTime:Date.now(), - __operator:function(data:{ + structs:{ + accelConstant: 1/8192, //+/-4g mpu6050 //1/16384, //+/- 2g mpu6050 + gyroConstant: 1/65.5, //500deg/s //1/131, //250deg/s mpu6050 + gyroXAngle:0, + gyroYAngle:0, + gyroZAngle:0, + px:0, + py:0, + pz:0, + sps:100, + lastAccelTime:Date.now(), + lastGyroTime:Date.now() + }, + ondata:(ctx, data:{ ax:number|number[], ay:number|number[], az:number|number[], @@ -35,7 +37,7 @@ export const accel_gyro = { gz:number|number[], [key:string]:any, timestamp?:number|number[] - }) { + })=>{ if(!('ax' in data) && !('gx' in data)) return undefined; //invalid data @@ -43,7 +45,7 @@ export const accel_gyro = { if((data.ax && Array.isArray(data.ax)) || (data.gx && Array.isArray(data.gx))) { //assume timestamp let len = data.ax ? data.ax.length : data.gx.length; let now = Date.now(); - let toInterp = [now - len*this.sps*1000, now]; + let toInterp = [now - len*ctx.sps*1000, now]; data.timestamp = Math2.upsample(toInterp,len); } else { data.timestamp = Date.now(); @@ -55,12 +57,12 @@ export const accel_gyro = { if(data.ax) { let apass = (timestamp,ax,ay,az) => { - ax = ax*this.accelConstant; //assume raw data - ay = ay*this.accelConstant; - az = az*this.accelConstant; + ax = ax*ctx.accelConstant; //assume raw data + ay = ay*ctx.accelConstant; + az = az*ctx.accelConstant; - const accelXAngle = Math.atan((ay/Math.sqrt(ax*ax)) + az*az*180/Math.PI) + this.accelXError; - const accelYAngle = Math.atan((-ax/Math.sqrt(ay*ay)) + az*az*180/Math.PI) + this.accelYError; + const accelXAngle = Math.atan((ay/Math.sqrt(ax*ax)) + az*az*180/Math.PI) + ctx.accelXError; + const accelYAngle = Math.atan((-ax/Math.sqrt(ay*ay)) + az*az*180/Math.PI) + ctx.accelYError; return { ax, @@ -79,24 +81,24 @@ export const accel_gyro = { } if(data.gx) { let gpass = (timestamp,gx,gy,gz) => { - const elapsed = timestamp - this.lastGyroTime; - this.lastGyroTime = timestamp; + const elapsed = timestamp - ctx.lastGyroTime; + ctx.lastGyroTime = timestamp; - gx = gx*this.gyroConstant+this.gyroXError; //assume raw data - gy = gy*this.gyroConstant+this.gyroYError; - gz = gz*this.gyroConstant+this.gyroZError; + gx = gx*ctx.gyroConstant+ctx.gyroXError; //assume raw data + gy = gy*ctx.gyroConstant+ctx.gyroYError; + gz = gz*ctx.gyroConstant+ctx.gyroZError; - this.gyroXAngle += gx*elapsed; - this.gyroYAngle += gy*elapsed; - this.gyroZAngle += gz*elapsed; + ctx.gyroXAngle += gx*elapsed; + ctx.gyroYAngle += gy*elapsed; + ctx.gyroZAngle += gz*elapsed; return { gx, gy, gz, - roll:this.gyroXAngle, - pitch:this.gyroYAngle, - yaw:this.gyroZAngle + roll:ctx.gyroXAngle, + pitch:ctx.gyroYAngle, + yaw:ctx.gyroZAngle } } @@ -122,26 +124,26 @@ export const accel_gyro = { result.yaw = res.yaw; } else result = res; } - } else if(this.gyroXAngle || this.gyroYAngle || this.gyroZAngle) { //e.g. if accel and gyro are reported separately (looking at you, muse O__O) - result.roll = result.roll*0.04 + this.gyroXAngle*0.96; //complementary filter - result.pitch = result.pitch*0.04 + this.gyroYAngle*0.96; - result.yaw = this.gyroXAngle; + } else if(ctx.gyroXAngle || ctx.gyroYAngle || ctx.gyroZAngle) { //e.g. if accel and gyro are reported separately (looking at you, muse O__O) + result.roll = result.roll*0.04 + ctx.gyroXAngle*0.96; //complementary filter + result.pitch = result.pitch*0.04 + ctx.gyroYAngle*0.96; + result.yaw = ctx.gyroXAngle; } //add estimated position offsets px, py, pz if(result.ax) { const setPositionOffset = (timestamp, result) => { - const elapsed = timestamp - this.lastAccelTime; - this.lastAccelTime = timestamp; + const elapsed = timestamp - ctx.lastAccelTime; + ctx.lastAccelTime = timestamp; - this.px += result.ax*elapsed*elapsed*Math.cos(this.pitch*Math.PI*0.005555555555); //correct for angle in local coordinate space - this.py += result.ay*elapsed*elapsed*Math.cos(this.roll*Math.PI*0.005555555555); - this.pz += result.az*elapsed*elapsed*Math.sin(this.pitch*Math.PI*0.005555555555); + ctx.px += result.ax*elapsed*elapsed*Math.cos(ctx.pitch*Math.PI*0.005555555555); //correct for angle in local coordinate space + ctx.py += result.ay*elapsed*elapsed*Math.cos(ctx.roll*Math.PI*0.005555555555); + ctx.pz += result.az*elapsed*elapsed*Math.sin(ctx.pitch*Math.PI*0.005555555555); - result.px = this.px; - result.py = this.py; - result.pz = this.pz; + result.px = ctx.px; + result.py = ctx.py; + result.pz = ctx.pz; return result; @@ -159,6 +161,6 @@ export const accel_gyro = { return result; } -} as GraphNodeProperties +} as SubprocessContextProps //e.g. combine with gps to get local absolute position changes \ No newline at end of file diff --git a/extras/algorithms/beat_detect.ts b/extras/algorithms/beat_detect.ts new file mode 100644 index 00000000..c01dd62b --- /dev/null +++ b/extras/algorithms/beat_detect.ts @@ -0,0 +1,225 @@ +//AlgorithmContext implementation for a basic low-pass peak finding algorithm with some basic error correction +import { Math2 } from 'brainsatplay-math'; +import { SubprocessContext, SubprocessContextProps } from '../../services/worker/Subprocess'; +import { Biquad } from './util/BiquadFilters'; + +export const beat_detect = { + structs:{ //assign key data structures to the context for reference on each pass + refdata:[] as any, + lowpass:undefined, + smoothed:[] as any, + //dsmoothed:[] as any, //slope + timestamp:[] as any, + peaks:[] as any, + valleys:[] as any, + peak_distances:[] as any, + valley_distances:[] as any, + beats:[] as any, + lastPeak:0, + lastValley:0, + sps:100, //set the sample rate, e.g. 100 + maxFreq:4, //the max frequency of peaks we want to detect, we will create a moving average and peak finding interval based on this and the sample rate. //e.g. 4hz for heart rate, or 1/3rd hz for breathing + limit:10, //limit number of last-values stored on the peak/valley/beat arrays to save memory, can just collect externally when a beat is returned + }, + oncreate:(context) => { + if(!context.lowpass) { //init lowpass filter with up to date sample rate + let freq = context.maxFreq; + if(!freq) freq = 1; + if(freq > 1) freq *= 0.5; //helps smooth more on faster sine waves, for low freqs this starts to be too smooth + + //lowpass filter constraints + context.lowpass = new Biquad('lowpass', context.maxFreq, context.sps); + + context.peakFinderWindow = Math.floor(context.sps/context.maxFreq) + if(context.peakFinderWindow%2 === 0) context.peakFinderWindow+=1; + if(context.peakFinderWindow < 5) context.peakFinderWindow = 5; + context.midpoint = Math.round(context.peakFinderWindow*.5); + + } + }, + ondata:( + context:SubprocessContext, + data:{ + //general use data key + raw?:number|number[], + + //pulse ox or fnirs data + red?:number|number[], //could be any LED really but we are using red and IR predominantly + ir?:number|number[], + heg?:number|number[], //e.g. the Peanut only gives us the HEG in a usable way + + //used for frequency finding + timestamp?:number|number[] + } + )=>{ + + if(!('red' in data) && !('heg' in data) && !('raw' in data)) return undefined; //invalid data + + let refdata = data.red ? data.red : data.heg? data.heg : data.raw; + + if(!('timestamp' in data)) { //generate timestamps if none, assuming latest data is at time of the ondata callback + if(Array.isArray(refdata)) { //assume timestamp + let now = Date.now(); + let len; + if(refdata) len = (refdata as number[]).length; + let toInterp = [now - (refdata as number[]).length*context.sps*1000, now]; + data.timestamp = Math2.upsample(toInterp,(refdata as number[]).length); + } else { + data.timestamp = Date.now(); + } + } + + let pass = (amplitude, timestamp) => { + if(amplitude) { + context.refdata.push(amplitude); + } + context.timestamp.push(timestamp); + + let beat; + + if(context.refdata.length > context.peakFinderWindow) { //we only need to store enough data in a buffer to run the algorithm (to limit buffer overflow) + context.refdata.shift(); + context.timestamp.shift(); + } + + + context.smoothed.push( + context.lowpass.applyFilter(context.refdata[context.refdata.length - 1]) + ); + + if(context.smoothed.length > context.peakFinderWindow) { + context.smoothed.shift(); + } + + + if(context.smoothed.length === context.peakFinderWindow) { + // context.dsmoothed.push( + // ( context.refdata[context.refdata.length-1] - + // context.refdata[context.refdata.length-2] + // ) / context.timestamp[context.timestamp[context.timestamp.length-1]] + // ); + + //context.smoothed.indexOf(Math.max(...context.smoothed)) === context.midpoint + if(Math2.isExtrema(context.smoothed,'valley')) { + context.valleys.push({ + value:context.smoothed[context.smoothed.length - context.midpoint ? context.midpoint : 1], + timestamp:context.timestamp[context.timestamp.length - context.midpoint ? context.midpoint : 1] + }); + } else if (Math2.isExtrema(context.smoothed,'peak')) { + context.peaks.push({ + value:context.smoothed[context.smoothed.length - context.midpoint ? context.midpoint : 1], + timestamp:context.timestamp[context.timestamp.length - context.midpoint ? context.midpoint : 1] + }); + } + + + if(context.valleys.length > 2 && context.peaks.length > 2) { + + //if we have 3+ peaks or 3+ valleys in front of the previous peak or valley, we need to shave them off as we are looking for a sine wave (1 peak 1 valley). + if(context.valleys[context.valleys.length-1].timestamp < context.peaks[context.peaks.length - 2].timestamp) + context.peaks.splice(context.peaks.length-1); + if(context.peaks[context.peaks.length-1].timestamp < context.valleys[context.valleys.length - 2].timestamp) + context.valleys.splice(context.valleys.length-1); + + context.valley_distances.push({ + distance:context.valleys[context.valleys.length - 1].timestamp - context.valleys[context.valleys.length - 2].timestamp, + timestamp:context.valleys[context.valleys.length - 1].timestamp, + peak0:context.valleys[context.valleys.length - 1].value, + peak1:context.valleys[context.valleys.length - 2].value + }); + + context.peak_distances.push({ + distance:context.peaks[context.peaks.length - 1].timestamp - context.peaks[context.peaks.length - 2].timestamp, + timestamp:context.peaks[context.peaks.length - 1].timestamp, + peak0:context.peaks[context.peaks.length - 1].value, + peak1:context.peaks[context.peaks.length - 2].value + }); + + if(context.peak_distances.length > 1 && context.valley_distances.length > 1) { + if(context.lastPeak < context.peaks[context.peaks.length-1].timestamp && context.lastValley < context.peaks[context.peaks.length-1].timestamp) { + if(context.valley_distances[context.valley_distances.length -1].timestamp > context.peak_distances[context.peak_distances.length-1].timestamp) { + let bpm, change = 0; + if(context.beats.length < 1) { + bpm = 60/(0.0005 * (context.peak_distances[context.peak_distances.length-1].distance + + context.valley_distances[context.valley_distances.length-1].distance)); + + } else if (context.beats[context.beats.length-1].timestamp !== context.peak_distances[context.peak_distances.length-1].timestamp) { + bpm = 60/(0.0005*(context.peak_distances[context.peak_distances.length-1].dt + context.valley_distances[context.valley_distances.length-1].dt)); + change = Math.abs(bpm - context.beats[context.beats.length - 1].bpm); + } + + beat = { + timestamp:context.peak_distances[context.peak_distances.length - 1].timestamp, + change, + bpm, + height0:context.peak_distances[context.peak_distances.length-1].peak0 - + context.valley_distances[context.valley_distances.length-1].peak0, + height1:context.peak_distances[context.peak_distances.length-1].peak1 - + context.valley_distances[context.valley_distances.length-1].peak1 + } + + context.beats.push(beat); + + context.lastPeak = context.peaks[context.peaks.length-1].timestamp; + context.lastValley = context.peaks[context.peaks.length-1].timestamp; + } else { + let bpm, change = 0; + if(context.beats.length < 2) { + bpm = 60/(0.0005*(context.peak_distances[context.peak_distances.length-2].distance + context.valley_distances[context.valley_distances.length-2].distance)); //(averaged peak + valley distance (msec)) * msec/sec * 60sec/min + } else if(context.beats[context.beats.length-1].timestamp !== context.peak_distances[context.peak_distances.length-2].timestamp) { + bpm = 60/(0.0005*(context.peak_distances[context.peak_distances.length-2].distance + context.valley_distances[context.valley_distances.length-2].distance)); + change = Math.abs(bpm-context.beats[context.beats.length-2].bpm); + } + + beat = { + timestamp:context.peak_distances[context.peak_distances.length-2].timestamp, + change, + bpm, + height0:context.peak_distances[context.peak_distances.length-2].peak0-context.valley_distances[context.valley_distances.length-2].peak0, + height1:context.peak_distances[context.peak_distances.length-2].peak1-context.valley_distances[context.valley_distances.length-2].peak1 + } + + context.beats.push(beat); + + context.lastPeak = context.peaks[context.peaks.length-1].timestamp; + context.lastValley = context.peaks[context.peaks.length-1].timestamp; + } + } + } + + //limits memory usage + if(context.peaks.length > context.limit) { context.peaks.shift(); } + if(context.valleys.length > context.limit) { context.valleys.shift(); } + if(context.peak_distances.length > context.limit) { context.peak_distances.shift(); } + if(context.valley_distances.length > context.limit) { context.valley_distances.shift(); } + if(context.beats.length > context.limit) { context.beats.shift(); } + + } + } + + return beat; + } + + //console.log(context); console.log(data); + + if(data.red) { + if(('ir' in data) && !Array.isArray(data.red)) return pass((data.red as number)+(data.ir as number),data.timestamp); + + let result; + if(data.ir) (data.red as number[]).map((v,i) => { return pass(v+(data as any).ir[i],(data.timestamp as number[])[i]); }); + else (data.red as number[]).map((v,i) => { return pass(v,(data.timestamp as number[])[i]); }); + return result; + + } else if (data.raw) { + if(!Array.isArray(data.raw)) return pass(data.raw,data.timestamp); + let result = data.raw.map((v,i) => { return pass(v,(data.timestamp as number[])[i]); }); + return result; + } else if (Array.isArray(data.heg)) { + if(!Array.isArray(data.heg)) return pass(data.heg,data.timestamp); + let result = data.heg.map((v,i) => { return pass(v,(data.timestamp as number[])[i]); }); + return result; + + } + //returns a beat when one is detected with the latest data passed in, else returns undefined + } +} as SubprocessContextProps; \ No newline at end of file diff --git a/extras/algorithms/blink.ts b/extras/algorithms/blink.ts new file mode 100644 index 00000000..901e53d5 --- /dev/null +++ b/extras/algorithms/blink.ts @@ -0,0 +1,62 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +import { Biquad } from './util/BiquadFilters'; +import { Math2 } from 'brainsatplay-math'; + + +export const blink_detect = { + structs:{ + sps:250, + intervals:{}, + watch:['0'], + tolerance:0.2 //absolute tolerance e.g. 0.2mV + }, + oncreate:(ctx) => { + ctx.watch.forEach((ch) => ctx.intervals[ch] = { + lowpass:new Biquad('lowpass',20,ctx.sps), + filtered:[] as number[], + averaged:[] as number[] + }) + }, + ondata:(ctx,data:{ + [key:string]:number|number[] + }) => { + let checkCt = 5; + let averageCt = 50; + + let found = {}; + let passed = false; + + + let pass = (key,n) => { + let next = ctx.intervals[key].lowpass.applyFilter(n) + ctx.intervals[key].filtered.push(next); + ctx.intervals[key].averaged.push(next); + if(ctx.intervals[key].filtered.length > checkCt) { + if(ctx.intervals[key].averaged.length > averageCt) { + ctx.intervals[key].averaged.splice(0,checkCt); + let mean = Math2.mean(ctx.intervals[key].averaged); + if(Math.abs(Math.min(...ctx.intervals[key].filtered)) > Math.abs(mean) + ctx.tolerance) { + ctx.intervals[key].filtered.length = 0; //reset + passed = true; + found[key] = true; + } + } else + ctx.intervals[key].filtered.shift(); + } + } + + + for(const key in ctx.intervals) { + if(data[key]) { + if(Array.isArray(data[key])) { + (data[key] as any).forEach((n) => { + pass(key,n); + }); + } else if(typeof data[key] === 'number') pass(key,data[key]); + } + } + + if(passed) return found; + + } +} as SubprocessContextProps \ No newline at end of file diff --git a/extras/algorithms/buffering.ts b/extras/algorithms/buffering.ts new file mode 100644 index 00000000..74514fbf --- /dev/null +++ b/extras/algorithms/buffering.ts @@ -0,0 +1,34 @@ +//we need to buffer before doing bulk blocking operations on separate threads sometimes (ffts in our case) so we are splitting this into 2 algos + +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +import { ByteParser } from './util/ByteParser'; + + +export const circularBuffer2d:SubprocessContextProps = { + structs:{ + bufferSize:250, //e.g. sps * nsec of data to buffer + watch:['0','1','2','3'], + data:{}, + blocking:false + }, + oncreate:(ctx) => { + for(const key in ctx.watch) { + ctx.data[key] = new Array(ctx.bufferSize).fill(0); + } + }, + ondata:(ctx,data) => { + + let buffer2d = [] as number[][]; + + ctx.watch.forEach((key) => { + if(data[key]) { + ByteParser.circularBuffer(ctx.data[key], data[key]) + buffer2d.push(ctx.data[key]) + } + }); + + //console.log('buffered', buffer2d) + + return buffer2d; + } +} \ No newline at end of file diff --git a/src/extras/algorithms/coherence.ts b/extras/algorithms/coherence.ts similarity index 52% rename from src/extras/algorithms/coherence.ts rename to extras/algorithms/coherence.ts index dfb96641..8308fd60 100644 --- a/src/extras/algorithms/coherence.ts +++ b/extras/algorithms/coherence.ts @@ -1,46 +1,47 @@ - -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; import { GPUService } from '../gpu/GPU.service'; if(!globalThis.gpu) globalThis.gpu = new GPUService(); // contains macros for persistent kernels (programs) on the gpu using an instance of gpujs, using the same instance lets us reuse the same kernel instances -export const coherence:GraphNodeProperties = { - sps:250, //sample rate of data - nSec:1, //number of seconds of data to buffer - freqStart:0, - freqEnd:125, //default full nyquist range - tags:['0','1','2','3'], - coherenceTags:[] as any[], - __onconnected:function (node) { - node.tags.forEach((tag,i) => { - if(i !== node.tags.length-1){ - for(let j = i+1; j < node.tags.length; j++) { - node.coherenceTags.push(node.tags[i]+'_'+node.tags[j]); +export const coherence:SubprocessContextProps = { + structs:{ + sps:250, //sample rate of data + nSec:1, //number of seconds of data to buffer + freqStart:0, + freqEnd:125, //default full nyquist range + tags:['0','1','2','3'], + coherenceTags:[] as any[] + }, + oncreate:(ctx) => { + ctx.tags.forEach((tag,i) => { + if(i !== ctx.tags.length-1){ + for(let j = i+1; j < ctx.tags.length; j++) { + ctx.coherenceTags.push(ctx.tags[i]+'_'+ctx.tags[j]); } } }) }, - __operator:function(arraybuffer) { + ondata:(ctx,arraybuffer) => { let ts = Date.now(); //console.log('buffer', arraybuffer) let results = (globalThis.gpu as GPUService).coherence( arraybuffer, - this.nSec, - this.freqStart, - this.freqEnd + ctx.nSec, + ctx.freqStart, + ctx.freqEnd ) as [number[],number[][],number[][]] //frequency (x), power spectrums (y), coherence per channel (in order of channels) let dft = {}; - this.tags.forEach((tag,i) => { + ctx.tags.forEach((tag,i) => { dft[tag] = results[1][i]; }); let coherence = {}; - this.coherenceTags.forEach((tag,i) => { + ctx.coherenceTags.forEach((tag,i) => { coherence[tag] = results[2][i]; }); diff --git a/src/extras/algorithms/dft.ts b/extras/algorithms/dft.ts similarity index 56% rename from src/extras/algorithms/dft.ts rename to extras/algorithms/dft.ts index f9356062..5796136f 100644 --- a/src/extras/algorithms/dft.ts +++ b/extras/algorithms/dft.ts @@ -1,30 +1,33 @@ -import { GraphNodeProperties } from '../../core/Graph'; +import { SubprocessContextProps } from '../../services/worker/Subprocess'; import { GPUService } from '../gpu/GPU.service'; if(!globalThis.gpu) globalThis.gpu = new GPUService(); // contains macros for persistent kernels (programs) on the gpu using an instance of gpujs, using the same instance lets us reuse the same kernel instances -export const dft:GraphNodeProperties = { - sps:250, //sample rate of data - nSec:1, //number of seconds of data to buffer - freqStart:0, - freqEnd:125, //default full nyquist range - watch:['0','1','2','3'], - blocking:false, - //__onconnected:(ctx) => {}, - __operator:function (arraybuffer) { +export const dft:SubprocessContextProps = { + structs:{ + sps:250, //sample rate of data + nSec:1, //number of seconds of data to buffer + freqStart:0, + freqEnd:125, //default full nyquist range + watch:['0','1','2','3'], + blocking:false + }, + oncreate:(ctx) => { + }, + ondata:(ctx,arraybuffer) => { //console.log('buffer', arraybuffer) let results = (globalThis.gpu as GPUService).multidftbandpass( arraybuffer, - this.nSec, - this.freqStart, - this.freqEnd, + ctx.nSec, + ctx.freqStart, + ctx.freqEnd, 1 ) as [number[],number[][],number[][]] //frequency (x), power spectrums (y), coherence per channel (in order of channels) let dft = {}; - this.watch.forEach((tag,i) => { + ctx.watch.forEach((tag,i) => { dft[tag] = results[1][i]; }); diff --git a/src/extras/algorithms/index.gpu.ts b/extras/algorithms/index.gpu.ts similarity index 100% rename from src/extras/algorithms/index.gpu.ts rename to extras/algorithms/index.gpu.ts diff --git a/src/extras/algorithms/index.ts b/extras/algorithms/index.ts similarity index 66% rename from src/extras/algorithms/index.ts rename to extras/algorithms/index.ts index 89dc133f..197080c9 100644 --- a/src/extras/algorithms/index.ts +++ b/extras/algorithms/index.ts @@ -1,13 +1,12 @@ - +import { algorithms, SubprocessContextProps } from "../../services/worker/Subprocess"; import { accel_gyro } from "./accel_gyro"; import { beat_detect } from "./beat_detect"; import { blink_detect } from './blink'; import { rms } from './rms'; import { circularBuffer2d } from './buffering'; -import { GraphNodeProperties } from "../../core/Graph"; //data in, interpretation out (with unique key:value pairs) -const algorithms = { +Object.assign(algorithms,{ beat_detect, //beat detection, set sps and maxFreq detection (for low passing) accel_gyro, //get absolute angle and position change from starting point (need magnetometer for global position, the gyro is relative) heartrate:beat_detect, //alias @@ -16,9 +15,10 @@ const algorithms = { rms, circularBuffer2d } as { - [key:string]:GraphNodeProperties -}; + [key:string]:SubprocessContextProps +}); -algorithms['breath'].maxFreq = 0.2; //another quick preset +algorithms['breath'].structs = JSON.parse( JSON.stringify( algorithms['breath'].structs )); +(algorithms['breath'].structs as any).maxFreq = 0.2; //another quick preset export { algorithms }; \ No newline at end of file diff --git a/src/extras/algorithms/pulse/2min - 2min.csv b/extras/algorithms/pulse/2min - 2min.csv similarity index 100% rename from src/extras/algorithms/pulse/2min - 2min.csv rename to extras/algorithms/pulse/2min - 2min.csv diff --git a/src/extras/algorithms/pulse/2min_dcoffset - 2min_dcoffset.csv b/extras/algorithms/pulse/2min_dcoffset - 2min_dcoffset.csv similarity index 100% rename from src/extras/algorithms/pulse/2min_dcoffset - 2min_dcoffset.csv rename to extras/algorithms/pulse/2min_dcoffset - 2min_dcoffset.csv diff --git a/src/extras/algorithms/pulse/pulseTest_html.html b/extras/algorithms/pulse/pulseTest_html.html similarity index 100% rename from src/extras/algorithms/pulse/pulseTest_html.html rename to extras/algorithms/pulse/pulseTest_html.html diff --git a/extras/algorithms/rms.ts b/extras/algorithms/rms.ts new file mode 100644 index 00000000..1c64ddc5 --- /dev/null +++ b/extras/algorithms/rms.ts @@ -0,0 +1,46 @@ +//root mean square doer thinger + +import { SubprocessContextProps } from "../../services/worker/Subprocess"; +import { ByteParser } from "./util/ByteParser"; + +export const rms:SubprocessContextProps = { + structs:{ + sps:250, //sample rate of data + nSec:1, //number of seconds of data to buffer + watch:['0','1','2','3'], + data:{}, + rms:{} + }, + //oncreate:(ctx) => { }, + ondata:(ctx,data) => { + + ctx.watch.forEach((key) => { + if(data[key]) { + if(!ctx.data[key]) { + if(Array.isArray(data[key])) { + ctx.data[key] = new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key][0]); + } else ctx.data[key] = new Array(Math.floor(ctx.sps*ctx.nSec)).fill(data[key]); + } + ByteParser.circularBuffer(ctx.data[key],data[key]); + } + }); + + if(data.timestamp) { + if(Array.isArray(data.timestamp)) { + ctx.rms.timestamp = data.timestamp[data.timestamp.length - 1]; + } else ctx.rms.timestamp = data.timestamp; + } else ctx.rms.timestamp = Date.now(); + + //console.log(ctx.rms,ctx.data); + + return new Promise(async res => { + await Promise.all(ctx.watch.map(async (key) => { + if(ctx.data[key]) ctx.rms[key] = Math.sqrt(Math.abs((ctx.data[key] as number[]).reduce((p,v,i) => p + v*v )/ctx.data[key].length)); //root mean square sum + else delete ctx.rms[key]; + })) + + res(ctx.rms); + }) + + } +} \ No newline at end of file diff --git a/src/extras/algorithms/util/ArrayManip.ts b/extras/algorithms/util/ArrayManip.ts similarity index 99% rename from src/extras/algorithms/util/ArrayManip.ts rename to extras/algorithms/util/ArrayManip.ts index 084fd3fa..dca929ef 100644 --- a/src/extras/algorithms/util/ArrayManip.ts +++ b/extras/algorithms/util/ArrayManip.ts @@ -171,7 +171,7 @@ export class ArrayManip { arr.splice( 0, len, - ...newEntries.slice(newEntries.length - len) + newEntries.slice(len-newEntries.length) ); } else { diff --git a/src/extras/algorithms/util/BiquadFilters.ts b/extras/algorithms/util/BiquadFilters.ts similarity index 100% rename from src/extras/algorithms/util/BiquadFilters.ts rename to extras/algorithms/util/BiquadFilters.ts diff --git a/src/extras/algorithms/util/ByteParser.ts b/extras/algorithms/util/ByteParser.ts similarity index 100% rename from src/extras/algorithms/util/ByteParser.ts rename to extras/algorithms/util/ByteParser.ts diff --git a/extras/dist/Graph.d.ts b/extras/dist/Graph.d.ts new file mode 100644 index 00000000..8128de4d --- /dev/null +++ b/extras/dist/Graph.d.ts @@ -0,0 +1,108 @@ +import { EventHandler } from "./services/EventHandler"; +export declare const state: EventHandler; +export declare type GraphNodeProperties = { + __props?: Function | GraphNodeProperties; + __operator?: ((...args: any[]) => any) | string; + __children?: { + [key: string]: GraphNodeProperties; + }; + __listeners?: { + [key: string]: true | string | ((result: any) => void) | { + __callback: string | ((result: any) => void) | true; + subInput?: boolean; + [key: string]: any; + }; + } | { + [key: string]: ((result: any) => void) | true | string; + }; + __onconnected?: ((node: any) => void | ((node: any) => void)[]); + __ondisconnected?: ((node: any) => void | ((node: any) => void)[]); + __node?: { + tag?: string; + state?: EventHandler; + inputState?: boolean; + [key: string]: any; + }; + [key: string]: any; +}; +export declare type Loader = (node: GraphNode, parent: Graph | GraphNode, graph: Graph, tree: any, properties: GraphNodeProperties, key: string) => void; +export declare type GraphOptions = { + tree?: { + [key: string]: any; + }; + loaders?: { + [key: string]: Loader | { + init?: Loader; + connected?: (node: any) => void; + disconnected?: (node: any) => void; + }; + }; + state?: EventHandler; + mapGraphs?: false; + [key: string]: any; +}; +export declare class GraphNode { + __node: { + [key: string]: any; + }; + __children?: any; + __operator?: any; + __listeners?: any; + __props?: any; + [key: string]: any; + constructor(properties: any, parent?: { + [key: string]: any; + }, graph?: Graph); + __subscribe: (callback: string | GraphNode | ((res: any) => void), key?: string, subInput?: boolean, bound?: string, target?: string) => any; + __unsubscribe: (sub?: number, key?: string, subInput?: boolean) => any; + __setOperator: (fn: (...args: any[]) => any) => any; + __addLocalState(props?: { + [key: string]: any; + }): void; + __proxyObject: (obj: any) => void; + __addOnconnected(callback: (node: any) => void): void; + __addOndisconnected(callback: (node: any) => void): void; + __callConnected(node?: this): void; + __callDisconnected(node?: this): void; +} +export declare class Graph { + [key: string]: any; + __node: { + tag: string; + state: EventHandler; + nodes: Map; + [key: string]: any; + }; + constructor(options?: GraphOptions); + init: (options: GraphOptions) => void; + setTree: (tree: { + [key: string]: any; + }) => { + [key: string]: any; + }; + setLoaders: (loaders: { + [key: string]: (node: GraphNode, parent: Graph | GraphNode, graph: Graph, tree: any, props: any, key: string) => void; + }, replace?: boolean) => any; + add: (properties: any, parent?: GraphNode | string) => any; + recursiveSet: (t: any, parent: any, listeners: {}, origin: any) => {}; + remove: (node: GraphNode | string, clearListeners?: boolean) => string | GraphNode; + run: (node: string | GraphNode, ...args: any[]) => any; + setListeners: (listeners: { + [key: string]: { + [key: string]: any; + }; + }) => void; + clearListeners: (node: GraphNode | string, listener?: string) => void; + get: (tag: string) => any; + set: (tag: string, node: GraphNode) => Map; + delete: (tag: string) => boolean; + getProps: (node: GraphNode | string, getInitial?: boolean) => void; + subscribe: (node: GraphNode | string, callback: string | GraphNode | ((res: any) => void), key?: string | undefined, subInput?: boolean, target?: string, bound?: string) => any; + unsubscribe: (node: GraphNode | string, sub?: number, key?: string, subInput?: boolean) => any; + setState: (update: { + [key: string]: any; + }) => void; +} +export declare function getAllProperties(obj: any): any[]; +export declare function instanceObject(obj: any): {}; +export declare function isNativeClass(thing: any): boolean; diff --git a/extras/dist/GraphServiceRouter/Graph.d.ts b/extras/dist/GraphServiceRouter/Graph.d.ts new file mode 100644 index 00000000..ff116fdd --- /dev/null +++ b/extras/dist/GraphServiceRouter/Graph.d.ts @@ -0,0 +1,214 @@ +export declare function parseFunctionFromText(method?: string): any; +export declare type OperatorType = (//can be async +...args: any) => any | void; +export declare type Tree = { + [key: string]: //the key becomes the node tag on the graph + GraphNode | Graph | //for graphs, pass an input object to the operator like so: e.g. to run a node in the graph: node.run({run:[arg1,arg2]}) + GraphNodeProperties | OperatorType | ((...args: any[]) => any | void) | ({ + aliases: string[]; + } & GraphNodeProperties); +}; +export declare type GraphNodeProperties = { + tag?: string; + operator?: OperatorType | ((...args: any[]) => any | void); + forward?: boolean; + backward?: boolean; + children?: { + [key: string]: string | boolean | undefined | GraphNodeProperties | GraphNode | Graph; + }; + parent?: GraphNode | Graph | string; + branch?: { + [label: string]: { + if: any | ((output: any) => boolean); + then: string | ((...operator_result: any[]) => any) | GraphNode; + }; + }; + tree?: Tree; + delay?: false | number; + repeat?: false | number; + recursive?: false | number; + reactive?: boolean | ((_state: { + [key: string]: any; + }) => void); + frame?: boolean; + animate?: boolean; + loop?: false | number; + animation?: OperatorType; + looper?: OperatorType; + oncreate?: (self: GraphNode | any, ...args: any[]) => void; + ondelete?: (self: GraphNode | any, ...args: any[]) => void; + DEBUGNODE?: boolean; + [key: string]: any; +}; +export declare class EventHandler { + pushToState: {}; + data: {}; + triggers: {}; + constructor(); + setState: (updateObj: { + [key: string]: any; + }) => {}; + subscribeTrigger: (key: string, onchange: (res: any) => void) => number; + unsubscribeTrigger: (key: string, sub?: number) => boolean; + subscribeTriggerOnce: (key: string, onchange: (res: any) => void) => void; +} +export declare const state: EventHandler; +/** + * Creates new instance of a GraphNode + * The methods of this class can be referenced in the operator after setup for more complex functionality + * + * ```typescript + * const graph = new GraphNode({custom: 1, operator: (input) => console.log(input, self.custom)}); + * ``` + */ +declare function addLocalState(props: any): void; +export declare class GraphNode { + nodes: Map; + _initial: { + [key: string]: any; + }; + _unique: string; + tag: string; + parent: GraphNode | Graph; + children: any; + graph: Graph; + state: EventHandler; + isLooping: boolean; + isAnimating: boolean; + looper: any; + animation: any; + forward: boolean; + backward: boolean; + reactive: boolean | ((_state: { + [key: string]: any; + }) => void); + runSync: boolean; + firstRun: boolean; + DEBUGNODE: boolean; + source: Graph | GraphNode; + tree: Tree; + [key: string]: any; + constructor(properties?: GraphNodeProperties | Graph | OperatorType | ((...args: any[]) => any | void), parent?: GraphNode | Graph | string, graph?: Graph); + addLocalState: typeof addLocalState; + operator: OperatorType; + runOp: (...args: any[]) => any; + setOperator: (operator: OperatorType) => OperatorType; + /** + * Runs the graph node and passes output to connected nodes + * + * ```typescript + * const res = await node.run(arg1, arg2, arg3); + * ``` + */ + runAsync: (...args: any[]) => Promise; + transformArgs: (args: any[], self?: GraphNode) => any[]; + isRunSync: () => boolean; + run: (...args: any[]) => any; + runParent: (n: GraphNode, ...args: any[]) => Promise; + runChildren: (n: GraphNode, ...args: any[]) => Promise; + runBranch: (n: GraphNode, output: any) => Promise; + runAnimation: (animation?: OperatorType, args?: any[]) => void; + runLoop: (loop?: OperatorType, args?: any[], timeout?: number) => void; + setParent: (parent: GraphNode) => void; + setChildren: (children: GraphNode | GraphNode[]) => void; + add: (n?: GraphNodeProperties | OperatorType | ((...args: any[]) => any | void)) => GraphNode | GraphNodeProperties; + remove: (n: string | GraphNode) => void; + append: (n: string | GraphNode, parentNode?: this) => void; + subscribe: (callback: string | GraphNode | ((res: any) => void), tag?: string) => number; + unsubscribe: (sub?: number, tag?: string) => boolean; + subscribeState: (callback: string | GraphNode | ((res: any) => void)) => number; + addChildren: (children: { + [key: string]: string | boolean | GraphNode | Graph | GraphNodeProperties; + }) => void; + callParent: (...args: any[]) => any; + callChildren: (...args: any[]) => any; + getProps: (n?: this, getInitial?: boolean) => { + tag: string; + operator: OperatorType; + graph: Graph; + children: any; + parent: GraphNode | Graph; + forward: boolean; + backward: any; + loop: any; + animate: any; + frame: any; + delay: any; + recursive: any; + repeat: any; + branch: any; + oncreate: any; + reactive: boolean | ((_state: { + [key: string]: any; + }) => void); + DEBUGNODE: boolean; + }; + setProps: (props?: GraphNodeProperties) => void; + removeTree: (n: GraphNode | string) => void; + checkNodesHaveChildMapped: (n: GraphNode | Graph, child: GraphNode, checked?: {}) => void; + convertChildrenToNodes: (n?: GraphNode) => any; + stopLooping: (n?: GraphNode) => void; + stopAnimating: (n?: GraphNode) => void; + stopNode: (n?: GraphNode) => void; + subscribeNode: (n: GraphNode | string) => number; + print: (n?: string | GraphNode, printChildren?: boolean, nodesPrinted?: any[]) => any; + reconstruct: (json: string | { + [x: string]: any; + }) => GraphNode | GraphNodeProperties; + setState: (data: { + [key: string]: any; + }) => void; + DEBUGNODES: (debugging?: boolean) => void; +} +export declare class Graph { + nNodes: number; + tag: string; + nodes: Map; + state: EventHandler; + reactive: boolean | ((_state: { + [key: string]: any; + }) => void); + _initial: any; + _unique: string; + tree: Tree; + [key: string]: any; + constructor(tree?: Tree, tag?: string, props?: { + [key: string]: any; + }); + addLocalState: typeof addLocalState; + add: (n?: GraphNode | GraphNodeProperties | OperatorType | ((...args: any[]) => any | void)) => GraphNode | GraphNodeProperties; + setTree: (tree?: Tree) => void; + get: (tag: string) => any; + set: (n: GraphNode) => Map; + run: (n: string | GraphNode, ...args: any[]) => any; + runAsync: (n: string | GraphNode, ...args: any[]) => Promise; + removeTree: (n: string | GraphNode, checked?: any) => void; + remove: (n: string | GraphNode) => string | GraphNode; + append: (n: GraphNode, parentNode: GraphNode) => void; + callParent: (n: GraphNode, ...args: any[]) => Promise; + callChildren: (n: GraphNode, ...args: any[]) => Promise; + subscribe: (n: string | GraphNode, callback: string | GraphNode | ((res: any) => void)) => number; + unsubscribe: (tag: string, sub?: number) => boolean; + subscribeState: (callback: string | GraphNode | ((res: any) => void)) => number; + subscribeNode: (inputNode: string | GraphNode, outputNode: GraphNode | string) => number; + stopNode: (n: string | GraphNode) => void; + print: (n?: GraphNode, printChildren?: boolean) => any; + reconstruct: (json: string | { + [x: string]: any; + }) => GraphNode | GraphNodeProperties; + create: (operator: OperatorType, parentNode: GraphNode, props: GraphNodeProperties) => GraphNode; + setState: (data: { + [key: string]: any; + }) => void; + DEBUGNODES: (debugging?: boolean) => void; +} +export declare function reconstructNode(json: string | { + [x: string]: any; +}, parentNode: any, graph: any): GraphNode; +export declare function reconstructObject(json?: string | { + [x: string]: any; +}): any; +export declare const stringifyWithCircularRefs: (obj: any, space?: any) => string; +export declare const stringifyFast: (obj: any, space?: any) => string; +export declare function createNode(operator: OperatorType, parentNode: GraphNode, props: GraphNodeProperties, graph: Graph): GraphNode; +export {}; diff --git a/extras/dist/GraphServiceRouter/extras/algorithms/coherence.d.ts b/extras/dist/GraphServiceRouter/extras/algorithms/coherence.d.ts new file mode 100644 index 00000000..5acffc84 --- /dev/null +++ b/extras/dist/GraphServiceRouter/extras/algorithms/coherence.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const coherence: SubprocessContextProps; diff --git a/extras/dist/GraphServiceRouter/extras/algorithms/dft.d.ts b/extras/dist/GraphServiceRouter/extras/algorithms/dft.d.ts new file mode 100644 index 00000000..82988737 --- /dev/null +++ b/extras/dist/GraphServiceRouter/extras/algorithms/dft.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const dft: SubprocessContextProps; diff --git a/extras/dist/GraphServiceRouter/extras/algorithms/index.gpu.d.ts b/extras/dist/GraphServiceRouter/extras/algorithms/index.gpu.d.ts new file mode 100644 index 00000000..d11cfebe --- /dev/null +++ b/extras/dist/GraphServiceRouter/extras/algorithms/index.gpu.d.ts @@ -0,0 +1,4 @@ +export declare const gpualgorithms: { + dft: import("../../services/worker/Subprocess").SubprocessContextProps; + coherence: import("../../services/worker/Subprocess").SubprocessContextProps; +}; diff --git a/src/extras/dist/src/extras/gpu/GPU.service.d.ts b/extras/dist/GraphServiceRouter/extras/gpu/GPU.service.d.ts similarity index 79% rename from src/extras/dist/src/extras/gpu/GPU.service.d.ts rename to extras/dist/GraphServiceRouter/extras/gpu/GPU.service.d.ts index 547ea325..099312bf 100644 --- a/src/extras/dist/src/extras/gpu/GPU.service.d.ts +++ b/extras/dist/GraphServiceRouter/extras/gpu/GPU.service.d.ts @@ -1,14 +1,14 @@ -import { Service } from "../../services/Service"; +import { Routes, Service, ServiceOptions } from "../../services/Service"; import { gpuUtils } from 'gpujsutils'; export declare class GPUService extends Service { gpu: gpuUtils; - constructor(options?: any); + constructor(options?: ServiceOptions); addFunc: (fn: string | Function) => void; addKernel: (name: string, fn: string | Function, options?: any) => void; - combineKernels: (name: string, fs: (string | Function)[], ckrnl?: () => void) => void; callKernel: (name: string, ...args: any[]) => void; dft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; multidft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; multidftbandpass: (buffered: number[][], nSeconds: number, freqStart: number, freqEnd: number, scalar?: number) => any; coherence: (buffered: number[][], nSeconds: number, freqStart: number, freqEnd: number) => any[]; + routes: Routes; } diff --git a/src/extras/dist/extras/index.gpu.services.d.ts b/extras/dist/GraphServiceRouter/extras/index.gpu.services.d.ts similarity index 100% rename from src/extras/dist/extras/index.gpu.services.d.ts rename to extras/dist/GraphServiceRouter/extras/index.gpu.services.d.ts diff --git a/extras/dist/GraphServiceRouter/services/Service.d.ts b/extras/dist/GraphServiceRouter/services/Service.d.ts new file mode 100644 index 00000000..5fe51119 --- /dev/null +++ b/extras/dist/GraphServiceRouter/services/Service.d.ts @@ -0,0 +1,78 @@ +/// +import { Graph, GraphNode, GraphNodeProperties, OperatorType } from "../Graph"; +/** + * + * A service extends acyclic graph to enhance networking operations and aggregate for our microservices + * + */ +export declare type RouteProp = { + get?: ((...args: any) => any | void); + post?: OperatorType | ((...args: any[]) => any | void); + put?: (...args: any) => any | void; + head?: (...args: any) => any | void; + delete?: (...args: any) => any | void; + patch?: (...args: any) => any | void; + options?: (...args: any) => any | void; + connect?: (...args: any) => any | void; + trace?: (...args: any) => any | void; + aliases?: string[]; +} & GraphNodeProperties; +export declare type Class = { + new (...args: any[]): any; +}; +export declare type Route = GraphNode | GraphNodeProperties | Graph | Service | OperatorType | ((...args: any[]) => any | void) | ({ + aliases?: string[]; +} & GraphNodeProperties) | RouteProp | Class | any; +export declare type Routes = { + [key: string]: Route; +}; +export declare type ServiceMessage = { + route?: string; + args?: any; + method?: string; + node?: string | GraphNode; + [key: string]: any; +}; +export declare type ServiceOptions = { + routes?: Routes | Routes[]; + name?: string; + props?: { + [key: string]: any; + }; + loadDefaultRoutes?: boolean; + includeClassName?: boolean; + routeFormat?: string; + customRoutes?: { + [key: string]: (route: Route, routeKey: string, routes: Routes) => Route | any | void; + }; + customChildren?: { + [key: string]: (child: Route, childRouteKey: string, parent: Route, routes: Routes, checked: Routes) => Route | any | void; + }; + sharedState?: boolean; + [key: string]: any; +}; +export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export declare class Service extends Graph { + routes: Routes; + loadDefaultRoutes: boolean; + keepState: boolean; + firstLoad: boolean; + customRoutes: any; + customChildren: any; + constructor(options?: ServiceOptions); + init: (options?: ServiceOptions) => void; + load: (routes?: any, includeClassName?: boolean, routeFormat?: string, customRoutes?: ServiceOptions["customRoutes"], customChildren?: ServiceOptions["customChildren"], sharedState?: boolean) => Routes; + unload: (routes?: Service | Routes | any) => Routes; + handleMethod: (route: string, method: string, args?: any) => any; + handleServiceMessage(message: ServiceMessage): any; + handleGraphNodeCall(route: string | GraphNode, args: any): any; + transmit: (...args: any[]) => any | void; + receive: (...args: any[]) => any | void; + pipe: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => number; + pipeOnce: (source: GraphNode | string, destination: string, endpoint?: string | any, method?: string, callback?: (res: any) => any | void) => void; + terminate: (...args: any) => void; + isTypedArray(x: any): boolean; + recursivelyAssign: (target: any, obj: any) => any; + spliceTypedArray(arr: TypedArray, start: number, end?: number): TypedArray; + defaultRoutes: Routes; +} diff --git a/extras/dist/GraphServiceRouter/services/unsafe/Unsafe.service.d.ts b/extras/dist/GraphServiceRouter/services/unsafe/Unsafe.service.d.ts new file mode 100644 index 00000000..fecbf4b8 --- /dev/null +++ b/extras/dist/GraphServiceRouter/services/unsafe/Unsafe.service.d.ts @@ -0,0 +1,25 @@ +export declare const unsafeRoutes: { + setRoute: (fn: string | (() => any), fnName?: string) => boolean; + setNode: (fn: string | (() => any), fnName?: string) => boolean; + setMethod: (route: string, fn: string | (() => any), fnName?: string) => boolean; + assignRoute: (route: string, source: { + [key: string]: any; + }) => void; + transferClass: (classObj: any, className?: string) => false | { + route: string; + args: any[]; + }; + receiveClass: (stringified: string, className?: string) => boolean; + setGlobal: (key: string, value: any) => boolean; + assignGlobalObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setValue: (key: string, value: any) => boolean; + assignObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setGlobalFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToGlobalObject: (globalObjectName: string, fn: any, fnName: any) => boolean; + setFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToObject: (objectName: string, fn: any, fnName: any) => boolean; +}; diff --git a/extras/dist/GraphServiceRouter/services/worker/Subprocess.d.ts b/extras/dist/GraphServiceRouter/services/worker/Subprocess.d.ts new file mode 100644 index 00000000..9963fd85 --- /dev/null +++ b/extras/dist/GraphServiceRouter/services/worker/Subprocess.d.ts @@ -0,0 +1,127 @@ +import { WorkerInfo, WorkerService } from './Worker.service'; +export declare type Subprocess = (context: SubprocessContext, data: { + [key: string]: any; +} | any) => { + [key: string]: any; +} | undefined; +export declare type SubprocessContextProps = { + ondata: Subprocess; + oncreate?: (context: SubprocessContext) => void; + structs?: { + [key: string]: any; + }; + [key: string]: any; +}; +export declare type SubprocessContext = { + ondata: Subprocess; + oncreate?: (context: SubprocessContext) => void; + run?: (data: { + [key: string]: any; + } | any) => any; + [key: string]: any; +}; +export declare type SubprocessWorkerProps = { + subprocess: string | { + name: string; + structs: {}; + oncreate: string | ((ctx: SubprocessContext) => void); + ondata: string | ((context: any, data: { + [key: string]: any; + } | any) => { + [key: string]: any; + } | undefined); + props?: { + [key: string]: any; + }; + }; + subscribeRoute: string; + source?: WorkerInfo; + route: string; + init?: string; + initArgs?: any[]; + otherArgs?: any[]; + callback?: string | ((data: any) => any); + pipeTo?: { + worker?: WorkerInfo; + portId?: string; + route: string; + otherArgs?: any[]; + init?: string; + initArgs?: any[]; + }; + worker?: WorkerInfo; + url?: any; + stopped?: boolean; +}; +export declare type SubprocessWorkerInfo = { + sub: number; + blocking?: boolean; + stop: () => void; + start: () => void; + terminate: () => void; + setArgs: (args: any[] | { + [key: string]: any; + }) => void; +} & SubprocessWorkerProps; +export declare const algorithms: { + [key: string]: SubprocessContextProps; +}; +export declare const loadAlgorithms: (settings: { + [key: string]: SubprocessContextProps; +}) => { + [key: string]: SubprocessContextProps; +} & { + [key: string]: SubprocessContextProps; +}; +export declare function createSubprocess(options: SubprocessContextProps, inputs?: { + [key: string]: any; +}): SubprocessContext; +export declare const subprocessRoutes: { + loadAlgorithms: (settings: { + [key: string]: SubprocessContextProps; + }) => { + [key: string]: SubprocessContextProps; + } & { + [key: string]: SubprocessContextProps; + }; + initSubprocesses: (subprocesses: { + [key: string]: SubprocessWorkerProps; + }, service?: WorkerService) => Promise<{ + [key: string]: SubprocessWorkerInfo; + }>; + addSubprocessTemplate: (name: string, structs: {}, oncreate: string | ((ctx: SubprocessContext) => void), ondata: string | ((context: any, data: any) => { + [key: string]: any; + }), props?: { + [key: string]: any; + }) => boolean; + updateSubprocess: (structs: {}, _id?: string) => void; + createSubprocess: (options: SubprocessContextProps | string, inputs?: { + [key: string]: any; + }) => any; + runSubprocess: (data: { + [key: string]: any; + }, _id?: string) => any; + setRoute: (fn: string | (() => any), fnName?: string) => boolean; + setNode: (fn: string | (() => any), fnName?: string) => boolean; + setMethod: (route: string, fn: string | (() => any), fnName?: string) => boolean; + assignRoute: (route: string, source: { + [key: string]: any; + }) => void; + transferClass: (classObj: any, className?: string) => false | { + route: string; + args: any[]; + }; + receiveClass: (stringified: string, className?: string) => boolean; + setGlobal: (key: string, value: any) => boolean; + assignGlobalObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setValue: (key: string, value: any) => boolean; + assignObject: (target: string, source: { + [key: string]: any; + }) => boolean; + setGlobalFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToGlobalObject: (globalObjectName: string, fn: any, fnName: any) => boolean; + setFunction: (fn: any, fnName?: string) => boolean; + assignFunctionToObject: (objectName: string, fn: any, fnName: any) => boolean; +}; diff --git a/src/extras/dist/services/worker/Worker.service.d.ts b/extras/dist/GraphServiceRouter/services/worker/Worker.service.d.ts similarity index 63% rename from src/extras/dist/services/worker/Worker.service.d.ts rename to extras/dist/GraphServiceRouter/services/worker/Worker.service.d.ts index 9539bb89..c0e49bf9 100644 --- a/src/extras/dist/services/worker/Worker.service.d.ts +++ b/extras/dist/GraphServiceRouter/services/worker/Worker.service.d.ts @@ -1,9 +1,10 @@ -import { Service, ServiceMessage, ServiceOptions } from "../Service"; +import { Service, Routes, ServiceMessage, ServiceOptions } from "../Service"; import Worker from 'web-worker'; -import { GraphNode, GraphNodeProperties } from "../../core/Graph"; -export type WorkerRoute = { +import { GraphNodeProperties } from "../../Graph"; +export declare type WorkerRoute = { worker?: WorkerInfo; workerUrl?: string | URL | Blob; + workerId?: string; transferFunctions?: { [key: string]: Function; }; @@ -19,8 +20,8 @@ export type WorkerRoute = { initArgs?: any[]; initTransfer?: any[]; } & GraphNodeProperties & WorkerProps; -export type WorkerProps = { - worker?: WorkerInfo; +export declare type WorkerProps = { + worker: WorkerInfo; workerUrl?: string | URL | Blob; url?: URL | string | Blob; _id?: string; @@ -29,13 +30,13 @@ export type WorkerProps = { onerror?: (ev: any) => void; onclose?: (worker: Worker | MessagePort) => void; }; -export type WorkerInfo = { +export declare type WorkerInfo = { worker: Worker | MessagePort; send: (message: any, transfer?: any) => void; - request: (message: any, method?: string, transfer?: any) => Promise; - post: (route: any, args?: any, method?: string, transfer?: any) => void; - run: (route: any, args?: any, method?: string, transfer?: any) => Promise; - subscribe: (route: any, callback?: ((res: any) => void) | string, args?: any[], key?: string, subInput?: boolean, blocking?: boolean) => Promise; + request: (message: any, transfer?: any, method?: string) => Promise; + post: (route: any, args?: any, transfer?: any) => void; + run: (route: any, args?: any, transfer?: any, method?: string) => Promise; + subscribe: (route: any, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; unsubscribe: (route: any, sub: number) => Promise; start: (route?: any, portId?: string, callback?: ((res: any) => void) | string, blocking?: boolean) => Promise; stop: (route?: string, portId?: string) => Promise; @@ -49,7 +50,7 @@ export type WorkerInfo = { }; }; terminate: () => boolean; - postMessage: (message: any, transfer?: any[]) => void; + postMessage: (message: any, transfer: any[]) => void; graph: WorkerService; _id: string; } & WorkerProps & WorkerRoute; @@ -59,11 +60,16 @@ export declare class WorkerService extends Service { [key: string]: WorkerInfo; }; threadRot: number; - connections: any; + connections: { + workers: { + [key: string]: WorkerInfo; + }; + }; constructor(options?: ServiceOptions); - loadWorkerRoute: (node: WorkerRoute & GraphNode, routeKey: string) => WorkerInfo; - workerloader: any; - addDefaultMessageListener: () => void; + loadWorkerRoute(rt: WorkerRoute, routeKey: string): WorkerInfo; + customRoutes: ServiceOptions["customRoutes"]; + customChildren: ServiceOptions["customChildren"]; + addDefaultMessageListener(): void; postMessage: (message: any, target: string, transfer?: Transferable[]) => void; addWorker: (options: { url?: URL | string | Blob; @@ -72,24 +78,19 @@ export declare class WorkerService extends Service { onmessage?: (ev: any) => void; onerror?: (ev: any) => void; }) => WorkerInfo; - open: (options: { - url?: URL | string | Blob; - port?: MessagePort; - _id?: string; - onmessage?: (ev: any) => void; - onerror?: (ev: any) => void; - }) => WorkerInfo; - close: () => void; toObjectURL: (scriptTemplate: string) => string; getTransferable(message: any): any; - transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: StructuredSerializeOptions) => any; - terminate: (worker: Worker | MessagePort | string | WorkerInfo) => boolean; + transmit: (message: ServiceMessage | any, worker?: Worker | MessagePort | string, transfer?: any) => any; + terminate: (worker: Worker | MessagePort | string) => boolean; establishMessageChannel: (worker: Worker | string | MessagePort | WorkerInfo, worker2?: Worker | string | MessagePort | WorkerInfo) => string | false; request: (message: ServiceMessage | any, workerId: string, transfer?: any, method?: string) => Promise; - runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number, getTransferable?: boolean) => any; - subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => number; - subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), args?: any[], key?: string, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; + runRequest: (message: ServiceMessage | any, worker: undefined | string | Worker | MessagePort, callbackId: string | number) => any; + subscribeWorker: (route: string, worker: WorkerInfo | Worker | string | MessagePort, blocking?: boolean) => number; + subscribeToWorker: (route: string, workerId: string, callback?: string | ((res: any) => void), blocking?: boolean) => Promise; triggerSubscription: (route: string, workerId: string, result: any) => Promise; - pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, args?: any[], key?: any, subInput?: boolean, blocking?: boolean, getTransferable?: boolean) => Promise; + pipeWorkers: (sourceWorker: WorkerInfo | string, listenerWorker: WorkerInfo | string, sourceRoute: string, listenerRoute: string, portId?: string, blocking?: boolean) => Promise; unpipeWorkers: (sourceRoute: string, sourceWorker: WorkerInfo | string, sub?: number) => Promise; + transferFunction(worker: WorkerInfo, fn: Function, fnName?: string): Promise; + transferClass(worker: WorkerInfo, cls: Function, className?: string): Promise; + routes: Routes; } diff --git a/extras/dist/Loaders.d.ts b/extras/dist/Loaders.d.ts new file mode 100644 index 00000000..c91cf5c1 --- /dev/null +++ b/extras/dist/Loaders.d.ts @@ -0,0 +1,67 @@ +import { GraphNode, Graph, GraphNodeProperties } from "./Graph"; +/** + * setting nodeA.__node.backward:true propagates operator results to parent + */ +export declare const backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** + * + * Specify a timer loop, will stop when node is popped or nodeA.__node.isLooping is set false + * nodeA.__node.loop = 100 will loop the operator every 100 milliseconds + * + * Or + * nodeA.__node.delay will delay the operator by specified millisecond number and resolve the result as a promise + * nodeA.__node.frame will use requestAnimationFrame to call the function and resolve the result as a promise + * + * Use in combination with: + * nodeA.__node.repeat will repeat the operator the specified number of times + * nodeA.__node.recursive will do the same as repeat but will pass in the previous operator call's results + * + * + */ +export declare const loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Animations + * + * nodeA.__node.animate = true | () => void, to run the operator or a specified animation function on loop + * + */ +export declare const animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Branching operations + * + * nodeA.__node.branch = {[key:string]:{if:Function|any, then:Function|any|GraphNode}} + * + * nodeA.__listeners['nodeB.x'] = { + * callback:(result)=>void, + * branch:{if:Function|any, then:Function|any|GraphNode} + * } + * + */ +export declare const branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Trigger listeners oncreate with specific arguments + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, oncreate:any } + * + */ +export declare const triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** Trigger listeners oncreate with specific arguments + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, binding:{[key:string]:any} } + * + */ +export declare const bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +/** + * + * nodeA.__listeners['nodeB.x'] = { callback:(result)=>void, transform:(result)=>any } + * + */ +export declare const transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; +export declare const substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; +export declare const loaders: { + backprop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + loop: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + animate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + branching: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + triggerListenerOncreate: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + bindListener: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + transformListenerResult: (node: GraphNode, parent: GraphNode | Graph, graph: Graph) => void; + substitute__operator: (node: GraphNode & GraphNodeProperties, parent: GraphNode | Graph, graph: Graph) => void; +}; diff --git a/extras/dist/Worker.js b/extras/dist/Worker.js new file mode 100644 index 00000000..b783739c --- /dev/null +++ b/extras/dist/Worker.js @@ -0,0 +1 @@ +(()=>{var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_browser=__commonJS({"../node_modules/web-worker/cjs/browser.js"(exports,module){module.exports=Worker}});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var import_web_worker=__toESM(require_browser());var WorkerService=class extends Service{constructor(options){super();this.name="worker";this.workers={};this.threadRot=0;this.loadWorkerRoute=(rt,routeKey)=>{if(rt.workerUrl)rt.url=rt.workerUrl;if(rt.workerId)rt.__node.tag=rt.workerId;if(!rt.__node.tag)rt.__node.tag=routeKey;rt._id=rt.__node.tag;let worker;if(this.workers[rt._id])worker=this.workers[rt._id];else if(rt.worker)worker=rt.worker;if(!worker){worker=this.addWorker(rt);let ondelete=rt2=>{rt2.worker?.terminate()};rt.__addOndisconnected(ondelete)}rt.worker=worker;if(rt.transferFunctions){for(const prop in rt.transferFunctions){this.transferFunction(worker,rt.transferFunctions[prop],prop)}}if(rt.transferClasses){for(const prop in rt.transferClasses){this.transferClass(worker,rt.transferClasses[prop],prop)}}if(worker){if(!rt.__operator){rt.__operator=(...args)=>{if(rt.callback){if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.post(rt.callback,args);else return worker.run(rt.callback,args)}else{if(!this.__node.nodes.get(rt.__node.tag)?.__children)worker.send(args);else return worker.request(args)}}}if(rt.init){worker.run(rt.init,rt.initArgs,rt.initTransfer)}return worker}};this.workerloader={"workers":(node,parent2,graph,tree)=>{let rt=node;if(!node.parentRoute&&(parent2?.callback&&parent2?.worker))node.parentRoute=parent2?.callback;if(rt?.worker||rt?.workerId||rt?.workerUrl){let worker=this.loadWorkerRoute(rt,rt.__node.tag);if(worker){if(!rt.parentRoute&&rt.__parent?.callback)rt.parentRoute=rt.__parent.callback;if(rt.__parent&&!rt.portId){if(typeof rt.__parent==="string"){if(rt.__node.tag!==rt.__parent&&worker._id!==rt.__parent)rt.portId=this.establishMessageChannel(worker,rt.__parent)}else if(rt.__node.tag!==rt.__parent?.__node?.tag&&worker._id!==rt.__parent.tag){rt.portId=this.establishMessageChannel(worker,rt.__parent.worker)}};if(rt.parentRoute){if(!rt.stopped){if(typeof rt.__parent==="string"&&rt.__parent===worker._id){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else if(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag){worker.run("subscribe",[rt.parentRoute,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.parentRoute,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.parentRoute+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id)&&!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.parentRoute+rt.portId]={sub:null,route:rt.parentRoute,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent){if(typeof rt.__parent==="string"){if(!rt.stopped){if(rt.__parent===worker._id){worker.run("subscribe",[rt.__parent,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent+rt.portId].sub=sub})}if(!(typeof rt.__parent==="string"&&rt.__parent===worker._id))worker.workerSubs[rt.__parent+rt.portId]={sub:null,route:worker._id,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}else if(rt.__parent?.__node?.tag&&rt.__parent?.worker){if(!rt.stopped){if(rt.__node.tag===rt.__parent.__node.tag||worker._id===rt.__parent.__node.tag){worker.run("subscribe",[rt.__parent.__node.tag,void 0,rt.callback])}else worker.run("subscribeToWorker",[rt.__parent.__node.tag,rt.portId,rt.callback,rt.blocking]).then(sub=>{worker.workerSubs[rt.__parent.__node.tag+rt.portId].sub=sub})}if(!(rt.__node.tag===rt.__parent?.__node?.tag||worker._id===rt.__parent?.__node?.tag))worker.workerSubs[rt.__parent.__node.tag+rt.portId]={sub:null,route:rt.__parent.__node.tag,portId:rt.portId,callback:rt.callback,blocking:rt.blocking}}}}}else if(rt.__parent&&rt.parentRoute){if(typeof rt.__parent==="string"&&tree[rt.__parent]?.worker){tree[rt.__parent].worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}else if(rt.__parent?.worker){rt.__parent.worker.subscribe(rt.parentRoute,rt.__operator,rt.blocking)}}return rt}};this.addDefaultMessageListener=()=>{globalThis.onmessage=ev2=>{let result=this.receive(ev2.data);if(this.__node.keepState)this.setState({[this.name]:result})}};this.postMessage=(message,target,transfer)=>{if(this.workers[target]){this.workers[target].send(message,transfer)}else{globalThis.postMessage(message,target,transfer)}};this.addWorker=options=>{let worker;if(!options._id)options._id=`worker${Math.floor(Math.random()*1e15)}`;if(options.url)worker=new import_web_worker.default(options.url);else if(options.port){worker=options.port}else if(this.workers[options._id]){if(this.workers[options._id].port)worker=this.workers[options._id].port;else worker=this.workers[options._id].worker}if(!worker)return;let send=(message,transfer)=>{return this.transmit(message,worker,transfer)};let post=(route,args,transfer,method)=>{let message={route,args};if(method)message.method=method;return this.transmit(message,worker,transfer)};let run=(route,args,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[{route,args},options._id,callbackId]};if(method)req.args[0].method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let request=(message,transfer,method)=>{return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,options._id,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};let workerSubs={};let subscribe=(route,callback,blocking)=>{return this.subscribeToWorker(route,options._id,callback,blocking)};let unsubscribe=(route,sub)=>{return run("unsubscribe",[route,sub])};let start=async(route,portId,callback,blocking)=>{if(route)await run("subscribeToWorker",[route,portId,callback,blocking]).then(sub=>{if(sub)workerSubs[route+portId]={sub,route,portId,callback,blocking}});else for(const key in workerSubs){if(typeof workerSubs[key].sub!=="number")await run("subscribeToWorker",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].callback,workerSubs[key].blocking]).then(sub=>{workerSubs[key].sub=sub})}return true};let stop=async(route,portId)=>{if(route&&portId&&workerSubs[route+portId]){await run("unsubscribe",[route,workerSubs[route+portId].sub]);workerSubs[route+portId].sub=false}else{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){await run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}}return true};let terminate=()=>{for(const key in workerSubs){if(typeof workerSubs[key].sub==="number"){run("unpipeWorkers",[workerSubs[key].route,workerSubs[key].portId,workerSubs[key].sub])}workerSubs[key].sub=false}return this.terminate(options._id)};if(!options.onmessage)options.onmessage=ev2=>{this.receive(ev2.data);this.setState({[options._id]:ev2.data})};if(!options.onerror){options.onerror=ev2=>{console.error(ev2.data)}}worker.onmessage=options.onmessage;worker.onerror=options.onerror;this.workers[options._id]={worker,send,post,run,request,subscribe,unsubscribe,terminate,start,stop,postMessage:worker.postMessage,workerSubs,graph:this,...options};return this.workers[options._id]};this.toObjectURL=scriptTemplate=>{let blob=new Blob([scriptTemplate],{type:"text/javascript"});return URL.createObjectURL(blob)};this.transmit=(message,worker,transfer)=>{if(!transfer){transfer=this.getTransferable(message)}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){worker.postMessage(message,transfer)}else if(typeof worker==="string"){if(this.workers[worker]){if(this.workers[worker].port)this.workers[worker].port.postMessage(message,transfer);else if(this.workers[worker].worker)this.workers[worker].worker.postMessage(message,transfer)}}else{let keys=Object.keys(this.workers);this.workers[keys[this.threadRot]].worker.postMessage(message,transfer);this.threadRot++;if(this.threadRot===keys.length)this.threadRot=0}return message};this.terminate=worker=>{let onclose;if(typeof worker==="string"){let obj=this.workers[worker];if(obj){delete this.workers[worker];worker=obj.worker;if(obj.onclose)onclose=obj.onclose}}if(worker instanceof import_web_worker.default){worker.terminate();if(onclose)onclose(worker);return true}if(worker instanceof MessagePort){worker.close();if(onclose)onclose(worker);return true}return false};this.establishMessageChannel=(worker,worker2)=>{let workerId;if(typeof worker==="string"){workerId=worker;if(this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker2=this.workers[worker].worker}}else if(worker?.worker){worker=worker.worker}if(typeof worker2==="string"){if(this.workers[worker2]){if(this.workers[worker2].port)worker2=this.workers[worker2].port;else worker2=this.workers[worker2].worker}}else if(worker2?.worker){worker2=worker2.worker}if(worker instanceof import_web_worker.default||worker instanceof MessagePort){let channel=new MessageChannel;let portId=`port${Math.floor(Math.random()*1e15)}`;worker.postMessage({route:"addWorker",args:{port:channel.port1,_id:portId}},[channel.port1]);if(worker2 instanceof import_web_worker.default||worker2 instanceof MessagePort){worker2.postMessage({route:"addWorker",args:{port:channel.port2,_id:portId}},[channel.port2])}else if(workerId&&this.workers[workerId]){channel.port2.onmessage=this.workers[workerId].onmessage;this.workers[workerId].port=channel.port2}return portId}return false};this.request=(message,workerId,transfer,method)=>{let worker=this.workers[workerId].worker;return new Promise((res,rej)=>{let callbackId=Math.random();let req={route:"runRequest",args:[message,callbackId]};if(method)req.method=method;let onmessage=ev2=>{if(typeof ev2.data==="object"){if(ev2.data.callbackId===callbackId){worker.removeEventListener("message",onmessage);res(ev2.data.args)}}};worker.addEventListener("message",onmessage);this.transmit(req,worker,transfer)})};this.runRequest=(message,worker,callbackId)=>{let res=this.receive(message);if(typeof worker==="string"&&this.workers[worker]){if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}if(res instanceof Promise){res.then(r=>{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:r,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:r,callbackId})})}else{if(worker instanceof import_web_worker.default||worker instanceof MessagePort)worker.postMessage({args:res,callbackId});else if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)globalThis.postMessage({args:res,callbackId})}return res};this.subscribeWorker=(route,worker,blocking,key,subInput)=>{let callback;if(blocking){let blocked=false;callback=res=>{if(!blocked){blocked=true;if(res instanceof Promise){res.then(r=>{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,r]).then(ret=>{blocked=false})})}else{if(worker?.run)worker.run("triggerSubscription",[route,worker._id,res]).then(ret=>{blocked=false})}}}}else{callback=res=>{if(res instanceof Promise){res.then(r=>{if(worker?.postMessage)worker.postMessage({args:r,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:r,callbackId:route})})}else{if(worker?.postMessage)worker.postMessage({args:res,callbackId:route});else if(globalThis.postMessage)globalThis.postMessage({args:res,callbackId:route})}}}if(!blocking&&worker?.port){worker=worker.port}else if(!blocking&&worker?.worker){worker=worker.worker}else if(typeof worker==="string"&&this.workers[worker]){if(blocking)worker=this.workers[worker];else if(this.workers[worker].port)worker=this.workers[worker].port;else worker=this.workers[worker].worker}return this.subscribe(route,callback,key,subInput)};this.subscribeToWorker=(route,workerId,callback,blocking,key,subInput)=>{if(typeof workerId==="string"&&this.workers[workerId]){this.__node.state.subscribeTrigger(workerId,res=>{if(res?.callbackId===route){if(!callback)this.setState({[workerId]:res.args});else if(typeof callback==="string"){this.run(callback,res.args)}else callback(res.args)}});return this.workers[workerId].run("subscribeWorker",[route,workerId,blocking,key,subInput])}};this.triggerSubscription=async(route,workerId,result)=>{if(this.__node.state.triggers[workerId])for(let i=0;i{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(typeof listenerWorker==="string")listenerWorker=this.workers[listenerWorker];if(!portId){portId=this.establishMessageChannel(sourceWorker.worker,listenerWorker.worker)}return listenerWorker.run("subscribeToWorker",[sourceRoute,portId,listenerRoute,blocking])};this.unpipeWorkers=(sourceRoute,sourceWorker,sub)=>{if(typeof sourceWorker==="string")sourceWorker=this.workers[sourceWorker];if(sourceWorker)return sourceWorker.run("unsubscribe",[sourceRoute,sub])};this.connections={workers:this.workers};if(options?.services)this.addServices(options.services);this.setTree(this);this.setLoaders(this.workerloader);if(options)this.init(options);if(typeof WorkerGlobalScope!=="undefined"&&globalThis instanceof WorkerGlobalScope){this.addDefaultMessageListener()}}getTransferable(message){let transfer;if(typeof message==="object"){if(message.args){if(message.args?.constructor?.name==="Object"){for(const key in message.args){if(ArrayBuffer.isView(message.args[key])){if(!transfer)transfer=[message.args[key].buffer];else transfer.push(message.args[key].buffer)}else if(message.args[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message.args[key]];else transfer.push(message.args[key])}}}else if(Array.isArray(message.args)&&message.args.length<11){message.args.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg?.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message.args)){transfer=[message.args.buffer]}else if(message.args?.constructor?.name==="ArrayBuffer"){transfer=[message]}}else if(message?.constructor?.name==="Object"){for(const key in message){if(ArrayBuffer.isView(message[key])){if(!transfer)transfer=[message[key].buffer];else transfer.push(message[key].buffer)}else if(message[key]?.constructor?.name==="ArrayBuffer"){if(!transfer)transfer=[message[key]];else transfer.push(message[key])}}}else if(Array.isArray(message)&&message.length<11){message.forEach(arg=>{if(ArrayBuffer.isView(arg)){transfer=[arg.buffer]}else if(arg.constructor?.name==="ArrayBuffer")transfer=[arg]})}else if(ArrayBuffer.isView(message)){transfer=[message.buffer]}else if(message.constructor?.name==="ArrayBuffer"){transfer=[message]}}return transfer}transferFunction(worker,fn,fnName){if(!fnName)fnName=fn.name;return worker.request({route:"setRoute",args:[fn.toString(),fnName]})}transferClass(worker,cls,className){if(!className)className=cls.name;return worker.request({route:"receiveClass",args:[cls.toString(),className]})}};var mouseEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","button","pointerType","clientX","clientY","pageX","pageY"]);var wheelEventHandlerImpl=makeSendPropertiesHandler(["deltaX","deltaY"]);var keydownEventHandler=makeSendPropertiesHandler(["ctrlKey","metaKey","shiftKey","keyCode"]);function wheelEventHandler(event,sendFn){event.preventDefault();wheelEventHandlerImpl(event,sendFn)}function preventDefaultHandler(event){event.preventDefault()}function copyProperties(src,properties,dst){for(const name of properties){dst[name]=src[name]}}function makeSendPropertiesHandler(properties){return function sendProperties(event,sendFn){const data={type:event.type};copyProperties(event,properties,data);sendFn(data)}}function touchEventHandler(event,sendFn){const touches=[];const data={type:event.type,touches};for(let i=0;i{if(!worker){handleProxyEvent(data,id)}else worker.postMessage({route:"handleProxyEvent",args:[data,id]})};let entries=Object.entries(eventHandlers);for(const[eventName,handler]of entries){element.addEventListener(eventName,function(event){handler(event,sendEvent)})}const sendSize=()=>{const rect=element.getBoundingClientRect();sendEvent({type:"resize",left:rect.left,top:rect.top,width:element.clientWidth,height:element.clientHeight})};sendSize();globalThis.addEventListener("resize",sendSize);return id}var EventDispatcher=class{addEventListener(type,listener){if(this.__listeners===void 0)this.__listeners={};const listeners=this.__listeners;if(listeners[type]===void 0){listeners[type]=[]}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener)}}hasEventListener(type,listener){if(this.__listeners===void 0)return false;const listeners=this.__listeners;return listeners[type]!==void 0&&listeners[type].indexOf(listener)!==-1}removeEventListener(type,listener){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[type];if(listenerArray!==void 0){const index=listenerArray.indexOf(listener);if(index!==-1){listenerArray.splice(index,1)}}}dispatchEvent(event,target){if(this.__listeners===void 0)return;const listeners=this.__listeners;const listenerArray=listeners[event.type];if(listenerArray!==void 0){if(!target)event.target=this;else event.target=target;const array=listenerArray.slice(0);for(let i=0,l=array.length;i{};this.releasePointerCapture=()=>{};this.getBoundingClientRect=()=>{return{left:this.left,top:this.top,width:this.width,height:this.height,right:this.left+this.width,bottom:this.top+this.height}};this.handleEvent=data=>{if(data.type==="resize"){this.left=data.left;this.top=data.top;this.width=data.width;this.height=data.height;if(typeof this.proxied==="object"){this.proxied.style.width=this.width+"px";this.proxied.style.height=this.height+"px";this.proxied.clientWidth=this.width;this.proxied.clientHeight=this.height}}data.preventDefault=noop;data.stopPropagation=noop;this.dispatchEvent(data,this.proxied)};this.style={}}get clientWidth(){return this.width}get clientHeight(){return this.height}focus(){}};var ProxyManager=class{constructor(){this.targets={};this.makeProxy=(id,addTo=void 0)=>{if(!id)id=`proxyReceiver${Math.floor(Math.random()*1e15)}`;let proxy;if(this.targets[id])proxy=this.targets[id];else{proxy=new ElementProxyReceiver;this.targets[id]=proxy}if(typeof addTo==="object"){addTo.proxy=proxy;proxy.proxied=addTo;if(typeof WorkerGlobalScope!=="undefined")addTo.style=proxy.style;if(proxy.width){addTo.style.width=proxy.width+"px";addTo.clientWidth=proxy.width}if(proxy.height){addTo.style.height=proxy.height+"px";addTo.clientHeight=proxy.height}addTo.setPointerCapture=proxy.setPointerCapture.bind(proxy);addTo.releasePointerCapture=proxy.releasePointerCapture.bind(proxy);addTo.getBoundingClientRect=proxy.getBoundingClientRect.bind(proxy);addTo.addEventListener=proxy.addEventListener.bind(proxy);addTo.removeEventListener=proxy.removeEventListener.bind(proxy);addTo.handleEvent=proxy.handleEvent.bind(proxy);addTo.dispatchEvent=proxy.dispatchEvent.bind(proxy);addTo.focus=proxy.focus.bind(proxy)}};this.getProxy=id=>{return this.targets[id]};this.handleEvent=(data,id)=>{if(!this.targets[id])this.makeProxy(id);if(this.targets[id]){this.targets[id].handleEvent(data);return true}return void 0};if(!globalThis.document)globalThis.document={}}};function makeProxy(id,elm){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;this.__node.graph.ProxyManager.makeProxy(id,elm)}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;globalThis.ProxyManager.makeProxy(id,elm)}return id}function handleProxyEvent(data,id){if(this?.__node?.graph){if(!this.__node.graph.ProxyManager)this.__node.graph.ProxyManager=new ProxyManager;if(this.__node.graph.ProxyManager.handleEvent(data,id))return data}else{if(!globalThis.ProxyManager)globalThis.ProxyManager=new ProxyManager;if(globalThis.ProxyManager.handleEvent(data,id))return data}}var proxyElementWorkerRoutes={initProxyElement,makeProxy,handleProxyEvent};function Renderer(options){if(options.worker){let worker=options.worker;let route=options.route;if(worker instanceof Blob||typeof worker==="string"){worker=new Worker(worker)}delete options.worker;delete options.route;return transferCanvas(worker,options,route)}else{initProxyElement(options.canvas,void 0,options._id);return setupCanvas(options)}}function transferCanvas(worker,options,route){if(!options)return void 0;if(!options._id)options._id=`canvas${Math.floor(Math.random()*1e15)}`;let offscreen=options.canvas.transferControlToOffscreen();if(!options.width)options.width=options.canvas.clientWidth;if(!options.height)options.height=options.canvas.clientHeight;let message={route:route?route:"setupCanvas",args:{...options,canvas:offscreen}};if(this?.__node?.graph)this.__node.graph.run("initProxyElement",options.canvas,worker,options._id);else initProxyElement(options.canvas,worker,options._id);if(options.draw){if(typeof options.draw==="function")message.args.draw=options.draw.toString();else message.args.draw=options.draw}if(options.update){if(typeof options.update==="function")message.args.update=options.update.toString();else message.args.update=options.update}if(options.init){if(typeof options.init==="function")message.args.init=options.init.toString();else message.args.init=options.init}if(options.clear){if(typeof options.clear==="function")message.args.clear=options.clear.toString();else message.args.clear=options.clear}let transfer=[offscreen];if(options.transfer){transfer.push(...options.transfer);delete options.transfer}worker.postMessage(message,transfer);const canvascontrols={_id:options._id,width:options.width,height:options.height,worker,draw:props=>{worker.postMessage({route:"drawFrame",args:[props,options._id]})},update:props=>{worker.postMessage({route:"updateCanvas",args:[props,options._id]})},clear:()=>{worker.postMessage({route:"clearCanvas",args:options._id})},init:()=>{worker.postMessage({route:"initCanvas",args:options._id})},stop:()=>{worker.postMessage({route:"stopAnim",args:options._id})},start:()=>{worker.postMessage({route:"startAnim",args:options._id})},set:newDrawProps=>{worker.postMessage({route:"setDraw",args:[newDrawProps,options._id]})},terminate:()=>{worker.terminate()}};return canvascontrols}function setDraw(settings,_id){let canvasopts;if(this?.__node?.graph){if(_id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else if(settings._id)canvasopts=this.__node.graph.CANVASES?.[settings._id];else canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]]}else{if(_id)canvasopts=globalThis.CANVASES?.[settings._id];else if(settings._id)canvasopts=globalThis.CANVASES?.[settings._id];else canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]]}if(canvasopts){if(settings.canvas){canvasopts.canvas=settings.canvas;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasopts._id,canvasopts.canvas);else proxyElementWorkerRoutes.makeProxy(canvasopts._id,canvasopts.canvas)}if(typeof settings.context==="string")canvasopts.context=canvasopts.canvas.getContext(settings.context);else if(settings.context)canvasopts.context=settings.context;if(settings.width)canvasopts.canvas.width=settings.width;if(settings.height)canvasopts.canvas.height=settings.height;if(typeof settings.draw==="string")settings.draw=parseFunctionFromText(settings.draw);if(typeof settings.draw==="function"){canvasopts.draw=settings.draw}if(typeof settings.update==="string")settings.update=parseFunctionFromText(settings.update);if(typeof settings.update==="function"){canvasopts.update=settings.update}if(typeof settings.init==="string")settings.init=parseFunctionFromText(settings.init);if(typeof settings.init==="function"){canvasopts.init=settings.init}if(typeof settings.clear==="string")settings.clear=parseFunctionFromText(settings.clear);if(typeof settings.clear==="function"){canvasopts.clear=settings.clear}return settings._id}return void 0}function setupCanvas(options){if(this?.__node?.graph){if(!this.__node.graph.CANVASES)this.__node.graph.CANVASES={}}else if(!globalThis.CANVASES)globalThis.CANVASES={};let canvasOptions=options;options._id?canvasOptions._id=options._id:canvasOptions._id=`canvas${Math.floor(Math.random()*1e15)}`;typeof options.context==="string"?canvasOptions.context=options.canvas.getContext(options.context):canvasOptions.context=options.context;"animating"in options?canvasOptions.animating=options.animating:canvasOptions.animating=true;if(this?.__node?.graph?.CANVASES[canvasOptions._id]){this.__node.graph.run("setDraw",canvasOptions)}else if(globalThis.CANVASES?.[canvasOptions._id]){setDraw(canvasOptions)}else{if(this?.__node?.graph)canvasOptions.graph=this.__node.graph;if(this?.__node?.graph)this.__node.graph.CANVASES[canvasOptions._id]=canvasOptions;else globalThis.CANVASES[canvasOptions._id]=canvasOptions;if(this?.__node?.graph)this.__node.graph.run("makeProxy",canvasOptions._id,canvasOptions.canvas);else proxyElementWorkerRoutes.makeProxy(canvasOptions._id,canvasOptions.canvas);if(options.width)canvasOptions.canvas.width=options.width;if(options.height)canvasOptions.canvas.height=options.height;if(typeof canvasOptions.draw==="string"){canvasOptions.draw=parseFunctionFromText(canvasOptions.draw)}else if(typeof canvasOptions.draw==="function"){canvasOptions.draw=canvasOptions.draw}if(typeof canvasOptions.update==="string"){canvasOptions.update=parseFunctionFromText(canvasOptions.update)}else if(typeof canvasOptions.update==="function"){canvasOptions.update=canvasOptions.update}if(typeof canvasOptions.init==="string"){canvasOptions.init=parseFunctionFromText(canvasOptions.init)}else if(typeof canvasOptions.init==="function"){canvasOptions.init=canvasOptions.init}if(typeof canvasOptions.clear==="string"){canvasOptions.clear=parseFunctionFromText(canvasOptions.clear)}else if(typeof canvasOptions.clear==="function"){canvasOptions.clear=canvasOptions.clear}if(typeof canvasOptions.init==="function")canvasOptions.init(canvasOptions,canvasOptions.canvas,canvasOptions.context);canvasOptions.stop=()=>{stopAnim(canvasOptions._id)};canvasOptions.start=draw=>{startAnim(canvasOptions._id,draw)};canvasOptions.set=settings=>{setDraw(settings,canvasOptions._id)};if(typeof canvasOptions.draw==="function"&&canvasOptions.animating){let draw=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw(s,canvas,context)})}};draw(canvasOptions,canvasOptions.canvas,canvasOptions.context)}}if(typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope)return canvasOptions._id;else{const canvascontrols={_id:options._id,width:options.width,height:options.height,draw:props=>{drawFrame(props,options._id)},update:props=>{updateCanvas(props,options._id)},clear:()=>{clearCanvas(options._id)},init:()=>{initCanvas(options._id)},stop:()=>{stopAnim(options._id)},start:()=>{startAnim(options._id)},set:newDrawProps=>{setDraw(newDrawProps,options._id)},terminate:()=>{stopAnim(options._id)}};return canvascontrols}}function drawFrame(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){if(props)Object.assign(canvasopts,props);if(canvasopts.draw){canvasopts.draw(canvasopts,canvasopts.canvas,canvasopts.context);return _id}}return void 0}function clearCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.clear){canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function initCanvas(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.init){canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function updateCanvas(input,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts?.update){canvasopts.update(canvasopts,canvasopts.canvas,canvasopts.context,input);return _id}return void 0}function setProps(props,_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){Object.assign(canvasopts,props);if(props.width)canvasopts.canvas.width=props.width;if(props.height)canvasopts.canvas.height=props.height;return _id}return void 0}function startAnim(_id,draw){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}canvasopts.animating=true;if(canvasopts&&draw){if(typeof draw==="string")draw=parseFunctionFromText(draw);if(typeof draw==="function"){canvasopts.draw=draw}return _id}if(typeof canvasopts?.draw==="function"){let draw2=(s,canvas,context)=>{if(s.animating){s.draw(s,canvas,context);requestAnimationFrame(()=>{draw2(s,canvas,context)})}};if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);if(typeof canvasopts.init==="function")canvasopts.init(canvasopts,canvasopts.canvas,canvasopts.context);draw2(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}function stopAnim(_id){let canvasopts;if(this?.__node?.graph){if(!_id)canvasopts=this.__node.graph.CANVASES?.[Object.keys(this.__node.graph.CANVASES)[0]];else canvasopts=this.__node.graph.CANVASES?.[_id]}else{if(!_id)canvasopts=globalThis.CANVASES?.[Object.keys(globalThis.CANVASES)[0]];else canvasopts=globalThis.CANVASES?.[_id]}if(canvasopts){canvasopts.animating=false;if(typeof canvasopts.clear==="function")canvasopts.clear(canvasopts,canvasopts.canvas,canvasopts.context);return _id}return void 0}var workerCanvasRoutes={...proxyElementWorkerRoutes,Renderer,transferCanvas,setupCanvas,setDraw,drawFrame,clearCanvas,initCanvas,updateCanvas,setProps,startAnim,stopAnim};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}function parseFunctionFromText2(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx--}}}}function checkCircular(key,value){if(value!=null){if(typeof value==="object"){if(key){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}}}return value}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value||idx===0){path.push(key);parents.push(value.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value;path[idx]=key;break}}idx++}}}}}function checkValues(key,value){let val;if(value!=null){if(typeof value==="object"){let c=value.constructor.name;if(key&&c==="Object"){updateParents(key,value)}let other=refs.get(value);if(other){return"[Circular Reference]"+other}else{refs.set(value,path.join("."))}if(c==="Array"){if(value.length>20){val=value.slice(value.length-20)}else val=value}else if(c.includes("Set")){val=Array.from(value)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value){if(value[prop]==null){obj[prop]=value[prop]}else if(Array.isArray(value[prop])){if(value[prop].length>20)obj[prop]=value[prop].slice(value[prop].length-20);else obj[prop]=value[prop]}else if(value[prop].constructor.name==="Object"){obj[prop]={};for(const p in value[prop]){if(Array.isArray(value[prop][p])){if(value[prop][p].length>20)obj[prop][p]=value[prop][p].slice(value[prop][p].length-20);else obj[prop][p]=value[prop][p]}else{if(value[prop][p]!=null){let con=value[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value[prop][p]}}else{obj[prop][p]=value[prop][p]}}}}else{let con=value[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value[prop]}}}val=obj}else{val=value}}else{val=value}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var unsafeRoutes={setRoute:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else{let node=this.__node.graph.add({__node:{tag:fnName},__operator:fn})}return true}return false},setNode:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(fnName)){this.__node.graph.get(fnName).__setOperator(fn)}else this.__node.graph.add({__node:{tag:fnName},__operator:fn});return true}return false},setMethod:function(route,fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;if(this.__node.graph.get(route)){this.__node.graph.get(route)[fnName]=fn}else this.__node.graph.add({__node:{tag:fnName,[fnName]:fn}});return true}return false},assignRoute:function(route,source){if(this.__node.graph.get(route)&&typeof source==="object"){Object.assign(this.__node.graph.get(route),source)}},transferClass:(classObj,className)=>{if(typeof classObj==="object"){let str=classObj.toString();let message={route:"receiveClass",args:[str,className]};return message}return false},receiveClass:function(stringified,className){if(typeof stringified==="string"){if(stringified.indexOf("class")===0){let cls=(0,eval)("("+stringified+")");let name=className;if(!name)name=cls.name;this.__node.graph[name]=cls;return true}}return false},setGlobal:(key,value)=>{globalThis[key]=value;return true},assignGlobalObject:(target,source)=>{if(!globalThis[target])return false;if(typeof source==="object")Object.assign(globalThis[target],source);return true},setValue:function(key,value){this.__node.graph[key]=value;return true},assignObject:function(target,source){if(!this.__node.graph[target])return false;if(typeof source==="object")Object.assign(this.__node.graph[target],source);return true},setGlobalFunction:(fn,fnName)=>{if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;globalThis[fnName]=fn;return true}return false},assignFunctionToGlobalObject:function(globalObjectName,fn,fnName){if(!globalThis[globalObjectName])return false;if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[globalObjectName][fnName]=fn;return true}return false},setFunction:function(fn,fnName){if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[fnName]=fn;return true}return false},assignFunctionToObject:function(objectName,fn,fnName){if(!this.__node.graph[objectName])return false;if(typeof fn==="string")fn=parseFunctionFromText2(fn);if(typeof fn==="function"){if(!fnName)fnName=fn.name;this.__node.graph[objectName][fnName]=fn;return true}return false}};var __defProp2=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __publicField=(obj,key,value)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);return value};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean=void 0){let avg=mean;if(!mean)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean*mean-det);let eig1=mean+sqrt;let eig2=mean-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean1=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean1=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean1,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean1)*(delaybuf[delay+i]-mean1));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean=this.mean(smoothed);let std=this.std(smoothed,mean);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window=49)=>{let mid=Math.floor(window*.5);let peaks=[];for(let i=0;i{}|[(v,i,x,y..)=>{},(v,i,x,y...)=>{}]) //iterate an array buffer with the matrix coordinates of each buffer, use the asIndex function to run operations on that coordinate, or an array of functions e.g. to specify rgb color or xyz axis specific operators, returns a new array buffer. + * combinations(choices,vecsize); //create array of vectors of set size containing every combination from a given array of choices + * generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],stepSizes=[1,1,1]) //generate a coordinate space between the upper and lower bounds, with each dimension having its own step size specifiable as a number or function, e.g. one function could be a time increment on its own interval and the rest are cartesian coordinates + * meshgrid(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],stepSizes=[1,1,1]) //same as generateCoordinateSpace but named after the common python/matlab function + * calcVectorField(generateCoordinateSpace(),formula=(...vec)=>{return vec.map(d => d*0.5)}) //pass a genenerated coordinate space and a formula that returns results for each vector in the coordinate space, e.g. navier stokes + * transpose(mat) //2d mat transpose + * matmul(a,b) //2d mat mul + * matscale(mat,scalar) //2d mat scalar + * matadd(a,b) //2d mat add + * matsub(a,b) //2d mat subtract + * normalDistribution(samples=[], normalize=true) //create a normal (gaussian) distribution + * expectedValue(samples=[],probabilities=this.normalDistribution(samples)) //get expected value of an array + * originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1) //statistical moment about origin + * centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1) //statistical moment about mean + * linearDiscriminantAnalysis(samples=[], classifier=[]) //LDA + * conv1D(arr=[],kern=[],pad=0) //1d convolution //1d convolution + * conv2D(mat=[[],[],[]],kern=[[],[],[]],pad=0) //2d convolution + * cov2d(mat) //2d covariance + * cov1d(arr1=[],arr2=[]) //1d covariance + * cov3d(x=[],y=[],z=[]) //3d covariance + * covNd(dimensionalData=[]) //nd covariance + * eigens2x2(mat=[[1,2],[3,4]]) //fast 2x2 eigenvalue + * eigenvectors2x2(mat=[[1,2],[3,4]], eigens=[1,2]) //fast 2x2 eigenvector + * fastpca2d(xarr,yarr) //fast 2d pca + * crosscorrelation(arr1,arr2) //crosscor + * autocorrelation(arr1) //autocor + * autocorrelation2d(mat2d=[[],[],...]) //2d autocorrelation + * autocorrelation2dNormalized(mat2d=[[],[],...]) //normalized 2d autocorrelation + * dft(arr=[]) //discrete fourier transform (slow) + * correlograms(dat=[[],[]]) //return cross correlations of many signals + * sma(arr=[], window) //simple moving average + * sum(arr=[]) //array sum + * reduceArrByFactor(arr,factor=2) //reduce array sizes + * makeArr(startValue, stopValue, nSteps) //linspace + * HSLtoRGB(h,s,l,scalar=255) //convert hsl to rgb, returns array + * autoscale(array,stackedLines=1,stackPosition=0,centerZero=false)//autoscale array between -1 and 1, can be used for stacking lines e.g. in webgl + * absmax(array) //returns the absolute value maximum of an array + * downsample(data, fitCount, scalar=1) //downsample array, different formula than interpolateArray + * interpolateArray(data, fitCount, scalar=1) //or upsample(data, fitCount, scalar=1), upsampling array with spring factor + * lerp(v0,v1,fit,floor?) //linearly interpolate (linspace) between two values with a specified fit count, can make sure all values are rounded down too. + * isExtrema(arr,critical='peak') //peak or valley + * isCriticalPoint(arr,critical='peak') //peak, valley + * peakDetect = (smoothedArray,type='peak',window=49) //wider window to find less peaks + * getPeakThreshold(arr, peakIndices, thresholdVar) + * eigens(M=[[],[]], tolerance=0.0001, max_iterations=1000) + * pca(mat=[[],[]],tolerance = 0.00001) //power iteration method PCA + * eigenvalue_of_vector(mat, eigenvector) + * power_iteration(mat, tolerance=0.00001, max_iterations=1000) + * squared_difference(v1, v2) + * flatten_vector(v) //column to row + * column(mat, x) //row to column + * circularBuffer(arr:any[],newData:any|any[]) //push new entries to end of array and roll over starting entries with a set array length + * + */ +export class Math2 { + static TWO_PI: number; + static C: number; + static G: number; + static h: number; + static R: number; + static Ra: number; + static H: number; + static kbar: number; + static kB: number; + static ke: number; + static me: number; + static mp: number; + static mn: number; + static P0: number; + static T0: number; + static p0: number; + static Na: number; + static y: number; + static M0: number; + static g0: number; + static Re: number; + static B: number; + static S: number; + static Sigma: number; + static imgkernels: { + edgeDetection: number[][]; + boxBlur: number[][]; + sobelLeft: number[][]; + sobelRight: number[][]; + sobelTop: number[][]; + sobelBottom: number[][]; + identity: number[][]; + gaussian3x3: number[][]; + guassian7x7: number[][]; + emboss: number[][]; + sharpen: number[][]; + }; + static genSineWave(freq?: number, peakAmp?: number, nSec?: number, fs?: number, freq2?: number, peakAmp2?: number): number[][]; + static getSineAmplitude(frequency?: number, peakAmplitude?: number, ti?: number, tOffset?: number): number; + static mean(arr: any): number; + static mode(arr: any): any; + static std(arr: any, mean?: any): number; + static relError(actual?: any[], forecast?: any[], abs?: boolean): any[]; + static informationEntropy(probabilities?: any[]): any[]; + static zscore(arr: any): any; + static variance(arr: any): number; + static dot(vec1: any, vec2: any): number; + static cross3D(vec1: any, vec2: any): number[]; + static magnitude(vec: any): number; + static distance(point1: any, point2: any): number; + static midpoint(point1?: number[], point2?: number[]): number[]; + static normalize(vec: any): any[]; + static normalizeSeries(arr?: any[], fromZero?: boolean): number[]; + static quadraticFormula(a: any, b: any, c: any): string[] | number[]; + static newtonsMethod(foo?: (x: any) => number, start?: number, end?: number, precision?: number, attempts?: number): any[]; + static integral: (func?: (x: any) => any, range?: any[], stepx?: number) => number; + static dintegral: (func?: (x: any, y: any) => any, range?: any[][], stepx?: number, stepy?: number) => number; + static tintegral: (func?: (x: any, y: any, z: any) => any, range?: any[][], stepx?: number, stepy?: number, stepz?: number) => number; + static pintegral: (func?: (x: any) => any, range?: any[], stepx?: number) => number; + static makeVec(point1: any, point2: any): any[]; + static getBufferedValueByCoordinates(vb?: any[], dims?: number[], coordinate?: number[], cardinal?: any): any; + static forBufferedMat(vb?: any[], dims?: number[], asIndex?: (v: any, i: any, x: any, y: any) => any): any[]; + static mapBufferedMat(buffer?: any[], dimensions?: number[], asIndex?: (v: any, idx: any, i: any, j: any) => any): any[]; + static combinations(choices?: string[], vecsize?: number): any[][]; + static generateCoordinateSpace(upperBounds?: number[], lowerBounds?: number[], steps?: number[], mutater?: any): any[]; + static meshgrid: typeof Math2.generateCoordinateSpace; + static calcVectorField(coordinates?: number[][], formula?: (x: any, y: any) => number[]): number[][]; + static transpose(mat: any): any; + static matmul(a: any, b: any): any[]; + static matscale(mat: any, scalar: any): any[][]; + static matadd(a: any, b: any): any[][]; + static matsub(a: any, b: any): any[][]; + static histogram(arr?: any[], binSize?: number, nBins?: any): number[][]; + static normalDistribution(samples?: any[], normalize?: boolean, cutoff?: number): number[]; + static expectedValue(samples?: any[], probabilities?: number[]): any; + static originMoment(samples?: any[], probabilities?: number[], order?: number): any; + static centralMoment(samples?: any[], probabilities?: number[], order?: number): any; + static linearDiscriminantAnalysis(samples?: any[], classifier?: any[]): number[]; + static conv1D(arr?: any[], kern?: number[], pad?: number): number[]; + static conv2D(mat?: any[][], kern?: any[][], pad?: number): any[]; + static cov2d(mat: any): any[]; + static cov1d(arr1?: any[], arr2?: any[]): any[]; + static cov3d(x?: any[], y?: any[], z?: any[]): any[][][]; + static covNd(dimensionalData?: any[]): void; + static eigens2x2(mat?: number[][]): number[]; + static eigenvectors2x2(mat?: number[][], eigens?: number[]): number[][]; + static fastpca2d(xarr: any, yarr: any): (number[] | number[][])[]; + static crosscorrelation(arr1: any, arr2: any): any[]; + static autocorrelation(arr1: any): any[]; + static autocorrelation2d: (mat2d: any) => any[][]; + static autocorrelation2dNormalized(mat2d: any): any[][]; + static crosscorrelation2d(mat2d1: any, mat2d2: any): any[][]; + static crosscorrelation2dNormalized(mat2d1: any, mat2d2: any): any[][]; + static correlograms(dat?: any[][]): any[]; + static dft(sineWave?: any[]): { + real: number[]; + imag: number[]; + freqs: number[]; + mags: any[]; + }; + static sma(arr: any[], window: any): any[]; + static sum(arr?: any[]): any; + static reduceArrByFactor(arr: any, factor?: number): any; + static makeArr(startValue: any, stopValue: any, nSteps: any): any[]; + static lerp: typeof Math2.makeArr; + static autoscale(array: any, stackedLines?: number, stackPosition?: number, centerZero?: boolean): any; + static absmax(array: any): number; + static downsample(array: any, fitCount: any, scalar?: number): any; + static interpolateArray(data: any, fitCount: any, scalar?: number): any[]; + static upsample: typeof Math2.interpolateArray; + static isExtrema(arr: any, critical?: string): boolean; + static isCriticalPoint(arr: any, critical?: string): boolean; + static peakDetect: (smoothedArray: any, type?: string, window?: number) => number[]; + static getPeakThreshold(arr: any, peakIndices: any, thresholdVar: any): number; + static column(mat: any, x: any): any[][]; + static flatten_vector(v: any): any[]; + static squared_difference(v1: any, v2: any): number; + static shift_deflate(mat: any, eigenvalue: any, eigenvector: any): any[][]; + static eigenvalue_of_vector(mat: any, eigenvector: any): any; + static power_iteration(mat: any, tolerance?: number, max_iterations?: number): any[]; + static eigens(mat: any, tolerance?: number, max_iterations?: number): any[][]; + static pca(mat: any, tolerance?: number): any[]; + static circularBuffer(arr: any, newEntries: any): any; + static HSLToRGB(h: any, s: any, l: any, scalar?: number): number[]; + static p300(event_timestamps?: any[], raw_signal?: any[], signal_timestamps?: any[], sps?: number): any[]; +} diff --git a/extras/dist/extras/algorithms/accel_gyro.d.ts b/extras/dist/extras/algorithms/accel_gyro.d.ts new file mode 100644 index 00000000..45c340cd --- /dev/null +++ b/extras/dist/extras/algorithms/accel_gyro.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const accel_gyro: SubprocessContextProps; diff --git a/extras/dist/extras/algorithms/beat_detect.d.ts b/extras/dist/extras/algorithms/beat_detect.d.ts new file mode 100644 index 00000000..346cbfcf --- /dev/null +++ b/extras/dist/extras/algorithms/beat_detect.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const beat_detect: SubprocessContextProps; diff --git a/extras/dist/extras/algorithms/blink.d.ts b/extras/dist/extras/algorithms/blink.d.ts new file mode 100644 index 00000000..3005ec1a --- /dev/null +++ b/extras/dist/extras/algorithms/blink.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const blink_detect: SubprocessContextProps; diff --git a/extras/dist/extras/algorithms/buffering.d.ts b/extras/dist/extras/algorithms/buffering.d.ts new file mode 100644 index 00000000..92ad69e9 --- /dev/null +++ b/extras/dist/extras/algorithms/buffering.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const circularBuffer2d: SubprocessContextProps; diff --git a/extras/dist/extras/algorithms/coherence.d.ts b/extras/dist/extras/algorithms/coherence.d.ts new file mode 100644 index 00000000..5acffc84 --- /dev/null +++ b/extras/dist/extras/algorithms/coherence.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const coherence: SubprocessContextProps; diff --git a/extras/dist/extras/algorithms/dft.d.ts b/extras/dist/extras/algorithms/dft.d.ts new file mode 100644 index 00000000..82988737 --- /dev/null +++ b/extras/dist/extras/algorithms/dft.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from '../../services/worker/Subprocess'; +export declare const dft: SubprocessContextProps; diff --git a/extras/dist/extras/algorithms/index.d.ts b/extras/dist/extras/algorithms/index.d.ts new file mode 100644 index 00000000..8ba2e475 --- /dev/null +++ b/extras/dist/extras/algorithms/index.d.ts @@ -0,0 +1,2 @@ +import { algorithms } from "../../services/worker/Subprocess"; +export { algorithms }; diff --git a/extras/dist/extras/algorithms/index.gpu.d.ts b/extras/dist/extras/algorithms/index.gpu.d.ts new file mode 100644 index 00000000..d11cfebe --- /dev/null +++ b/extras/dist/extras/algorithms/index.gpu.d.ts @@ -0,0 +1,4 @@ +export declare const gpualgorithms: { + dft: import("../../services/worker/Subprocess").SubprocessContextProps; + coherence: import("../../services/worker/Subprocess").SubprocessContextProps; +}; diff --git a/extras/dist/extras/algorithms/rms.d.ts b/extras/dist/extras/algorithms/rms.d.ts new file mode 100644 index 00000000..117927d3 --- /dev/null +++ b/extras/dist/extras/algorithms/rms.d.ts @@ -0,0 +1,2 @@ +import { SubprocessContextProps } from "../../services/worker/Subprocess"; +export declare const rms: SubprocessContextProps; diff --git a/src/extras/dist/extras/algorithms/util/ArrayManip.d.ts b/extras/dist/extras/algorithms/util/ArrayManip.d.ts similarity index 92% rename from src/extras/dist/extras/algorithms/util/ArrayManip.d.ts rename to extras/dist/extras/algorithms/util/ArrayManip.d.ts index b6d5e3ad..af7ef430 100644 --- a/src/extras/dist/extras/algorithms/util/ArrayManip.d.ts +++ b/extras/dist/extras/algorithms/util/ArrayManip.d.ts @@ -1,4 +1,4 @@ -export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; export declare class ArrayManip { static autoscale(array: any, lineIdx?: number, nLines?: number, centerZero?: boolean, ymin?: number, ymax?: number, clamp?: boolean): any; static genTimestamps(ct: any, sps: any): any[]; diff --git a/src/extras/dist/extras/algorithms/util/BiquadFilters.d.ts b/extras/dist/extras/algorithms/util/BiquadFilters.d.ts similarity index 98% rename from src/extras/dist/extras/algorithms/util/BiquadFilters.d.ts rename to extras/dist/extras/algorithms/util/BiquadFilters.d.ts index fd1d4fc9..06be6c3a 100644 --- a/src/extras/dist/extras/algorithms/util/BiquadFilters.d.ts +++ b/extras/dist/extras/algorithms/util/BiquadFilters.d.ts @@ -1,4 +1,4 @@ -export type FilterSettings = { +export declare type FilterSettings = { sps: number; useSMA4?: boolean; useNotch50?: boolean; diff --git a/src/extras/dist/extras/algorithms/util/ByteParser.d.ts b/extras/dist/extras/algorithms/util/ByteParser.d.ts similarity index 100% rename from src/extras/dist/extras/algorithms/util/ByteParser.d.ts rename to extras/dist/extras/algorithms/util/ByteParser.d.ts diff --git a/src/extras/dist/src/extras/ecs/ECS.systems.d.ts b/extras/dist/extras/ecs/ECS.systems.d.ts similarity index 86% rename from src/extras/dist/src/extras/ecs/ECS.systems.d.ts rename to extras/dist/extras/ecs/ECS.systems.d.ts index 34de4406..f3ed1974 100644 --- a/src/extras/dist/src/extras/ecs/ECS.systems.d.ts +++ b/extras/dist/extras/ecs/ECS.systems.d.ts @@ -196,9 +196,7 @@ export declare const Systems: { x: number; y: number; z: number; - }) => { - [key: string]: number; - }; + }) => any; calcNormal: (t0: { x: number; y: number; @@ -211,12 +209,8 @@ export declare const Systems: { x: number; y: number; z: number; - }, positive?: boolean) => {}; - dot: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; + }, positive?: boolean) => any; + dot: (v1: any, v2: any) => number; makeVec(p1: { x: number; y: number; @@ -230,50 +224,14 @@ export declare const Systems: { y: number; z: number; }; - vecadd: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecsub: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecmul: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecdiv: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => { - [key: string]: number; - }; - vecscale: (v1: { - [key: string]: number; - }, scalar: number) => { - [key: string]: number; - }; - distance: (v1: { - [key: string]: number; - }, v2: { - [key: string]: number; - }) => number; - magnitude: (v: { - [key: string]: number; - }) => number; - normalize: (v: { - [key: string]: number; - }) => {}; + vecadd: (v1: any, v2: any) => any; + vecsub: (v1: any, v2: any) => any; + vecmul: (v1: any, v2: any) => any; + vecdiv: (v1: any, v2: any) => any; + vecscale: (v1: any, scalar: number) => any; + distance: (v1: any, v2: any) => number; + magnitude: (v: any) => number; + normalize: (v: any) => any; distance3D(v1: { x: number; y: number; diff --git a/src/extras/dist/extras/gpu/GPU.service.d.ts b/extras/dist/extras/gpu/GPU.service.d.ts similarity index 89% rename from src/extras/dist/extras/gpu/GPU.service.d.ts rename to extras/dist/extras/gpu/GPU.service.d.ts index 547ea325..0973ddfc 100644 --- a/src/extras/dist/extras/gpu/GPU.service.d.ts +++ b/extras/dist/extras/gpu/GPU.service.d.ts @@ -5,7 +5,6 @@ export declare class GPUService extends Service { constructor(options?: any); addFunc: (fn: string | Function) => void; addKernel: (name: string, fn: string | Function, options?: any) => void; - combineKernels: (name: string, fs: (string | Function)[], ckrnl?: () => void) => void; callKernel: (name: string, ...args: any[]) => void; dft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; multidft: (signalBuffer: number[], nSeconds: any, scalar?: number) => any; diff --git a/src/extras/dist/src/extras/index.gpu.services.d.ts b/extras/dist/extras/index.gpu.services.d.ts similarity index 100% rename from src/extras/dist/src/extras/index.gpu.services.d.ts rename to extras/dist/extras/index.gpu.services.d.ts diff --git a/src/extras/dist/extras/index.services.d.ts b/extras/dist/extras/index.services.d.ts similarity index 75% rename from src/extras/dist/extras/index.services.d.ts rename to extras/dist/extras/index.services.d.ts index 4c38107e..34402ae3 100644 --- a/src/extras/dist/extras/index.services.d.ts +++ b/extras/dist/extras/index.services.d.ts @@ -1,6 +1,7 @@ export * from './struct/Struct.frontend'; export * from './struct/Struct.backend'; -export * from './struct/genTimestamps'; export * from './ecs/ECS.systems'; export * from './webgl-plot/webglplot.routes'; +import gsworker from '../services/worker/Worker'; export { algorithms } from './algorithms/index'; +export { gsworker }; diff --git a/src/extras/dist/src/storage/BFSUtils.d.ts b/extras/dist/extras/storage/BFSUtils.d.ts similarity index 85% rename from src/extras/dist/src/storage/BFSUtils.d.ts rename to extras/dist/extras/storage/BFSUtils.d.ts index be89548b..3bc84449 100644 --- a/src/extras/dist/src/storage/BFSUtils.d.ts +++ b/extras/dist/extras/storage/BFSUtils.d.ts @@ -1,8 +1,7 @@ export function readFileChunk(path?: string, begin?: number, end?: number, onread?: (data: any) => void): Promise; -export function processCSVChunksFromDB(path?: string, onData?: (csvdata: any, start: any, end: any, size: any) => void, maxChunkSize?: number, start?: number, end?: string, options?: {}): Promise; -export function readCSVChunkFromDB(path?: string, start?: number, end?: string, options?: {}): Promise<{}>; +export function readCSVChunkFromDB(path?: string, start?: number, end?: string): Promise<{}>; export let fsInited: boolean; -export const fs: import("browserfs/dist/node/core/FS.js").FSModule; +export const fs: import("browserfs/dist/node/core/FS").FSModule; export function initFS(dirs?: string[], oninit?: (exists?: any[]) => void, onerror?: (e: any) => void, filesystem?: string): Promise; export function exists(path?: string): Promise; export function readFile(path?: string): Promise; diff --git a/src/extras/dist/src/storage/BFS_CSV.d.ts b/extras/dist/extras/storage/BFS_CSV.d.ts similarity index 62% rename from src/extras/dist/src/storage/BFS_CSV.d.ts rename to extras/dist/extras/storage/BFS_CSV.d.ts index d18aaee3..2f1e5fbe 100644 --- a/src/extras/dist/src/storage/BFS_CSV.d.ts +++ b/extras/dist/extras/storage/BFS_CSV.d.ts @@ -1,27 +1,17 @@ -import { processCSVChunksFromDB, readCSVChunkFromDB } from './BFSUtils'; +import { readCSVChunkFromDB } from './BFSUtils'; import { CSV, toISOLocal } from './csv'; export declare const appendCSV: (newData: { [key: string]: number | number[]; -}, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; -}) => Promise; +}, filename: string, header?: string[]) => Promise; export declare const updateCSVHeader: (header: any[], filename: string) => void; -export declare const createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; +export declare const createCSV: (filename: string, header: string[]) => Promise; export declare const visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; export declare const csvRoutes: { appendCSV: (newData: { [key: string]: number | number[]; - }, filename: string, header?: string[], options?: { - json?: boolean; - toFixed?: number; - bufferSize?: number; - xIncrement?: number; - }) => Promise; + }, filename: string, header?: string[]) => Promise; updateCSVHeader: (header: any[], filename: string) => void; - createCSV: (filename: string, header: string[], toFixed?: number, bufferSize?: number, xIncrement?: number) => Promise; + createCSV: (filename: string, header: string[]) => Promise; visualizeDirectory: (dir: string, parentNode?: HTMLElement) => Promise; openCSV: typeof CSV.openCSV; saveCSV: typeof CSV.saveCSV; @@ -34,6 +24,5 @@ export declare const csvRoutes: { getCSVHeader: (path?: string, onopen?: (header: any, filename: any) => void) => Promise; writeToCSVFromDB: (path?: string, fileSizeLimitMb?: number) => Promise; readCSVChunkFromDB: typeof readCSVChunkFromDB; - processCSVChunksFromDB: typeof processCSVChunksFromDB; toISOLocal: typeof toISOLocal; }; diff --git a/extras/dist/extras/storage/browserfs.min.d.ts b/extras/dist/extras/storage/browserfs.min.d.ts new file mode 100644 index 00000000..c6285eed --- /dev/null +++ b/extras/dist/extras/storage/browserfs.min.d.ts @@ -0,0 +1,3 @@ +declare const _exports: any; +export = _exports; +export var BrowserFS: any; diff --git a/src/extras/dist/storage/csv.d.ts b/extras/dist/extras/storage/csv.d.ts similarity index 88% rename from src/extras/dist/storage/csv.d.ts rename to extras/dist/extras/storage/csv.d.ts index 030f67f5..08e7d7ae 100644 --- a/src/extras/dist/storage/csv.d.ts +++ b/extras/dist/extras/storage/csv.d.ts @@ -1,11 +1,14 @@ export function toISOLocal(d: any): string; export class CSV { static saveCSV(csvDat?: string, name?: string): void; - static openCSV(delimiter?: string, onOpen?: (csvDat: any, header: any, path: any) => any): Promise; - static openCSVRaw(onOpen?: (csvDat: any, path: any) => any): Promise; + static openCSV(delimiter?: string, onOpen?: (csvDat: any, header: any, path: any) => any): void; + static openCSVRaw(onOpen?: (csvDat: any, path: any) => any): void; constructor(onOpen?: (csvDat?: any[], header?: any[]) => void, saveButtonId?: any, openButtonId?: any); onOpen(csvDat?: any[], header?: any[]): void; - notes: any[]; + notes: { + idx: number; + text: string; + }[]; processArraysForCSV(data?: string[], delimiter?: string, header?: string, saveNotes?: boolean): string; } export function parseCSVData(data: any, filename: any, head: any, hasend?: boolean, parser?: (lines: any, filename: any, head: any) => { diff --git a/extras/dist/extras/struct/Struct.backend.d.ts b/extras/dist/extras/struct/Struct.backend.d.ts new file mode 100644 index 00000000..f8a335fd --- /dev/null +++ b/extras/dist/extras/struct/Struct.backend.d.ts @@ -0,0 +1,98 @@ +import ObjectID from "bson-objectid"; +import { AuthorizationStruct, GroupStruct, ProfileStruct } from "./datastructures/types"; +import { Service } from "../../services/Service"; +import { User } from '../../services/router/Router'; +export declare const toObjectID: (str: any) => any; +export declare const getStringId: (mongoid: string | ObjectID) => string; +declare type CollectionsType = { + users?: CollectionType; + [x: string]: CollectionType; +}; +declare type CollectionType = any | { + instance?: any; + reference: { + [key: string]: any; + }; +}; +export declare class StructBackend extends Service { + name: string; + debug: boolean; + db: any; + users: { + [key: string]: User; + }; + collections: CollectionsType; + mode: 'local' | 'mongodb' | string; + useAuths: boolean; + constructor(options?: any, dboptions?: { + users?: { + [key: string]: User; + }; + mode?: 'local' | 'mongodb' | string; + db?: any; + collections?: CollectionsType; + }); + query: (requestingUserId: string, collection?: any, queryObj?: any, findOne?: boolean, skip?: number) => Promise; + getUser: (requestingUserId: string, lookupId: string) => Promise; + setUser: (requestingUserId: string, struct: Partial) => Promise; + getUsersByIds: (requestingUserId: string, userIds: string[]) => Promise; + getUsersByRole: (requestingUserId: string, role: string) => Promise; + deleteUser: (requestingUserId: string, userId: string) => Promise; + setData: (requestingUserId: string, structs: any[], notify?: boolean) => Promise; + getData: (requestingUserId: string, collection?: string, ownerId?: string, dict?: any, limit?: number, skip?: number) => Promise; + getDataByIds: (requestingUserId: string, structIds: string[], ownerId?: string, collection?: string) => Promise; + getAllData: (requestingUserId: string, ownerId: string, excludedCollections?: string[]) => Promise; + deleteData: (requestingUserId: string, structIds: string[]) => Promise; + getUserGroups: (requestingUserId: string, userId?: string, groupId?: string) => Promise; + deleteGroup: (requestingUserId: string, groupId: string) => Promise; + getAuthorizations: (requestingUserId: string, ownerId?: string, authId?: string) => Promise; + deleteAuthorization: (requestingUserId: string, authId: string) => Promise; + notificationStruct(parentStruct?: any): { + structType: string; + timestamp: number; + _id: string; + note: string; + alert: boolean; + ownerId: string; + parentUserId: string; + parent: { + structType: any; + _id: string; + }; + }; + checkToNotify(user: Partial, structs?: any[], mode?: string): Promise; + queryMongo(user: Partial, collection: string, queryObj?: any, findOne?: boolean, skip?: number): Promise; + setMongoData(user: Partial, structs?: any[], notify?: boolean): Promise; + setMongoUser(user: Partial, struct: Partial): Promise; + setGroup(user: Partial, struct: any, mode?: string): Promise; + getMongoUser(user: Partial, info?: string, bypassAuth?: boolean): Promise<{} | { + user: ProfileStruct; + authorizations: AuthorizationStruct[]; + groups: GroupStruct[] | { + user: ProfileStruct; + }; + }>; + getMongoUsersByIds(user: Partial, userIds?: any[]): Promise; + getMongoUsersByRole(user: Partial, role: string): Promise; + getMongoDataByIds(user: Partial, structIds: string[], ownerId: string | undefined, collection: string | undefined): Promise; + getMongoData(user: Partial, collection: string | undefined, ownerId: string | undefined, dict?: any | undefined, limit?: number, skip?: number): Promise; + getAllUserMongoData(user: Partial, ownerId: any, excluded?: any[]): Promise; + getMongoDataByRefs(user: Partial, structRefs?: any[]): Promise; + getMongoAuthorizations(user: Partial, ownerId?: string, authId?: string): Promise; + getMongoGroups(user: Partial, userId?: string, groupId?: string): Promise; + deleteMongoData(user: Partial, structRefs?: any[]): Promise; + deleteMongoUser(user: Partial, userId: any): Promise; + deleteMongoGroup(user: Partial, groupId: any): Promise; + deleteMongoAuthorization(user: Partial, authId: any): Promise; + setAuthorization(user: Partial, authStruct: any, mode?: string): Promise; + checkAuthorization(user: string | Partial | { + _id: string; + }, struct: any, request?: string, //'WRITE' + mode?: string): Promise; + wipeDB: () => Promise; + overwriteLocalData(structs: any): void; + setLocalData(structs: any): void; + getLocalData(collection: any, query?: any): any; + deleteLocalData(struct: any): boolean; +} +export {}; diff --git a/src/extras/dist/src/extras/struct/Struct.frontend.d.ts b/extras/dist/extras/struct/Struct.frontend.d.ts similarity index 65% rename from src/extras/dist/src/extras/struct/Struct.frontend.d.ts rename to extras/dist/extras/struct/Struct.frontend.d.ts index 3b0ef8dc..7440b57d 100644 --- a/src/extras/dist/src/extras/struct/Struct.frontend.d.ts +++ b/extras/dist/extras/struct/Struct.frontend.d.ts @@ -1,33 +1,19 @@ import { DataTablet } from './datastructures/index'; import { Data, ProfileStruct, AuthorizationStruct, GroupStruct, DataStruct, EventStruct, ChatroomStruct, CommentStruct, Struct } from './datastructures/types'; -import { TimeSpecifier } from './genTimestamps'; import { Service } from '../../services/Service'; import { User } from '../../services/router/Router'; -import { GraphNodeProperties } from '../../core/Graph'; export declare const randomId: (prefix?: any) => string; export declare const pseudoObjectId: (m?: Math, d?: DateConstructor, h?: number, s?: (s: any) => string) => string; -export type StructFrontendProps = { - useAccessTokens?: boolean; - useRefreshTokens?: boolean; -} & GraphNodeProperties; export declare class StructFrontend extends Service { name: string; currentUser: User; tablet: DataTablet; collections: Map; id: string; - useAccessTokens: boolean; - useRefreshTokens: boolean; constructor(options?: any, user?: Partial); - getToken(user: Partial): string; - setupUser: (userinfo: Partial, callback?: (currentUser: any) => void) => Promise; + setupUser(userinfo: Partial, callback?: (currentUser: any) => void): Promise; baseServerCallback: (data: any) => void; - structNotification: () => void; - structDeleted: (struct: { - _id: string; - structType: string; - }) => void; - onResult: (data: any) => void; + onResult(data: any): void; randomId(tag?: string): string; /** let struct = { @@ -38,35 +24,34 @@ export declare class StructFrontend extends Service { parent: {structType:parentStruct?.structType,_id:parentStruct?._id}, //parent struct it's associated with (e.g. if it needs to spawn with it) } */ - addStruct: (structType?: string, props?: any, parentUser?: { + addStruct(structType?: string, props?: any, //add any props you want to set, adding users[] with ids will tell who to notify if this struct is updated + parentUser?: { [key: string]: any; }, parentStruct?: { [key: string]: any; - }, updateServer?: boolean) => Promise; - getUser: (info?: string | number, basicInfo?: boolean, callback?: (data: any) => void) => Promise<{ + }, updateServer?: boolean): Promise; + getUser: (info?: string | number, callback?: (data: any) => void) => Promise<{ user: ProfileStruct; - groups: GroupStruct[]; - authorizations: AuthorizationStruct[]; + groups: []; + authorizations: []; }>; - queryUsers: (info: string, skip?: number, limit?: number, callback?: (data: any) => void) => Promise; - getUsers: (ids?: (string | number)[], basicInfo?: boolean, callback?: (data: any) => void) => Promise; + getUsers: (ids?: (string | number)[], callback?: (data: any) => void) => Promise; getUsersByRole: (userRole: string, callback?: (data: any) => void) => Promise; - getAllUserData: (ownerId: string | number, excluded?: any[], timeRange?: [number | TimeSpecifier, number | TimeSpecifier], callback?: (data: any) => void) => Promise; - query: (collection: string, mongoQuery?: {}, findOne?: boolean, skip?: number, callback?: (data: any) => void) => Promise; - getDataByTimeRange(collection: any, timeRange?: [number | TimeSpecifier, number | TimeSpecifier], ownerId?: string | number | undefined, limit?: number, skip?: number, key?: string): Promise; + getAllUserData: (ownerId: string | number, excluded?: any[], callback?: (data: any) => void) => Promise; + query: (collection: string, queryObj?: {}, findOne?: boolean, skip?: number, callback?: (data: any) => void) => Promise; getData: (collection: string, ownerId?: string | number | undefined, searchDict?: any, limit?: number, skip?: number, callback?: (data: any) => void) => Promise; getDataByIds: (structIds?: any[], ownerId?: string | number | undefined, collection?: string | undefined, callback?: (data: any) => void) => Promise; - getStructParentData: (struct: Struct, callback?: (data: any) => void) => Promise; - setUser: (userStruct: ProfileStruct, callback?: (data: any) => void) => Promise; + getStructParentData: (struct: any, callback?: (data: any) => void) => Promise; + setUser: (userStruct?: {}, callback?: (data: any) => void) => Promise; checkUserToken: (usertoken: any, user?: User, callback?: (data: any) => void) => Promise; setData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; updateServerData: (structs?: Partial | Partial[], notify?: boolean, callback?: (data: any) => void) => Promise; deleteData: (structs?: any[], callback?: (data: any) => void) => Promise; - deleteUser: (userId?: string, deleteData?: boolean, callback?: (data: any) => void) => Promise; - setGroup: (groupStruct: GroupStruct, callback?: (data: any) => void) => Promise; + deleteUser: (userId: any, callback?: (data: any) => void) => Promise; + setGroup: (groupStruct?: {}, callback?: (data: any) => void) => Promise; getUserGroups: (userId?: string, groupId?: string, callback?: (data: any) => void) => Promise; deleteGroup: (groupId: any, callback?: (data: any) => void) => Promise; - setAuthorization: (authorizationStruct: AuthorizationStruct, callback?: (data: any) => void) => Promise; + setAuthorization: (authorizationStruct?: {}, callback?: (data: any) => void) => Promise; getAuthorizations: (userId?: string, authorizationId?: string, callback?: (data: any) => void) => Promise; deleteAuthorization: (authorizationId: any, callback?: (data: any) => void) => Promise; checkForNotifications: (userId?: string) => Promise; @@ -79,15 +64,13 @@ export declare class StructFrontend extends Service { overwriteLocalData(structs: any): void; setLocalData(structs: any): void; getLocalData(collection: any, query?: any): any; - getLocalUserPeerIds: (user?: User) => any; + getLocalUserPeerIds: (user?: User) => any[]; getLocalReplies(struct: any): any; hasLocalAuthorization(otherUserId: any, ownerId?: string): any; - deleteLocalData(structs: Struct[]): boolean; - deleteStruct(struct: Struct): boolean; - stripStruct(struct: Struct): Struct; - createStruct(structType: string, props: { - [key: string]: any; - }, parentUser?: User, parentStruct?: Struct): any; + deleteLocalData(structs: any): boolean; + deleteStruct(struct: any): boolean; + stripStruct(struct?: {}): {}; + createStruct(structType: any, props: any, parentUser?: User, parentStruct?: any): any; userStruct(props?: Partial, currentUser?: boolean): ProfileStruct; authorizeUser: (parentUser: Partial, authorizerUserId?: string, authorizerUserName?: string, authorizedUserId?: string, authorizedUserName?: string, authorizations?: {}, structs?: {}, excluded?: {}, groups?: {}, expires?: boolean) => Promise; addGroup: (parentUser: Partial, name?: string, details?: string, admins?: {}, peers?: {}, clients?: {}, updateServer?: boolean) => Promise; @@ -97,12 +80,8 @@ export declare class StructFrontend extends Service { timestamp: string | number; }; addData: (parentUser: Partial, author?: string, title?: string, type?: string, data?: string | Data[], expires?: boolean, updateServer?: boolean) => Promise; - addEvent: (parentUser: Partial, author?: string, event?: string | number, notes?: string, startTime?: string | number, endTime?: string | number, grade?: string | number, value?: any, units?: string, location?: any, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; - addChatroom: (parentUser: Partial, authorId?: string, message?: string, attachments?: string | Data[], users?: { - [key: string]: true; - }, updateServer?: boolean) => Promise; + addEvent: (parentUser: Partial, author?: string, event?: string, notes?: string, startTime?: number, endTime?: number, grade?: number, attachments?: string | Data[], users?: {}, updateServer?: boolean) => Promise; + addChatroom: (parentUser: Partial, authorId?: string, message?: string, attachments?: string | Data[], users?: {}, updateServer?: boolean) => Promise; addComment: (parentUser: Partial, roomStruct?: { _id: string; users: any[]; diff --git a/src/extras/dist/extras/struct/datastructures/DataStructures.d.ts b/extras/dist/extras/struct/datastructures/DataStructures.d.ts similarity index 100% rename from src/extras/dist/extras/struct/datastructures/DataStructures.d.ts rename to extras/dist/extras/struct/datastructures/DataStructures.d.ts diff --git a/src/extras/dist/extras/struct/datastructures/DataTablet.d.ts b/extras/dist/extras/struct/datastructures/DataTablet.d.ts similarity index 100% rename from src/extras/dist/extras/struct/datastructures/DataTablet.d.ts rename to extras/dist/extras/struct/datastructures/DataTablet.d.ts diff --git a/src/extras/dist/extras/struct/datastructures/index.d.ts b/extras/dist/extras/struct/datastructures/index.d.ts similarity index 100% rename from src/extras/dist/extras/struct/datastructures/index.d.ts rename to extras/dist/extras/struct/datastructures/index.d.ts diff --git a/src/extras/dist/src/extras/struct/datastructures/types.d.ts b/extras/dist/extras/struct/datastructures/types.d.ts similarity index 69% rename from src/extras/dist/src/extras/struct/datastructures/types.d.ts rename to extras/dist/extras/struct/datastructures/types.d.ts index ddb01f54..fd8c6968 100644 --- a/src/extras/dist/src/extras/struct/datastructures/types.d.ts +++ b/extras/dist/extras/struct/datastructures/types.d.ts @@ -1,7 +1,7 @@ -export type ArbitraryObject = { +export declare type ArbitraryObject = { [x: string | number]: any; }; -export type Struct = { +export declare type Struct = { _id: string; structType?: string | number; timestamp?: string | number; @@ -10,17 +10,16 @@ export type Struct = { structType: string; _id: string | number; }; - [key: string]: any; }; -export type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined; -export type StructTypes = LooseStructTypes | DataTypes | 'data' | 'struct' | string | number | undefined; -export type LooseStructTypes = 'coherence' | 'imu' | 'eyetracker' | 'profile' | 'authorization' | 'group' | 'event' | 'chatroom' | 'comment' | 'notification' | 'schedule' | 'date' | string | number | undefined; -export type Data = { +export declare type DataTypes = 'byTime' | 'notes' | 'events' | 'sleep' | 'food' | 'rx' | 'hr' | 'ppg' | 'hrv' | 'ecg' | 'emg' | 'eeg' | 'fnirs' | string | number | undefined; +export declare type StructTypes = LooseStructTypes | DataTypes | 'data' | 'struct' | string | number | undefined; +export declare type LooseStructTypes = 'coherence' | 'imu' | 'eyetracker' | 'profile' | 'authorization' | 'group' | 'event' | 'chatroom' | 'comment' | 'notification' | 'schedule' | 'date' | string | number | undefined; +export declare type Data = { type: string; data: any; timestamp?: string | number; }; -export type DataStruct = { +export declare type DataStruct = { title?: string; author?: string; expires: boolean | number | string; @@ -28,71 +27,61 @@ export type DataStruct = { data: Data[]; tag?: string | number; } & Struct; -export type EventStruct = { +export declare type EventStruct = { event: string; author: string; startTime: string; - endTime?: string; - grade?: string | number; - value?: any; - units?: string; - notes?: string; - location?: any; - attachments?: Data | string | number[]; - users?: { - [key: string]: true; - }; + endTime: string; + grade: string | number; + notes: string; + attachments: Data | string | number[]; + users: {}; tag?: string | number; } & Struct; -export type ChatroomStruct = { +export declare type ChatroomStruct = { message: string; topic: string; author: string; attachments: Data | string | number[]; comments: string[]; replies: string[]; - users: { - [key: string]: true; - }; + users: {}; audioChatActive: boolean; videoChatActive: boolean; tag?: string | number; } & Struct; -export type CommentStruct = { +export declare type CommentStruct = { author: string; replyTo: string; attachments: Data | string | number[]; replies: string[]; - users: { - [key: string]: true; - }; + users: {}; tag?: string | number; } & Struct; -export type NotificationStruct = { +export declare type NotificationStruct = { note: string; parentUserId: string; tag?: string | number; } & Struct; -export type ScheduleStruct = { +export declare type ScheduleStruct = { title: string; author: string; attachments: Data | string | number[]; dates: string[]; tag?: string | number; } & Struct; -export type DateStruct = { +export declare type DateStruct = { timeSet: string | number; notes: string; recurs: number | string | boolean; attachments: Data | string | number[]; tag?: string | number; } & Struct; -export type ProfileStruct = { - username?: string; +export declare type ProfileStruct = { + username: string; name?: string; firstName?: string; lastName?: string; - fullName?: string; email?: string; phone?: string; sex?: string; @@ -101,13 +90,10 @@ export type ProfileStruct = { socials?: {}; data?: {}; type?: string; - hidden?: boolean; - pictureUrl: string; - accessToken?: string; - refreshToken?: string; + id?: string | number; tag?: string | number; } & Struct; -export type AuthorizationStruct = { +export declare type AuthorizationStruct = { authorizedId: string; authorizedName: string; authorizerId: string; @@ -121,7 +107,7 @@ export type AuthorizationStruct = { associatedAuthId: string | number; tag?: string | number; } & Struct; -export type GroupStruct = { +export declare type GroupStruct = { name: string; details: string; admins: {}; @@ -130,9 +116,9 @@ export type GroupStruct = { users: {}; tag?: string | number; } & Struct; -type FreqBand = [number[], number[]]; -export type FrequencyBandNames = 'scp' | 'delta' | 'theta' | 'alpha1' | 'alpha2' | 'beta' | 'lowgamma' | 'highgamma'; -export type FrequencyBandsStruct = { +declare type FreqBand = [number[], number[]]; +export declare type FrequencyBandNames = 'scp' | 'delta' | 'theta' | 'alpha1' | 'alpha2' | 'beta' | 'lowgamma' | 'highgamma'; +export declare type FrequencyBandsStruct = { scp: FreqBand | []; delta: FreqBand | []; theta: FreqBand | []; @@ -142,7 +128,7 @@ export type FrequencyBandsStruct = { lowgamma: FreqBand | []; highgamma: FreqBand | []; }; -export type EEGStruct = { +export declare type EEGStruct = { position: { x: number; y: number; @@ -160,7 +146,7 @@ export type EEGStruct = { startTime: number | string; tag?: string | number; } & Struct; -export type CoherenceStruct = { +export declare type CoherenceStruct = { x0: number; y0: number; z0: number; @@ -175,7 +161,7 @@ export type CoherenceStruct = { startTime: number | string; tag?: string | number; } & Struct; -export type FNIRSStruct = { +export declare type FNIRSStruct = { position: { x: number; y: number; @@ -207,7 +193,7 @@ export type FNIRSStruct = { startTime: number | string; tag?: string | number; } & Struct; -export type IMUStruct = { +export declare type IMUStruct = { Ax: number[]; Ay: number[]; Az: number[]; @@ -217,7 +203,7 @@ export type IMUStruct = { startTime: number | string; tag?: string | number; } & Struct; -export type EyeTrackerStruct = { +export declare type EyeTrackerStruct = { count: number; times: number[]; x: number[]; @@ -227,7 +213,7 @@ export type EyeTrackerStruct = { startTime: number | string; tag?: string | number; } & Struct; -export type ECGStruct = { +export declare type ECGStruct = { count: number; times: number[]; raw: number[]; @@ -237,7 +223,7 @@ export type ECGStruct = { startTime: number | string; tag?: string | number; } & Struct; -export type PPGStruct = FNIRSStruct; -export type HRVStruct = ECGStruct; -export type EMGStruct = EEGStruct; +export declare type PPGStruct = FNIRSStruct; +export declare type HRVStruct = ECGStruct; +export declare type EMGStruct = EEGStruct; export {}; diff --git a/src/extras/dist/src/extras/webgl-plot/webglplot.routes.d.ts b/extras/dist/extras/webgl-plot/webglplot.routes.d.ts similarity index 82% rename from src/extras/dist/src/extras/webgl-plot/webglplot.routes.d.ts rename to extras/dist/extras/webgl-plot/webglplot.routes.d.ts index 26ef2e6b..b45c01d2 100644 --- a/src/extras/dist/src/extras/webgl-plot/webglplot.routes.d.ts +++ b/extras/dist/extras/webgl-plot/webglplot.routes.d.ts @@ -1,7 +1,7 @@ import { WorkerInfo } from '../../services/worker/Worker.service'; -import { WebglLinePlotInfo, WebglLinePlotProps, WebglLinePlotUtil, WebglLineProps } from "webgl-plot-utils"; +import { WebglLinePlotInfo, WebglLinePlotProps, WebglLineProps } from "webgl-plot-utils"; import { FilterSettings } from "../algorithms/util/BiquadFilters"; -export { WebglLinePlotUtil, WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo }; +export { WebglLineProps, WebglLinePlotProps, WebglLinePlotInfo }; export declare const webglPlotRoutes: { setupChart: (settings: WebglLinePlotProps) => any; updateChartData: (plot: WebglLinePlotInfo | string, lines?: { diff --git a/src/extras/dist/index.gpu.services.js b/extras/dist/index.gpu.services.esm.js similarity index 57% rename from src/extras/dist/index.gpu.services.js rename to extras/dist/index.gpu.services.esm.js index 90bf9273..2d90ccca 100644 --- a/src/extras/dist/index.gpu.services.js +++ b/extras/dist/index.gpu.services.esm.js @@ -1,4 +1,4 @@ -(()=>{var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value2)=>{this.data[key]=value2;this.triggerEvent(key,value2)};triggerEvent=(key,value2)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value2)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub2=>{return this.unsubscribeEvent(statesubKey,sub2)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value2=>{refObject[refKey]=value2},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub2)=>{let triggers=this.triggers[key];if(triggers){if(sub2===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub2;let changed=value2=>{onchange(value2);this.unsubscribeEvent(key,sub2)};sub2=this.subscribeEvent(key,changed);return sub2};getEvent=(key,sub2)=>{if(typeof sub2!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub2)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value2,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value2,receiver)}return Reflect.set(target,prop,value2,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub2=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub2);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub2;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub2};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub2;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub2}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub2;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub2}};__unsubscribe=(sub2,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub2)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub2)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub2=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub2);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value2=>{obj[k]=value2},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub2=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub2)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub2;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub2)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub2)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub2;if(nd instanceof GraphNode){const doSub=()=>{sub2=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)nd.__unsubscribe(sub2,key,subInput);sub2=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub2===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub2=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub2=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput);sub2=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub2=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub2};unsubscribe=(node,sub2,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub2,key,subInput)}else return this.get(node)?.__unsubscribe(sub2,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require2=(x2=>typeof __require!=="undefined"?__require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof __require!=="undefined"?__require:a)[b]}):x2)(function(x2){if(typeof __require!=="undefined")return __require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require22(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_gpu_browser_min=__commonJS({"src/gpu-browser.min.js"(exports,module){"use strict";(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}f()}})(function(){var define2,module2,exports2;return function(){function r(e,n,t){function o(i2,f){if(!n[i2]){if(!e[i2]){var c="function"==typeof __require2&&__require2;if(!f&&c)return c(i2,true);if(u)return u(i2,true);var a=new Error("Cannot find module '"+i2+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i2]={exports:{}};e[i2][0].call(p.exports,function(r2){var n2=e[i2][1][r2];return o(n2||r2)},p,p.exports,r,e,n,t)}return n[i2].exports}for(var u="function"==typeof __require2&&__require2,i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType2(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name2,prec){return new TokenType(name2,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name2,options){if(options===void 0)options={};options.keyword=name2;return keywords$1[name2]=new TokenType(name2,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position2(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation2(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start,end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser2(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse2(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports5);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports5){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports5,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports5,node.declaration.declarations)}else{this.checkExport(exports5,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports5);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value2=this.value;node=this.parseLiteral(value2.value);node.regex={pattern:value2.pattern,flags:value2.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value2){var node=this.startNode();node.value=value2;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref2){if(ref2===void 0)ref2={};var isTagged=ref2.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name2)>-1||scope.var.indexOf(name2)>-1;scope.lexical.push(name2);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name2]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name2)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name2)>-1}else{redeclared=scope$2.lexical.indexOf(name2)>-1||scope$2.var.indexOf(name2)>-1}scope$2.functions.push(name2)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name2)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name2)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name2)>-1){redeclared=true;break}scope$3.var.push(name2);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name2]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name2+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node2(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext2(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState2(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state2){var validFlags=state2.validFlags;var flags=state2.flags;for(var i=0;i-1){this.raise(state2.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state2){this.regexp_pattern(state2);if(!state2.switchN&&this.options.ecmaVersion>=9&&state2.groupNames.length>0){state2.switchN=true;this.regexp_pattern(state2)}};pp$8.regexp_pattern=function(state2){state2.pos=0;state2.lastIntValue=0;state2.lastStringValue="";state2.lastAssertionIsQuantifiable=false;state2.numCapturingParens=0;state2.maxBackReference=0;state2.groupNames.length=0;state2.backReferenceNames.length=0;this.regexp_disjunction(state2);if(state2.pos!==state2.source.length){if(state2.eat(41)){state2.raise("Unmatched ')'")}if(state2.eat(93)||state2.eat(125)){state2.raise("Lone quantifier brackets")}}if(state2.maxBackReference>state2.numCapturingParens){state2.raise("Invalid escape")}for(var i=0,list=state2.backReferenceNames;i=9){lookbehind=state2.eat(60)}if(state2.eat(61)||state2.eat(33)){this.regexp_disjunction(state2);if(!state2.eat(41)){state2.raise("Unterminated group")}state2.lastAssertionIsQuantifiable=!lookbehind;return true}}state2.pos=start;return false};pp$8.regexp_eatQuantifier=function(state2,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state2,noError)){state2.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state2,noError){return state2.eat(42)||state2.eat(43)||state2.eat(63)||this.regexp_eatBracedQuantifier(state2,noError)};pp$8.regexp_eatBracedQuantifier=function(state2,noError){var start=state2.pos;if(state2.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state2)){min=state2.lastIntValue;if(state2.eat(44)&&this.regexp_eatDecimalDigits(state2)){max=state2.lastIntValue}if(state2.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state2)}else if(state2.current()===63){state2.raise("Invalid group")}this.regexp_disjunction(state2);if(state2.eat(41)){state2.numCapturingParens+=1;return true}state2.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state2){return state2.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state2)||this.regexp_eatCharacterClass(state2)||this.regexp_eatUncapturingGroup(state2)||this.regexp_eatCapturingGroup(state2)||this.regexp_eatInvalidBracedQuantifier(state2)||this.regexp_eatExtendedPatternCharacter(state2)};pp$8.regexp_eatInvalidBracedQuantifier=function(state2){if(this.regexp_eatBracedQuantifier(state2,true)){state2.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state2){var ch=state2.current();if(isSyntaxCharacter(ch)){state2.lastIntValue=ch;state2.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state2){var start=state2.pos;var ch=0;while((ch=state2.current())!==-1&&!isSyntaxCharacter(ch)){state2.advance()}return state2.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state2){var ch=state2.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state2.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state2){if(state2.eat(63)){if(this.regexp_eatGroupName(state2)){if(state2.groupNames.indexOf(state2.lastStringValue)!==-1){state2.raise("Duplicate capture group name")}state2.groupNames.push(state2.lastStringValue);return}state2.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state2){state2.lastStringValue="";if(state2.eat(60)){if(this.regexp_eatRegExpIdentifierName(state2)&&state2.eat(62)){return true}state2.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state2){state2.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierStart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierPart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state2){if(this.regexp_eatBackReference(state2)||this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)||state2.switchN&&this.regexp_eatKGroupName(state2)){return true}if(state2.switchU){if(state2.current()===99){state2.raise("Invalid unicode escape")}state2.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state2){var start=state2.pos;if(this.regexp_eatDecimalEscape(state2)){var n=state2.lastIntValue;if(state2.switchU){if(n>state2.maxBackReference){state2.maxBackReference=n}return true}if(n<=state2.numCapturingParens){return true}state2.pos=start}return false};pp$8.regexp_eatKGroupName=function(state2){if(state2.eat(107)){if(this.regexp_eatGroupName(state2)){state2.backReferenceNames.push(state2.lastStringValue);return true}state2.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state2){return this.regexp_eatControlEscape(state2)||this.regexp_eatCControlLetter(state2)||this.regexp_eatZero(state2)||this.regexp_eatHexEscapeSequence(state2)||this.regexp_eatRegExpUnicodeEscapeSequence(state2)||!state2.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state2)||this.regexp_eatIdentityEscape(state2)};pp$8.regexp_eatCControlLetter=function(state2){var start=state2.pos;if(state2.eat(99)){if(this.regexp_eatControlLetter(state2)){return true}state2.pos=start}return false};pp$8.regexp_eatZero=function(state2){if(state2.current()===48&&!isDecimalDigit(state2.lookahead())){state2.lastIntValue=0;state2.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state2){var ch=state2.current();if(ch===116){state2.lastIntValue=9;state2.advance();return true}if(ch===110){state2.lastIntValue=10;state2.advance();return true}if(ch===118){state2.lastIntValue=11;state2.advance();return true}if(ch===102){state2.lastIntValue=12;state2.advance();return true}if(ch===114){state2.lastIntValue=13;state2.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state2){var ch=state2.current();if(isControlLetter(ch)){state2.lastIntValue=ch%32;state2.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(117)){if(this.regexp_eatFixedHexDigits(state2,4)){var lead=state2.lastIntValue;if(state2.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state2.pos;if(state2.eat(92)&&state2.eat(117)&&this.regexp_eatFixedHexDigits(state2,4)){var trail=state2.lastIntValue;if(trail>=56320&&trail<=57343){state2.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state2.pos=leadSurrogateEnd;state2.lastIntValue=lead}return true}if(state2.switchU&&state2.eat(123)&&this.regexp_eatHexDigits(state2)&&state2.eat(125)&&isValidUnicode(state2.lastIntValue)){return true}if(state2.switchU){state2.raise("Invalid unicode escape")}state2.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state2){if(state2.switchU){if(this.regexp_eatSyntaxCharacter(state2)){return true}if(state2.eat(47)){state2.lastIntValue=47;return true}return false}var ch=state2.current();if(ch!==99&&(!state2.switchN||ch!==107)){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state2){state2.lastIntValue=0;var ch=state2.current();if(ch>=49&&ch<=57){do{state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}while((ch=state2.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state2){var ch=state2.current();if(isCharacterClassEscape(ch)){state2.lastIntValue=-1;state2.advance();return true}if(state2.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state2.lastIntValue=-1;state2.advance();if(state2.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state2)&&state2.eat(125)){return true}state2.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state2){var start=state2.pos;if(this.regexp_eatUnicodePropertyName(state2)&&state2.eat(61)){var name2=state2.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state2)){var value2=state2.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state2,name2,value2);return true}}state2.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state2)){var nameOrValue=state2.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state2,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state2,name2,value2){if(!has(state2.unicodeProperties.nonBinary,name2)){state2.raise("Invalid property name")}if(!state2.unicodeProperties.nonBinary[name2].test(value2)){state2.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state2,nameOrValue){if(!state2.unicodeProperties.binary.test(nameOrValue)){state2.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state2){return this.regexp_eatUnicodePropertyValue(state2)};pp$8.regexp_eatCharacterClass=function(state2){if(state2.eat(91)){state2.eat(94);this.regexp_classRanges(state2);if(state2.eat(93)){return true}state2.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state2){while(this.regexp_eatClassAtom(state2)){var left=state2.lastIntValue;if(state2.eat(45)&&this.regexp_eatClassAtom(state2)){var right=state2.lastIntValue;if(state2.switchU&&(left===-1||right===-1)){state2.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state2.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state2){var start=state2.pos;if(state2.eat(92)){if(this.regexp_eatClassEscape(state2)){return true}if(state2.switchU){var ch$1=state2.current();if(ch$1===99||isOctalDigit(ch$1)){state2.raise("Invalid class escape")}state2.raise("Invalid escape")}state2.pos=start}var ch=state2.current();if(ch!==93){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state2){var start=state2.pos;if(state2.eat(98)){state2.lastIntValue=8;return true}if(state2.switchU&&state2.eat(45)){state2.lastIntValue=45;return true}if(!state2.switchU&&state2.eat(99)){if(this.regexp_eatClassControlLetter(state2)){return true}state2.pos=start}return this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)};pp$8.regexp_eatClassControlLetter=function(state2){var ch=state2.current();if(isDecimalDigit(ch)||ch===95){state2.lastIntValue=ch%32;state2.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(120)){if(this.regexp_eatFixedHexDigits(state2,2)){return true}if(state2.switchU){state2.raise("Invalid escape")}state2.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isDecimalDigit(ch=state2.current())){state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}return state2.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isHexDigit(ch=state2.current())){state2.lastIntValue=16*state2.lastIntValue+hexToInt(ch);state2.advance()}return state2.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state2){if(this.regexp_eatOctalDigit(state2)){var n1=state2.lastIntValue;if(this.regexp_eatOctalDigit(state2)){var n2=state2.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state2)){state2.lastIntValue=n1*64+n2*8+state2.lastIntValue}else{state2.lastIntValue=n1*8+n2}}else{state2.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state2){var ch=state2.current();if(isOctalDigit(ch)){state2.lastIntValue=ch-48;state2.advance();return true}state2.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state2,length){var start=state2.pos;state2.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state2=this.regexpState||(this.regexpState=new RegExpValidationState(this));state2.reset(start,pattern,flags);this.validateRegExpFlags(state2);this.validateRegExpPattern(state2);var value2=null;try{value2=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern,flags,value:value2})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos0){recording.pop()}}function insertVariable(name2,value2){variables[name2]=value2}function getEntity(value2){const name2=entityNames[value2];if(name2){return contextName+"."+name2}return value2}function setIndent(spaces){indent=" ".repeat(spaces)}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;recording.push(`${indent}const ${variableName} = ${source};`);contextVariables.push(value2);return variableName}function writePPM(width,height){const sourceVariable=`${contextName}Variable${contextVariables.length}`;const imageVariable=`imageDatum${imageCount}`;recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`);recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`);recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`);recording.push(`${indent}}`);recording.push(`${indent}if (typeof require !== "undefined") {`);recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`);recording.push(`${indent}}`);imageCount++}function addComment(value2){recording.push(`${indent}// ${value2}`)}function checkThrowError(){recording.push(`${indent}(() => { +var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x2+'" is not supported')});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value2)=>{this.data[key]=value2;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub2)=>{let triggers=this.triggers[key];if(triggers){if(!sub2)delete this.triggers[key];else{let sub3=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub3){sub3=i;return true}});if(obj)triggers.splice(sub3,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub2;let changed=value2=>{onchange(value2);this.unsubscribeTrigger(key,sub2)};sub2=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub2)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub2)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub2=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub2);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub2};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub2;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub2=subscribeToFunction(k);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub2}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub2;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub2=subscribeToFunction(k);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub2}};this.__unsubscribe=(sub2,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub2)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub2)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub2=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub2);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value2=>{obj[k]=value2;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value2)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub2;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub2=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub2}}else{sub2=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub2}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub2=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub2}}else{sub2=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub2}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub2;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub2=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub2,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub2=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub2)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub2=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub2).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub2=this.__node.state.subscribeTrigger(node,callback)}}return sub2};this.unsubscribe=(node,sub2,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub2,key,subInput)}else return this.get(node)?.__unsubscribe(sub2,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require2=(x2=>typeof __require!=="undefined"?__require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof __require!=="undefined"?__require:a)[b]}):x2)(function(x2){if(typeof __require!=="undefined")return __require.apply(this,arguments);throw new Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require22(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_gpu_browser_min=__commonJS({"src/gpu-browser.min.js"(exports,module){"use strict";(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}f()}})(function(){var define2,module2,exports2;return function(){function r(e,n,t){function o(i2,f){if(!n[i2]){if(!e[i2]){var c="function"==typeof __require2&&__require2;if(!f&&c)return c(i2,true);if(u)return u(i2,true);var a=new Error("Cannot find module '"+i2+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i2]={exports:{}};e[i2][0].call(p.exports,function(r2){var n2=e[i2][1][r2];return o(n2||r2)},p,p.exports,r,e,n,t)}return n[i2].exports}for(var u="function"==typeof __require2&&__require2,i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType2(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name2,prec){return new TokenType(name2,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name2,options){if(options===void 0)options={};options.keyword=name2;return keywords$1[name2]=new TokenType(name2,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position2(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation2(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start,end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser2(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse2(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports5);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports5){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports5,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports5,node.declaration.declarations)}else{this.checkExport(exports5,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports5);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value2=this.value;node=this.parseLiteral(value2.value);node.regex={pattern:value2.pattern,flags:value2.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value2){var node=this.startNode();node.value=value2;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref2){if(ref2===void 0)ref2={};var isTagged=ref2.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name2)>-1||scope.var.indexOf(name2)>-1;scope.lexical.push(name2);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name2]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name2)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name2)>-1}else{redeclared=scope$2.lexical.indexOf(name2)>-1||scope$2.var.indexOf(name2)>-1}scope$2.functions.push(name2)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name2)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name2)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name2)>-1){redeclared=true;break}scope$3.var.push(name2);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name2]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name2+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node2(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext2(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent2=this.curContext();if(parent2===types$1.f_expr||parent2===types$1.f_stat){return true}if(prevType===types.colon&&(parent2===types$1.b_stat||parent2===types$1.b_expr)){return!parent2.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent2===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState2(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state2){var validFlags=state2.validFlags;var flags=state2.flags;for(var i=0;i-1){this.raise(state2.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state2){this.regexp_pattern(state2);if(!state2.switchN&&this.options.ecmaVersion>=9&&state2.groupNames.length>0){state2.switchN=true;this.regexp_pattern(state2)}};pp$8.regexp_pattern=function(state2){state2.pos=0;state2.lastIntValue=0;state2.lastStringValue="";state2.lastAssertionIsQuantifiable=false;state2.numCapturingParens=0;state2.maxBackReference=0;state2.groupNames.length=0;state2.backReferenceNames.length=0;this.regexp_disjunction(state2);if(state2.pos!==state2.source.length){if(state2.eat(41)){state2.raise("Unmatched ')'")}if(state2.eat(93)||state2.eat(125)){state2.raise("Lone quantifier brackets")}}if(state2.maxBackReference>state2.numCapturingParens){state2.raise("Invalid escape")}for(var i=0,list=state2.backReferenceNames;i=9){lookbehind=state2.eat(60)}if(state2.eat(61)||state2.eat(33)){this.regexp_disjunction(state2);if(!state2.eat(41)){state2.raise("Unterminated group")}state2.lastAssertionIsQuantifiable=!lookbehind;return true}}state2.pos=start;return false};pp$8.regexp_eatQuantifier=function(state2,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state2,noError)){state2.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state2,noError){return state2.eat(42)||state2.eat(43)||state2.eat(63)||this.regexp_eatBracedQuantifier(state2,noError)};pp$8.regexp_eatBracedQuantifier=function(state2,noError){var start=state2.pos;if(state2.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state2)){min=state2.lastIntValue;if(state2.eat(44)&&this.regexp_eatDecimalDigits(state2)){max=state2.lastIntValue}if(state2.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state2)}else if(state2.current()===63){state2.raise("Invalid group")}this.regexp_disjunction(state2);if(state2.eat(41)){state2.numCapturingParens+=1;return true}state2.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state2){return state2.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state2)||this.regexp_eatCharacterClass(state2)||this.regexp_eatUncapturingGroup(state2)||this.regexp_eatCapturingGroup(state2)||this.regexp_eatInvalidBracedQuantifier(state2)||this.regexp_eatExtendedPatternCharacter(state2)};pp$8.regexp_eatInvalidBracedQuantifier=function(state2){if(this.regexp_eatBracedQuantifier(state2,true)){state2.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state2){var ch=state2.current();if(isSyntaxCharacter(ch)){state2.lastIntValue=ch;state2.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state2){var start=state2.pos;var ch=0;while((ch=state2.current())!==-1&&!isSyntaxCharacter(ch)){state2.advance()}return state2.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state2){var ch=state2.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state2.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state2){if(state2.eat(63)){if(this.regexp_eatGroupName(state2)){if(state2.groupNames.indexOf(state2.lastStringValue)!==-1){state2.raise("Duplicate capture group name")}state2.groupNames.push(state2.lastStringValue);return}state2.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state2){state2.lastStringValue="";if(state2.eat(60)){if(this.regexp_eatRegExpIdentifierName(state2)&&state2.eat(62)){return true}state2.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state2){state2.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierStart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierPart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state2){if(this.regexp_eatBackReference(state2)||this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)||state2.switchN&&this.regexp_eatKGroupName(state2)){return true}if(state2.switchU){if(state2.current()===99){state2.raise("Invalid unicode escape")}state2.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state2){var start=state2.pos;if(this.regexp_eatDecimalEscape(state2)){var n=state2.lastIntValue;if(state2.switchU){if(n>state2.maxBackReference){state2.maxBackReference=n}return true}if(n<=state2.numCapturingParens){return true}state2.pos=start}return false};pp$8.regexp_eatKGroupName=function(state2){if(state2.eat(107)){if(this.regexp_eatGroupName(state2)){state2.backReferenceNames.push(state2.lastStringValue);return true}state2.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state2){return this.regexp_eatControlEscape(state2)||this.regexp_eatCControlLetter(state2)||this.regexp_eatZero(state2)||this.regexp_eatHexEscapeSequence(state2)||this.regexp_eatRegExpUnicodeEscapeSequence(state2)||!state2.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state2)||this.regexp_eatIdentityEscape(state2)};pp$8.regexp_eatCControlLetter=function(state2){var start=state2.pos;if(state2.eat(99)){if(this.regexp_eatControlLetter(state2)){return true}state2.pos=start}return false};pp$8.regexp_eatZero=function(state2){if(state2.current()===48&&!isDecimalDigit(state2.lookahead())){state2.lastIntValue=0;state2.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state2){var ch=state2.current();if(ch===116){state2.lastIntValue=9;state2.advance();return true}if(ch===110){state2.lastIntValue=10;state2.advance();return true}if(ch===118){state2.lastIntValue=11;state2.advance();return true}if(ch===102){state2.lastIntValue=12;state2.advance();return true}if(ch===114){state2.lastIntValue=13;state2.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state2){var ch=state2.current();if(isControlLetter(ch)){state2.lastIntValue=ch%32;state2.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(117)){if(this.regexp_eatFixedHexDigits(state2,4)){var lead=state2.lastIntValue;if(state2.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state2.pos;if(state2.eat(92)&&state2.eat(117)&&this.regexp_eatFixedHexDigits(state2,4)){var trail=state2.lastIntValue;if(trail>=56320&&trail<=57343){state2.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state2.pos=leadSurrogateEnd;state2.lastIntValue=lead}return true}if(state2.switchU&&state2.eat(123)&&this.regexp_eatHexDigits(state2)&&state2.eat(125)&&isValidUnicode(state2.lastIntValue)){return true}if(state2.switchU){state2.raise("Invalid unicode escape")}state2.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state2){if(state2.switchU){if(this.regexp_eatSyntaxCharacter(state2)){return true}if(state2.eat(47)){state2.lastIntValue=47;return true}return false}var ch=state2.current();if(ch!==99&&(!state2.switchN||ch!==107)){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state2){state2.lastIntValue=0;var ch=state2.current();if(ch>=49&&ch<=57){do{state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}while((ch=state2.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state2){var ch=state2.current();if(isCharacterClassEscape(ch)){state2.lastIntValue=-1;state2.advance();return true}if(state2.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state2.lastIntValue=-1;state2.advance();if(state2.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state2)&&state2.eat(125)){return true}state2.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state2){var start=state2.pos;if(this.regexp_eatUnicodePropertyName(state2)&&state2.eat(61)){var name2=state2.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state2)){var value2=state2.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state2,name2,value2);return true}}state2.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state2)){var nameOrValue=state2.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state2,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state2,name2,value2){if(!has(state2.unicodeProperties.nonBinary,name2)){state2.raise("Invalid property name")}if(!state2.unicodeProperties.nonBinary[name2].test(value2)){state2.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state2,nameOrValue){if(!state2.unicodeProperties.binary.test(nameOrValue)){state2.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state2){return this.regexp_eatUnicodePropertyValue(state2)};pp$8.regexp_eatCharacterClass=function(state2){if(state2.eat(91)){state2.eat(94);this.regexp_classRanges(state2);if(state2.eat(93)){return true}state2.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state2){while(this.regexp_eatClassAtom(state2)){var left=state2.lastIntValue;if(state2.eat(45)&&this.regexp_eatClassAtom(state2)){var right=state2.lastIntValue;if(state2.switchU&&(left===-1||right===-1)){state2.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state2.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state2){var start=state2.pos;if(state2.eat(92)){if(this.regexp_eatClassEscape(state2)){return true}if(state2.switchU){var ch$1=state2.current();if(ch$1===99||isOctalDigit(ch$1)){state2.raise("Invalid class escape")}state2.raise("Invalid escape")}state2.pos=start}var ch=state2.current();if(ch!==93){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state2){var start=state2.pos;if(state2.eat(98)){state2.lastIntValue=8;return true}if(state2.switchU&&state2.eat(45)){state2.lastIntValue=45;return true}if(!state2.switchU&&state2.eat(99)){if(this.regexp_eatClassControlLetter(state2)){return true}state2.pos=start}return this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)};pp$8.regexp_eatClassControlLetter=function(state2){var ch=state2.current();if(isDecimalDigit(ch)||ch===95){state2.lastIntValue=ch%32;state2.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(120)){if(this.regexp_eatFixedHexDigits(state2,2)){return true}if(state2.switchU){state2.raise("Invalid escape")}state2.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isDecimalDigit(ch=state2.current())){state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}return state2.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isHexDigit(ch=state2.current())){state2.lastIntValue=16*state2.lastIntValue+hexToInt(ch);state2.advance()}return state2.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state2){if(this.regexp_eatOctalDigit(state2)){var n1=state2.lastIntValue;if(this.regexp_eatOctalDigit(state2)){var n2=state2.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state2)){state2.lastIntValue=n1*64+n2*8+state2.lastIntValue}else{state2.lastIntValue=n1*8+n2}}else{state2.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state2){var ch=state2.current();if(isOctalDigit(ch)){state2.lastIntValue=ch-48;state2.advance();return true}state2.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state2,length){var start=state2.pos;state2.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state2=this.regexpState||(this.regexpState=new RegExpValidationState(this));state2.reset(start,pattern,flags);this.validateRegExpFlags(state2);this.validateRegExpPattern(state2);var value2=null;try{value2=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern,flags,value:value2})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos0){recording.pop()}}function insertVariable(name2,value2){variables[name2]=value2}function getEntity(value2){const name2=entityNames[value2];if(name2){return contextName+"."+name2}return value2}function setIndent(spaces){indent=" ".repeat(spaces)}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;recording.push(`${indent}const ${variableName} = ${source};`);contextVariables.push(value2);return variableName}function writePPM(width,height){const sourceVariable=`${contextName}Variable${contextVariables.length}`;const imageVariable=`imageDatum${imageCount}`;recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`);recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`);recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`);recording.push(`${indent}}`);recording.push(`${indent}if (typeof require !== "undefined") {`);recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`);recording.push(`${indent}}`);imageCount++}function addComment(value2){recording.push(`${indent}// ${value2}`)}function checkThrowError(){recording.push(`${indent}(() => { ${indent}const error = ${contextName}.getError(); ${indent}if (error !== ${contextName}.NONE) { ${indent} const names = Object.getOwnPropertyNames(gl); @@ -1262,7 +1262,7 @@ ${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whil void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; - }`;module3.exports={vertexShader}},{}],107:[function(require2,module3,exports3){const lib=require2("./index");const GPU=lib.GPU;for(const p in lib){if(!lib.hasOwnProperty(p))continue;if(p==="GPU")continue;GPU[p]=lib[p]}if(typeof window!=="undefined"){bindTo(window)}if(typeof self!=="undefined"){bindTo(self)}function bindTo(target){if(target.GPUjs)return;Object.defineProperty(target,"GPUjs",{get(){return GPU}})}module3.exports=lib},{"./index":109}],108:[function(require2,module3,exports3){const{gpuMock}=require2("gpu-mock.js");const{utils}=require2("./utils");const{Kernel}=require2("./backend/kernel");const{CPUKernel}=require2("./backend/cpu/kernel");const{HeadlessGLKernel}=require2("./backend/headless-gl/kernel");const{WebGL2Kernel}=require2("./backend/web-gl2/kernel");const{WebGLKernel}=require2("./backend/web-gl/kernel");const{kernelRunShortcut}=require2("./kernel-run-shortcut");const kernelOrder=[HeadlessGLKernel,WebGL2Kernel,WebGLKernel];const kernelTypes=["gpu","cpu"];const internalKernels={"headlessgl":HeadlessGLKernel,"webgl2":WebGL2Kernel,"webgl":WebGLKernel};let validate=true;class GPU{static disableValidation(){validate=false}static enableValidation(){validate=true}static get isGPUSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported)}static get isKernelMapSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.kernelMap)}static get isOffscreenCanvasSupported(){return typeof Worker!=="undefined"&&typeof OffscreenCanvas!=="undefined"||typeof importScripts!=="undefined"}static get isWebGLSupported(){return WebGLKernel.isSupported}static get isWebGL2Supported(){return WebGL2Kernel.isSupported}static get isHeadlessGLSupported(){return HeadlessGLKernel.isSupported}static get isCanvasSupported(){return typeof HTMLCanvasElement!=="undefined"}static get isGPUHTMLImageArraySupported(){return WebGL2Kernel.isSupported}static get isSinglePrecisionSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.isFloatRead&&Kernel2.features.isTextureFloat)}constructor(settings){settings=settings||{};this.canvas=settings.canvas||null;this.context=settings.context||null;this.mode=settings.mode;this.Kernel=null;this.kernels=[];this.functions=[];this.nativeFunctions=[];this.injectedNative=null;if(this.mode==="dev")return;this.chooseKernel();if(settings.functions){for(let i=0;isettings.argumentTypes[argumentName])}function onRequestFallback(args){console.warn("Falling back to CPU");const fallbackKernel=new CPUKernel(source,{argumentTypes:kernelRun.argumentTypes,constantTypes:kernelRun.constantTypes,graphical:kernelRun.graphical,loopMaxIterations:kernelRun.loopMaxIterations,constants:kernelRun.constants,dynamicOutput:kernelRun.dynamicOutput,dynamicArgument:kernelRun.dynamicArguments,output:kernelRun.output,precision:kernelRun.precision,pipeline:kernelRun.pipeline,immutable:kernelRun.immutable,optimizeFloatMemory:kernelRun.optimizeFloatMemory,fixIntegerDivisionAccuracy:kernelRun.fixIntegerDivisionAccuracy,functions:kernelRun.functions,nativeFunctions:kernelRun.nativeFunctions,injectedNative:kernelRun.injectedNative,subKernels:kernelRun.subKernels,strictIntegers:kernelRun.strictIntegers,debug:kernelRun.debug});fallbackKernel.build.apply(fallbackKernel,args);const result=fallbackKernel.run.apply(fallbackKernel,args);kernelRun.replaceKernel(fallbackKernel);return result}function onRequestSwitchKernel(reasons,args,_kernel){if(_kernel.debug){console.warn("Switching kernels")}let newOutput=null;if(_kernel.signature&&!switchableKernels[_kernel.signature]){switchableKernels[_kernel.signature]=_kernel}if(_kernel.dynamicOutput){for(let i=reasons.length-1;i>=0;i--){const reason=reasons[i];if(reason.type==="outputPrecisionMismatch"){newOutput=reason.needed}}}const Constructor=_kernel.constructor;const argumentTypes=Constructor.getArgumentTypes(_kernel,args);const signature=Constructor.getSignature(_kernel,argumentTypes);const existingKernel=switchableKernels[signature];if(existingKernel){existingKernel.onActivate(_kernel);return existingKernel}const newKernel=switchableKernels[signature]=new Constructor(source,{argumentTypes,constantTypes:_kernel.constantTypes,graphical:_kernel.graphical,loopMaxIterations:_kernel.loopMaxIterations,constants:_kernel.constants,dynamicOutput:_kernel.dynamicOutput,dynamicArgument:_kernel.dynamicArguments,context:_kernel.context,canvas:_kernel.canvas,output:newOutput||_kernel.output,precision:_kernel.precision,pipeline:_kernel.pipeline,immutable:_kernel.immutable,optimizeFloatMemory:_kernel.optimizeFloatMemory,fixIntegerDivisionAccuracy:_kernel.fixIntegerDivisionAccuracy,functions:_kernel.functions,nativeFunctions:_kernel.nativeFunctions,injectedNative:_kernel.injectedNative,subKernels:_kernel.subKernels,strictIntegers:_kernel.strictIntegers,debug:_kernel.debug,gpu:_kernel.gpu,validate,returnType:_kernel.returnType,tactic:_kernel.tactic,onRequestFallback,onRequestSwitchKernel,texture:_kernel.texture,mappedTextures:_kernel.mappedTextures,drawBuffersMap:_kernel.drawBuffersMap});newKernel.build.apply(newKernel,args);kernelRun.replaceKernel(newKernel);kernels.push(newKernel);return newKernel}const mergedSettings=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate,onRequestFallback,onRequestSwitchKernel},settingsCopy);const kernel=new this.Kernel(source,mergedSettings);const kernelRun=kernelRunShortcut(kernel);if(!this.canvas){this.canvas=kernel.canvas}if(!this.context){this.context=kernel.context}kernels.push(kernel);return kernelRun}createKernelMap(){let fn;let settings;const argument2Type=typeof arguments[arguments.length-2];if(argument2Type==="function"||argument2Type==="string"){fn=arguments[arguments.length-2];settings=arguments[arguments.length-1]}else{fn=arguments[arguments.length-1]}if(this.mode!=="dev"){if(!this.Kernel.isSupported||!this.Kernel.features.kernelMap){if(this.mode&&kernelTypes.indexOf(this.mode)<0){throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}}}const settingsCopy=upgradeDeprecatedCreateKernelSettings(settings);if(settings&&typeof settings.argumentTypes==="object"){settingsCopy.argumentTypes=Object.keys(settings.argumentTypes).map(argumentName=>settings.argumentTypes[argumentName])}if(Array.isArray(arguments[0])){settingsCopy.subKernels=[];const functions=arguments[0];for(let i=0;i0){throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.')}this.nativeFunctions.push(Object.assign({name:name2,source},settings));return this}injectNative(source){this.injectedNative=source;return this}destroy(){return new Promise((resolve,reject)=>{if(!this.kernels){resolve()}setTimeout(()=>{try{for(let i=0;i{try{accept(run.apply(this,arguments))}catch(e){reject(e)}})};shortcut.replaceKernel=function(replacementKernel){kernel=replacementKernel;bindKernelToShortcut(kernel,shortcut)};bindKernelToShortcut(kernel,shortcut);return shortcut}function bindKernelToShortcut(kernel,shortcut){if(shortcut.kernel){shortcut.kernel=kernel;return}const properties=utils.allPropertiesOf(kernel);for(let i=0;ishortcut.kernel[property]);shortcut.__defineSetter__(property,value2=>{shortcut.kernel[property]=value2})}}shortcut.kernel=kernel}module3.exports={kernelRunShortcut}},{"./utils":114}],112:[function(require2,module3,exports3){const source=`// https://www.shadertoy.com/view/4t2SDh + }`;module3.exports={vertexShader}},{}],107:[function(require2,module3,exports3){const lib=require2("./index");const GPU2=lib.GPU;for(const p in lib){if(!lib.hasOwnProperty(p))continue;if(p==="GPU")continue;GPU2[p]=lib[p]}if(typeof window!=="undefined"){bindTo(window)}if(typeof self!=="undefined"){bindTo(self)}function bindTo(target){if(target.GPU)return;Object.defineProperty(target,"GPU",{get(){return GPU2}})}module3.exports=lib},{"./index":109}],108:[function(require2,module3,exports3){const{gpuMock}=require2("gpu-mock.js");const{utils}=require2("./utils");const{Kernel}=require2("./backend/kernel");const{CPUKernel}=require2("./backend/cpu/kernel");const{HeadlessGLKernel}=require2("./backend/headless-gl/kernel");const{WebGL2Kernel}=require2("./backend/web-gl2/kernel");const{WebGLKernel}=require2("./backend/web-gl/kernel");const{kernelRunShortcut}=require2("./kernel-run-shortcut");const kernelOrder=[HeadlessGLKernel,WebGL2Kernel,WebGLKernel];const kernelTypes=["gpu","cpu"];const internalKernels={"headlessgl":HeadlessGLKernel,"webgl2":WebGL2Kernel,"webgl":WebGLKernel};let validate=true;class GPU2{static disableValidation(){validate=false}static enableValidation(){validate=true}static get isGPUSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported)}static get isKernelMapSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.kernelMap)}static get isOffscreenCanvasSupported(){return typeof Worker!=="undefined"&&typeof OffscreenCanvas!=="undefined"||typeof importScripts!=="undefined"}static get isWebGLSupported(){return WebGLKernel.isSupported}static get isWebGL2Supported(){return WebGL2Kernel.isSupported}static get isHeadlessGLSupported(){return HeadlessGLKernel.isSupported}static get isCanvasSupported(){return typeof HTMLCanvasElement!=="undefined"}static get isGPUHTMLImageArraySupported(){return WebGL2Kernel.isSupported}static get isSinglePrecisionSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.isFloatRead&&Kernel2.features.isTextureFloat)}constructor(settings){settings=settings||{};this.canvas=settings.canvas||null;this.context=settings.context||null;this.mode=settings.mode;this.Kernel=null;this.kernels=[];this.functions=[];this.nativeFunctions=[];this.injectedNative=null;if(this.mode==="dev")return;this.chooseKernel();if(settings.functions){for(let i=0;isettings.argumentTypes[argumentName])}function onRequestFallback(args){console.warn("Falling back to CPU");const fallbackKernel=new CPUKernel(source,{argumentTypes:kernelRun.argumentTypes,constantTypes:kernelRun.constantTypes,graphical:kernelRun.graphical,loopMaxIterations:kernelRun.loopMaxIterations,constants:kernelRun.constants,dynamicOutput:kernelRun.dynamicOutput,dynamicArgument:kernelRun.dynamicArguments,output:kernelRun.output,precision:kernelRun.precision,pipeline:kernelRun.pipeline,immutable:kernelRun.immutable,optimizeFloatMemory:kernelRun.optimizeFloatMemory,fixIntegerDivisionAccuracy:kernelRun.fixIntegerDivisionAccuracy,functions:kernelRun.functions,nativeFunctions:kernelRun.nativeFunctions,injectedNative:kernelRun.injectedNative,subKernels:kernelRun.subKernels,strictIntegers:kernelRun.strictIntegers,debug:kernelRun.debug});fallbackKernel.build.apply(fallbackKernel,args);const result=fallbackKernel.run.apply(fallbackKernel,args);kernelRun.replaceKernel(fallbackKernel);return result}function onRequestSwitchKernel(reasons,args,_kernel){if(_kernel.debug){console.warn("Switching kernels")}let newOutput=null;if(_kernel.signature&&!switchableKernels[_kernel.signature]){switchableKernels[_kernel.signature]=_kernel}if(_kernel.dynamicOutput){for(let i=reasons.length-1;i>=0;i--){const reason=reasons[i];if(reason.type==="outputPrecisionMismatch"){newOutput=reason.needed}}}const Constructor=_kernel.constructor;const argumentTypes=Constructor.getArgumentTypes(_kernel,args);const signature=Constructor.getSignature(_kernel,argumentTypes);const existingKernel=switchableKernels[signature];if(existingKernel){existingKernel.onActivate(_kernel);return existingKernel}const newKernel=switchableKernels[signature]=new Constructor(source,{argumentTypes,constantTypes:_kernel.constantTypes,graphical:_kernel.graphical,loopMaxIterations:_kernel.loopMaxIterations,constants:_kernel.constants,dynamicOutput:_kernel.dynamicOutput,dynamicArgument:_kernel.dynamicArguments,context:_kernel.context,canvas:_kernel.canvas,output:newOutput||_kernel.output,precision:_kernel.precision,pipeline:_kernel.pipeline,immutable:_kernel.immutable,optimizeFloatMemory:_kernel.optimizeFloatMemory,fixIntegerDivisionAccuracy:_kernel.fixIntegerDivisionAccuracy,functions:_kernel.functions,nativeFunctions:_kernel.nativeFunctions,injectedNative:_kernel.injectedNative,subKernels:_kernel.subKernels,strictIntegers:_kernel.strictIntegers,debug:_kernel.debug,gpu:_kernel.gpu,validate,returnType:_kernel.returnType,tactic:_kernel.tactic,onRequestFallback,onRequestSwitchKernel,texture:_kernel.texture,mappedTextures:_kernel.mappedTextures,drawBuffersMap:_kernel.drawBuffersMap});newKernel.build.apply(newKernel,args);kernelRun.replaceKernel(newKernel);kernels.push(newKernel);return newKernel}const mergedSettings=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate,onRequestFallback,onRequestSwitchKernel},settingsCopy);const kernel=new this.Kernel(source,mergedSettings);const kernelRun=kernelRunShortcut(kernel);if(!this.canvas){this.canvas=kernel.canvas}if(!this.context){this.context=kernel.context}kernels.push(kernel);return kernelRun}createKernelMap(){let fn;let settings;const argument2Type=typeof arguments[arguments.length-2];if(argument2Type==="function"||argument2Type==="string"){fn=arguments[arguments.length-2];settings=arguments[arguments.length-1]}else{fn=arguments[arguments.length-1]}if(this.mode!=="dev"){if(!this.Kernel.isSupported||!this.Kernel.features.kernelMap){if(this.mode&&kernelTypes.indexOf(this.mode)<0){throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}}}const settingsCopy=upgradeDeprecatedCreateKernelSettings(settings);if(settings&&typeof settings.argumentTypes==="object"){settingsCopy.argumentTypes=Object.keys(settings.argumentTypes).map(argumentName=>settings.argumentTypes[argumentName])}if(Array.isArray(arguments[0])){settingsCopy.subKernels=[];const functions=arguments[0];for(let i=0;i0){throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.')}this.nativeFunctions.push(Object.assign({name:name2,source},settings));return this}injectNative(source){this.injectedNative=source;return this}destroy(){return new Promise((resolve,reject)=>{if(!this.kernels){resolve()}setTimeout(()=>{try{for(let i=0;i{try{accept(run.apply(this,arguments))}catch(e){reject(e)}})};shortcut.replaceKernel=function(replacementKernel){kernel=replacementKernel;bindKernelToShortcut(kernel,shortcut)};bindKernelToShortcut(kernel,shortcut);return shortcut}function bindKernelToShortcut(kernel,shortcut){if(shortcut.kernel){shortcut.kernel=kernel;return}const properties=utils.allPropertiesOf(kernel);for(let i=0;ishortcut.kernel[property]);shortcut.__defineSetter__(property,value2=>{shortcut.kernel[property]=value2})}}shortcut.kernel=kernel}module3.exports={kernelRunShortcut}},{"./utils":114}],112:[function(require2,module3,exports3){const source=`// https://www.shadertoy.com/view/4t2SDh //note: uniformly distributed, normalized rand, [0,1] highp float randomSeedShift = 1.0; highp float slide = 1.0; @@ -1278,23 +1278,19 @@ ${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whil slide += 0.0009; } return result; - }`;const name2="math-random-uniformly-distributed";const functionMatch=`Math.random()`;const functionReplace=`nrand(vTexCoord)`;const functionReturnType="Number";const onBeforeRun=kernel=>{kernel.setUniform1f("randomSeed1",Math.random());kernel.setUniform1f("randomSeed2",Math.random())};const plugin={name:name2,onBeforeRun,functionMatch,functionReplace,functionReturnType,source};module3.exports=plugin},{}],113:[function(require2,module3,exports3){class Texture{constructor(settings){const{texture,size,dimensions,output,context,type="NumberTexture",kernel,internalFormat,textureFormat}=settings;if(!output)throw new Error('settings property "output" required.');if(!context)throw new Error('settings property "context" required.');if(!texture)throw new Error('settings property "texture" required.');if(!kernel)throw new Error('settings property "kernel" required.');this.texture=texture;if(texture._refs){texture._refs++}else{texture._refs=1}this.size=size;this.dimensions=dimensions;this.output=output;this.context=context;this.kernel=kernel;this.type=type;this._deleted=false;this.internalFormat=internalFormat;this.textureFormat=textureFormat}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}module3.exports={Texture}},{}],114:[function(require2,module3,exports3){const acorn=require2("acorn");const{Input}=require2("./input");const{Texture}=require2("./texture");const FUNCTION_NAME=/function ([^(]*)/;const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const ARGUMENT_NAMES=/([^\s,]+)/g;const utils={systemEndianness(){return _systemEndianness},getSystemEndianness(){const b=new ArrayBuffer(4);const a=new Uint32Array(b);const c=new Uint8Array(b);a[0]=3735928559;if(c[0]===239)return"LE";if(c[0]===222)return"BE";throw new Error("unknown endianness")},isFunction(funcObj){return typeof funcObj==="function"},isFunctionString(fn){if(typeof fn==="string"){return fn.slice(0,"function".length).toLowerCase()==="function"}return false},getFunctionNameFromString(funcStr){const result=FUNCTION_NAME.exec(funcStr);if(!result||result.length===0)return null;return result[1].trim()},getFunctionBodyFromString(funcStr){return funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"))},getArgumentNamesFromString(fn){const fnStr=fn.replace(STRIP_COMMENTS,"");let result=fnStr.slice(fnStr.indexOf("(")+1,fnStr.indexOf(")")).match(ARGUMENT_NAMES);if(result===null){result=[]}return result},clone(obj){if(obj===null||typeof obj!=="object"||obj.hasOwnProperty("isActiveClone"))return obj;const temp=obj.constructor();for(let key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){obj.isActiveClone=null;temp[key]=utils.clone(obj[key]);delete obj.isActiveClone}}return temp},isArray(array){return!isNaN(array.length)},getVariableType(value2,strictIntegers){if(utils.isArray(value2)){if(value2.length>0&&value2[0].nodeName==="IMG"){return"HTMLImageArray"}return"Array"}switch(value2.constructor){case Boolean:return"Boolean";case Number:if(strictIntegers&&Number.isInteger(value2)){return"Integer"}return"Float";case Texture:return value2.type;case Input:return"Input"}switch(value2.nodeName){case"IMG":return"HTMLImage";case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}if(value2.hasOwnProperty("type")){return value2.type}return"Unknown"},getKernelTextureSize(settings,dimensions){let[w,h,d]=dimensions;let texelCount=(w||1)*(h||1)*(d||1);if(settings.optimizeFloatMemory&&settings.precision==="single"){w=texelCount=Math.ceil(texelCount/4)}if(h>1&&w*h===texelCount){return new Int32Array([w,h])}return utils.closestSquareDimensions(texelCount)},closestSquareDimensions(length){const sqrt=Math.sqrt(length);let high=Math.ceil(sqrt);let low=Math.floor(sqrt);while(high*low0){return lines.join(";\n")+";\n"}else{return"\n"}},warnDeprecated(type,oldName,newName){if(newName){console.warn(`You are using a deprecated ${type} "${oldName}". It has been replaced with "${newName}". Fixing, but please upgrade as it will soon be removed.`)}else{console.warn(`You are using a deprecated ${type} "${oldName}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)}},flipPixels:(pixels,width,height)=>{const halfHeight=height/2|0;const bytesPerRow=width*4;const temp=new Uint8ClampedArray(width*4);const result=pixels.slice(0);for(let y=0;y{return array.subarray(0,width)},erect2DPackedFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{return array.subarray(0,width)},erectMemoryOptimized2DFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{const xResults=new Float32Array(width);let i=0;for(let x2=0;x2{const yResults=new Array(height);let i=0;for(let y=0;y{const zResults=new Array(depth);let i=0;for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const yResults=new Array(height);const XResultsMax=width*4;for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(array);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const{findDependency,thisLookup,doNotDefine}=settings;let flattened=settings.flattened;if(!flattened){flattened=settings.flattened={}}const ast=acorn.parse(source);const functionDependencies=[];let indent=0;function flatten2(ast2){if(Array.isArray(ast2)){const results=[];for(let i=0;ir!==null);if(declarations.length<1){return""}else{return`${ast2.kind} ${declarations.join(",")}`}case"VariableDeclarator":if(ast2.init.object&&ast2.init.object.type==="ThisExpression"){const lookup=thisLookup(ast2.init.property.name,true);if(lookup){return`${ast2.id.name} = ${flatten2(ast2.init)}`}else{return null}}else{return`${ast2.id.name} = ${flatten2(ast2.init)}`}case"CallExpression":{if(ast2.callee.property.name==="subarray"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.name==="gl"||ast2.callee.object.name==="context"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.type==="ThisExpression"){functionDependencies.push(findDependency("this",ast2.callee.property.name));return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else if(ast2.callee.object.name){const foundSource=findDependency(ast2.callee.object.name,ast2.callee.property.name);if(foundSource===null){return`${ast2.callee.object.name}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{functionDependencies.push(foundSource);return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}}else if(ast2.callee.object.type==="MemberExpression"){return`${flatten2(ast2.callee.object)}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{throw new Error("unknown ast.callee")}}case"ReturnStatement":return`return ${flatten2(ast2.argument)}`;case"BinaryExpression":return`(${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)})`;case"UnaryExpression":if(ast2.prefix){return`${ast2.operator} ${flatten2(ast2.argument)}`}else{return`${flatten2(ast2.argument)} ${ast2.operator}`}case"ExpressionStatement":return`${flatten2(ast2.expression)}`;case"SequenceExpression":return`(${flatten2(ast2.expressions)})`;case"ArrowFunctionExpression":return`(${ast2.params.map(flatten2).join(", ")}) => ${flatten2(ast2.body)}`;case"Literal":return ast2.raw;case"Identifier":return ast2.name;case"MemberExpression":if(ast2.object.type==="ThisExpression"){return thisLookup(ast2.property.name)}if(ast2.computed){return`${flatten2(ast2.object)}[${flatten2(ast2.property)}]`}return flatten2(ast2.object)+"."+flatten2(ast2.property);case"ThisExpression":return"this";case"NewExpression":return`new ${flatten2(ast2.callee)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`;case"ForStatement":return`for (${flatten2(ast2.init)};${flatten2(ast2.test)};${flatten2(ast2.update)}) ${flatten2(ast2.body)}`;case"AssignmentExpression":return`${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)}`;case"UpdateExpression":return`${flatten2(ast2.argument)}${ast2.operator}`;case"IfStatement":return`if (${flatten2(ast2.test)}) ${flatten2(ast2.consequent)}`;case"ThrowStatement":return`throw ${flatten2(ast2.argument)}`;case"ObjectPattern":return ast2.properties.map(flatten2).join(", ");case"ArrayPattern":return ast2.elements.map(flatten2).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${flatten2(ast2.test)}?${flatten2(ast2.consequent)}:${flatten2(ast2.alternate)}`;case"Property":if(ast2.kind==="init"){return flatten2(ast2.key)}}throw new Error(`unhandled ast.type of ${ast2.type}`)}const result=flatten2(ast);if(functionDependencies.length>0){const flattenedFunctionDependencies=[];for(let i=0;i{if(ast.type!=="VariableDeclaration")throw new Error('Ast is not of type "VariableDeclaration"');const normalizedDeclarations=[];for(let declarationIndex=0;declarationIndex{const rKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.r*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const gKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.g*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const bKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.b*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const aKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.a*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const result=[rKernel(image),gKernel(image),bKernel(image),aKernel(image)];result.rKernel=rKernel;result.gKernel=gKernel;result.bKernel=bKernel;result.aKernel=aKernel;result.gpu=gpu;return result},splitRGBAToCanvases:(gpu,rgba,width,height)=>{const visualKernelR=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(pixel.r/255,0,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelR(rgba);const visualKernelG=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,pixel.g/255,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelG(rgba);const visualKernelB=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,0,pixel.b/255,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelB(rgba);const visualKernelA=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(255,255,255,pixel.a/255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelA(rgba);return[visualKernelR.canvas,visualKernelG.canvas,visualKernelB.canvas,visualKernelA.canvas]},getMinifySafeName:fn=>{try{const ast=acorn.parse(`const value = ${fn.toString()}`);const{init}=ast.body[0].declarations[0];return init.body.name||init.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(name2){if(dollarSign.test(name2)){name2=name2.replace(dollarSign,"S_S")}if(doubleUnderscore.test(name2)){name2=name2.replace(doubleUnderscore,"U_U")}else if(singleUnderscore.test(name2)){name2=name2.replace(singleUnderscore,"u_u")}return name2}};const dollarSign=/\$/;const doubleUnderscore=/__/;const singleUnderscore=/_/;const _systemEndianness=utils.getSystemEndianness();module3.exports={utils}},{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107)})}});var import_gpu_browser_min=__toESM(require_gpu_browser_min());function add(a,b){return a+b}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function cadd(a_real,a_imag,b_real,b_imag){return[a_real+b_real,a_imag+b_imag]}function csub(a_real,a_imag,b_real,b_imag){return[a_real-b_real,a_imag-b_imag]}function cmul(a_real,a_imag,b_real,b_imag){return[a_real*b_real-a_imag*b_imag,a_real*b_imag+a_imag*b_real]}function cexp(a_real,a_imag){const er=Math.exp(a_real);return[er*Math.cos(a_imag),er*Math.sin(a_imag)]}function mag(a,b){return Math.sqrt(a*a+b*b)}function conj(imag){return 0-imag}function lof(n){const sqrt_n=Math.sqrt(n);var factor=3;while(factor<=sqrt_n){if(n%factor===0)return factor;factor+=2}}function mean(arr,len){var mean2=0;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signal[j]*Math.cos(sharedi);imag=imag-signal[j]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function FFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=imag-signals[j+(len-1)*n]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function iDFT(fft,len,freq){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+fft[j]*Math.cos(sharedi);imag=fft[j]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function iFFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=signals[j+(len-1)*n]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function correlogramsKern(arrays,len){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=mean(arrays[k],len);var arr2mean=mean(arrays[k+1],len);var arr1Est=est(arrays[k],arr1mean,len);var arr2Est2=est(arrays[k+1],arr2mean,len);var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function correlogramsPCKern(arrays,len,means,estimators){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=means[k];var arr2mean=means[k+1];var arr1Est=estimators[k];var arr2Est2=estimators[k+1];var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function dftKern(signal,len,scalar){var result=DFT(signal,len,this.thread.x);return mag(result[0],result[1])*scalar}function idftKern(amplitudes,len,scalar){var result=iDFT(amplitudes,len,this.thread.x);return mag(result[0],result[1])*scalar}function fftKern(signal,len,scalar,sampleRate){var result=FFT(signal,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function ifftKern(amplitudes,len,scalar,sampleRate){var result=iFFT(amplitudes,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function listdft2DKern(signals,scalar){var len=this.output.x;var result=DFT(signals[this.thread.y],len,this.thread.x);return mag(result[0],result[1])*scalar}function listdft1DKern(signals,len,scalar){var result=[0,0];if(this.thread.x<=len){result=DFT(signals,len,this.thread.x)}else{var n=Math.floor(this.thread.x/len);result=DFTlist(signals,len,this.thread.x-n*len,n)}return mag(result[0],result[1])*scalar}function listfft1DKern(signals,len,scalar,sps){var result=[0,0];if(this.thread.x<=len){result=FFT(signals,len,this.thread.x,sps)}else{var n=Math.floor(this.thread.x/len);result=FFTlist(signals,len,this.thread.x-n*len,n,sps)}return mag(result[0],result[1])*scalar}function dft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=DFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function fft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=FFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function idft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iDFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function ifft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iFFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function listdft1D_windowedKern(signals,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];if(this.thread.x=width){i++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+i+kernelRadius;const weights=kernel[kernelOffset];const pixel=img[this.thread.y+i][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}i++}this.color(r,g,b)}function multiImgConv2DKern(img,width,height,kernels,kernelLengths,nKernels){let r=0,g=0,b=0;for(var i=0;i=width){k++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+k+kernelRadius;const weights=kernels[i][kernelOffset];const pixel=img[this.thread.y+k][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}k++}}this.color(r,g,b)}function transpose2DKern(mat2){return mat2[this.thread.y][this.thread.x]}var createGpuKernels={correlogramsKern,correlogramsPCKern,dftKern,idftKern,fftKern,ifftKern,dft_windowedKern,idft_windowedKern,fft_windowedKern,ifft_windowedKern,listdft2DKern,listdft1DKern,listfft1DKern,listfft1D_windowedKern,listdft1D_windowedKern,listidft1D_windowedKern,listifft1D_windowedKern,bulkArrayMulKern,multiImgConv2DKern,ImgConv2DKern,transpose2DKern};var addGpuFunctions=[add,sub,mul,div,cadd,csub,cmul,cexp,mag,conj,lof,mean,est,mse,rms,xcor,softmax,DFT,DFTlist,iDFT,iDFTlist,FFT,iFFT,iFFTlist];function makeKrnl(gpu,f,opts={setDynamicOutput:true,setDynamicArguments:true,setPipeline:true,setImmutable:true,setGraphical:false}){const k=gpu.createKernel(f);if(opts.setDynamicOutput)k.setDynamicOutput(true);if(opts.output)k.setOutput(opts.output);if(opts.setDynamicArguments)k.setDynamicArguments(true);if(opts.setPipeline)k.setPipeline(true);if(opts.setImmutable)k.setImmutable(true);if(opts.setGraphical)k.setGraphical(true);return k}function makeCanvasKrnl(gpu,f,opts={output:[300,300],setDynamicArguments:true,setDynamicOutput:true,setPipeline:false,setImmutable:true,setGraphical:true},divId){const k=makeKrnl(gpu,f,opts);const canvas=k.canvas;if(typeof divId==="string")document.getElementById(toAppend).appendChild(canvas);else if(divId)toAppend.appendChild(canvas);else document.body.appendChild(canvas);return k}var gpuUtils=class{constructor(gpu=new GPUjs){this.gpu=gpu;this.kernels=new Map;this.kernel;this.PI=3.141592653589793;this.SQRT1_2=.7071067811865476;this.addFunctions();this.imgkernels={edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],sobelLeft:[1,0,-1,2,0,-2,1,0,-1],sobelRight:[-1,0,1,-2,0,2,-1,0,1],sobelTop:[1,2,1,0,0,0,-1,-2,-1],sobelBottom:[-1,2,1,0,0,0,1,2,1],identity:[0,0,0,0,1,0,0,0,0],gaussian3x3:[1,2,1,2,4,2,1,2,1],guassian7x7:[0,0,0,5,0,0,0,0,5,18,32,18,5,0,0,18,64,100,64,18,0,5,32,100,100,100,32,5,0,18,64,100,64,18,0,0,5,18,32,18,5,0,0,0,0,5,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0]}}addFunction(func=function f(){}){this.gpu.addFunction(func)}addKernel(name2="",krnl=function foo(){},opts){let found=this.kernels.get(name2);if(!found){this.kernels.set(name2,makeKrnl(this.gpu,krnl,opts));return true}else{console.error("Kernel already exists");return false}}addCanvasKernel(name2,f,opts,divId){let found=this.kernels.get(name2);if(!found){let krnl=makeCanvasKrnl(this.gpu,f,opts,divId);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}combineKernels(name2,fs=[],ckrnl=function foo(){}){let found=this.kernels.get(name2);if(!found){fs.forEach((f,i)=>{if(typeof f==="string"){let found2=this.kernels.get(f);if(found2)fs[i]=found2;else return false}else if(typeof f==="function"){if(this.kernels.get(f.name)){}else{this.addKernel(f.name,f)}}});let krnl=this.gpu.combineKernels(...fs,ckrnl);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}callKernel(name2="",args=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}result=krnl(...args);return result}callCanvasKernel(name2="",args=[],outputDims=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}else{if(outputDims.length===2)krnl.setOutput(outputDims);result=krnl(...args);return result}}hasKernel(name2=""){let found=this.kernels.get(name2);if(!found){return false}else return true}addFunctions(){addGpuFunctions.forEach(f=>this.gpu.addFunction(f));this.correlograms=makeKrnl(this.gpu,createGpuKernels.correlogramsKern);this.correlogramsPC=makeKrnl(this.gpu,createGpuKernels.correlogramsPCKern);this.dft=makeKrnl(this.gpu,createGpuKernels.dftKern);this.idft=makeKrnl(this.gpu,createGpuKernels.idftKern);this.dft_windowed=makeKrnl(this.gpu,createGpuKernels.dft_windowedKern);this.idft_windowed=makeKrnl(this.gpu,createGpuKernels.idft_windowedKern);this.fft=makeKrnl(this.gpu,createGpuKernels.fftKern);this.ifft=makeKrnl(this.gpu,createGpuKernels.ifftKern);this.fft_windowed=makeKrnl(this.gpu,createGpuKernels.fft_windowedKern);this.ifft_windowed=makeKrnl(this.gpu,createGpuKernels.ifft_windowedKern);this.listdft2D=makeKrnl(this.gpu,createGpuKernels.listdft2DKern);this.listdft1D=makeKrnl(this.gpu,createGpuKernels.listdft1DKern);this.listdft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listdft1D_windowedKern);this.listfft1D=makeKrnl(this.gpu,createGpuKernels.listfft1DKern);this.listfft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listfft1D_windowedKern);this.listidft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listidft1D_windowedKern);this.listifft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listifft1D_windowedKern);this.bulkArrayMul=makeKrnl(this.gpu,createGpuKernels.bulkArrayMulKern);let kernels=[{name:"correlograms",krnl:this.correlograms},{name:"correlogramsPC",krnl:this.correlogramsPC},{name:"dft",krnl:this.dft},{name:"idft",krnl:this.idft},{name:"dft_windowed",krnl:this.idft_windowed},{name:"fft",krnl:this.fft},{name:"ifft",krnl:this.ifft},{name:"fft_windowed",krnl:this.fft_windowed},{name:"ifft_windowed",krnl:this.ifft_windowed},{name:"listdft2D",krnl:this.listdft2D},{name:"listdft1D",krnl:this.listdft1D},{name:"listdft1D_windowed",krnl:this.listdft1D_windowed},{name:"listfft1D",krnl:this.listfft1D},{name:"listfft1D_windowed",krnl:this.listfft1D_windowed},{name:"listidft1D_windowed",krnl:this.listidft1D_windowed},{name:"listifft1D_windowed",krnl:this.listifft1D_windowed},{name:"bulkArrayMul",krnl:this.bulkArrayMul}];kernels.forEach(k=>{this.kernels.set(k.name,k)});const signalBandpass=(signal,sampleRate,freqStart,freqEnd,scalar)=>{var dft2=this.fft_windowed(signal,sampleRate,freqStart,freqEnd,scalar,0);var filtered_signal=this.ifft_windowed(dft2,sampleRate,freqStart,freqEnd,scalar);return filtered_signal};const signalBandpassMulti=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var dfts=this.listdft1D_windowed(signals,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var filtered_signals=this.listifft1D_windowed(dfts,sampleRate,freqStart,freqEnd,scalar);return filtered_signals};this.gpuCoherence=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var xcors=this.correlograms(signals);var dfts=this.listfft1D_windowed(xcors,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var products=this.bulkArrayMul(dfts,sampleRate,5,1);return products}}gpuXCors(arrays,precompute=false,texOut=false){var outputTex;if(precompute===true){var means=[];var ests=[];arrays.forEach((arr,i2)=>{means.push(arr.reduce((prev,curr)=>curr+=prev)/arr.length);ests.push(Math.sqrt(means[i2].reduce((sum,item)=>sum+=Math.pow(item-mean1,2))))});var meansbuf=[];var estsbuf=[];var buffer=[];for(var i=0;i{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D.setOutput([signalBufferProcessed.length]);this.listdft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D(signalBufferProcessed,nSamplesPerChannel,scalar);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D_windowed.setOutput([signalBufferProcessed.length]);this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}gpuFFT(signalBuffer,nSeconds,scalar=1,sampleRate,texOut=false){var nSamples=signalBuffer.length;var sampleRate=nSamples/nSeconds;this.fft.setOutput([signalBuffer.length]);this.fft.setLoopMaxIterations(nSamples);var outputTex=this.fft(signalBuffer,nSamples,scalar,sampleRate);var output=null;if(texOut===false){var freqDist=this.makeFrequencyDistribution(nSamples,sampleRate);var signalBufferProcessed=outputTex.toArray();outputTex.delete();return[freqDist,this.orderMagnitudes(signalBufferProcessed)]}else{var tex=outputTex;outputTex.delete();return tex}}MultiChannelFFT(signalBuffer,nSeconds,scalar=1,texOut=false){var signalBufferProcessed=[];signalBuffer.forEach(row=>{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D.setOutput([signalBufferProcessed.length]);this.listfft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D(signalBufferProcessed,nSamplesPerChannel,scalar,sampleRate);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D_windowed.setOutput([signalBufferProcessed.length]);this.listfft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}orderMagnitudes(unorderedMags){return[...unorderedMags.slice(Math.ceil(unorderedMags.length*.5),unorderedMags.length),...unorderedMags.slice(0,Math.ceil(unorderedMags.length*.5))]}makeFrequencyDistribution(FFTlength,sampleRate){var N=FFTlength;var df=sampleRate/N;var freqDist=[];for(var i=-N/2;i1){magList.forEach((row,k)=>{summedMags.push([]);var _max=1/Math.max(...row);for(var i2=0;i2{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean2=void 0)=>{let avg=mean2;if(!mean2)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean2=this.mean(arr);let std=this.std(arr,mean2);let z=new Array(arr.length);for(let i=0;ia+(b-mean2)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean2=this.mean(arr);let std=this.std(arr,mean2);return populationMean?std/populationMean:std/mean2};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y)=>acc+Math.pow(y-meanY,2),0);const ssResidual=observed.reduce((acc,y,i)=>acc+Math.pow(y-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x2)=>sum+x2,0);const sumY=yCoords.reduce((sum,y)=>sum+y,0);const sumXY=xCoords.reduce((sum,x2,i)=>sum+x2*yCoords[i],0);const sumX2=xCoords.reduce((sum,x2)=>sum+x2*x2,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{return vec.map((v,i)=>v-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v,i)=>v/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v,i)=>v+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v,i)=>v-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v,i)=>v/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x2,y,z)=>{var r=Math.sqrt(x2*x2+y*y+z*z);var theta=Math.atan2(y,x2);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y=x2;return y},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x2=Math.cos(t);return x2},yFunc=t=>{let y=Math.sin(t);return y},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u,v)=>u,yFunc=(u,v)=>v,zFunc=(u,v)=>u+v,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u=rangeU[0];u{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value2,index)=>{const row=Array(values.length).fill(0);row[index]=value2;return row})};static householderMatrix=v=>{const size=v.length;const vvT=v.map(rowVal=>v.map(colVal=>rowVal*colVal));const vTv=this.normalize(v)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A,B)=>{return A.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean2=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value2=>(value2-min)/(max-min))};static garroteThreshold=(data,value2)=>{return data.map(x2=>{if(Math.abs(x2)<=value2){return 0}else{return x2-value2*value2/x2}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean12=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v,i)=>(v-mean12)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x2,x2),this.cov1d(x2,y),this.cov1d(x2,z)],[this.cov1d(y,x2),this.cov1d(y,y),this.cov1d(y,z)],[this.cov1d(z,x2),this.cov1d(z,y),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean2=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean2*mean2-det);let eig1=mean2+sqrt;let eig2=mean2-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean2=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v=>v-mean2)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N=signalA.length;const M=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean12=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(delaybuf[delay+i]-mean12));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x2=arr.filter((element,index)=>{return index%factor===0});return x2};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y=>y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x2)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A,numIter=100)=>{let b=Array(A.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A[0].length>A.length){A=this.transpose(A)}const m=A.length;const n=A[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x2):this.normalize(x2);const u=this.vecsub(x2,e);const normU=this.normalize(u);const v=u.map(val=>val/normU);const Qk=this.householderMatrix(v);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean2=this.mean(smoothed);let std=this.std(smoothed,mean2);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean2)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean2)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}}}return value2}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value2==="function"?value2.toString():value2,path.join("."))}}}return typeof value2==="function"?value2.toString():value2}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx++}}}}}function checkValues(key,value2){let val;if(value2!=null){if(typeof value2==="object"){let c=value2.constructor.name;if(key&&c==="Object"){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}if(c==="Array"){if(value2.length>20){val=value2.slice(value2.length-20)}else val=value2}else if(c.includes("Set")){val=Array.from(value2)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value2){if(value2[prop]==null){obj[prop]=value2[prop]}else if(Array.isArray(value2[prop])){if(value2[prop].length>20)obj[prop]=value2[prop].slice(value2[prop].length-20);else obj[prop]=value2[prop]}else if(value2[prop].constructor.name==="Object"){obj[prop]={};for(const p in value2[prop]){if(Array.isArray(value2[prop][p])){if(value2[prop][p].length>20)obj[prop][p]=value2[prop][p].slice(value2[prop][p].length-20);else obj[prop][p]=value2[prop][p]}else{if(value2[prop][p]!=null){let con=value2[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value2[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value2[prop][p]}}else{obj[prop][p]=value2[prop][p]}}}}else{let con=value2[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value2[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value2[prop]}}}val=obj}else{val=value2}}else{val=value2}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var GPUService=class extends Service{gpu=new gpuUtils;constructor(options){super(options);this.load(this)}addFunc=fn=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addFunction(fn)};addKernel=(name2,fn,options)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addKernel(name2,fn,options)};combineKernels=(name2,fs,ckrnl)=>{for(let i=0;i{this.gpu.callKernel(name2,args)};dft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.gpuDFT(signalBuffer,nSeconds,scalar)};multidft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT(signalBuffer,nSeconds,scalar)};multidftbandpass=(buffered,nSeconds,freqStart,freqEnd,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT_Bandpass(buffered,nSeconds,freqStart,freqEnd,scalar)};coherence=(buffered,nSeconds,freqStart,freqEnd)=>{const correlograms=Math2.correlograms(buffered);const buffer=[...buffered,...correlograms];var dfts;var scalar=1;dfts=this.gpu.MultiChannelDFT_Bandpass(buffer,nSeconds,freqStart,freqEnd,scalar);const cordfts=dfts[1].splice(buffered.length,buffer.length-buffered.length);const coherenceResults=[];const nChannels=buffered.length;var k=0;var l=0;cordfts.forEach((row,i)=>{if(l+k===nChannels){var temp=cordfts.splice(i,1);k++;cordfts.splice(k,0,...temp);l=0}l++});var autoFFTproducts=[];k=0;l=1;cordfts.forEach((dft2,i)=>{var newdft=new Array(dft2.length).fill(0);if(i{newdft[j]=amp});autoFFTproducts.push(newdft)}else{dft2.forEach((amp,j)=>{let denom=autoFFTproducts[k][j]*autoFFTproducts[k+l][j];if(denom!==0)newdft[j]=amp*amp/denom;else newdft[j]=0;if(newdft[j]>1){newdft[j]=1}});l++;if(l+k===nChannels){k++;l=1}coherenceResults.push(newdft)}});return[dfts[0],dfts[1],coherenceResults]}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var dft={sps:250,nSec:1,freqStart:0,freqEnd:125,watch:["0","1","2","3"],blocking:false,__operator:function(arraybuffer){let results=globalThis.gpu.multidftbandpass(arraybuffer,this.nSec,this.freqStart,this.freqEnd,1);let dft2={};this.watch.forEach((tag,i)=>{dft2[tag]=results[1][i]});return{frequencies:results[0],dft:dft2}}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var coherence={sps:250,nSec:1,freqStart:0,freqEnd:125,tags:["0","1","2","3"],coherenceTags:[],__onconnected:function(node){node.tags.forEach((tag,i)=>{if(i!==node.tags.length-1){for(let j=i+1;j{dft2[tag]=results[1][i]});let coherence2={};this.coherenceTags.forEach((tag,i)=>{coherence2[tag]=results[2][i]});return{timestamp:ts,frequencies:results[0],dft:dft2,coherence:coherence2}}};var gpualgorithms={dft,coherence};})(); -/*! Bundled license information: - -gpujsutils/dist/index.esm.js: - (** - * gpu.js - * http://gpu.rocks/ - * - * GPU Accelerated JavaScript - * - * @version 2.11.0 - * @date Tue Jan 05 2021 15:55:59 GMT-0500 (Eastern Standard Time) - * - * @license MIT - * The MIT License - * - * Copyright (c) 2021 gpu.js Team - *) -*/ + }`;const name2="math-random-uniformly-distributed";const functionMatch=`Math.random()`;const functionReplace=`nrand(vTexCoord)`;const functionReturnType="Number";const onBeforeRun=kernel=>{kernel.setUniform1f("randomSeed1",Math.random());kernel.setUniform1f("randomSeed2",Math.random())};const plugin={name:name2,onBeforeRun,functionMatch,functionReplace,functionReturnType,source};module3.exports=plugin},{}],113:[function(require2,module3,exports3){class Texture{constructor(settings){const{texture,size,dimensions,output,context,type="NumberTexture",kernel,internalFormat,textureFormat}=settings;if(!output)throw new Error('settings property "output" required.');if(!context)throw new Error('settings property "context" required.');if(!texture)throw new Error('settings property "texture" required.');if(!kernel)throw new Error('settings property "kernel" required.');this.texture=texture;if(texture._refs){texture._refs++}else{texture._refs=1}this.size=size;this.dimensions=dimensions;this.output=output;this.context=context;this.kernel=kernel;this.type=type;this._deleted=false;this.internalFormat=internalFormat;this.textureFormat=textureFormat}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}module3.exports={Texture}},{}],114:[function(require2,module3,exports3){const acorn=require2("acorn");const{Input}=require2("./input");const{Texture}=require2("./texture");const FUNCTION_NAME=/function ([^(]*)/;const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const ARGUMENT_NAMES=/([^\s,]+)/g;const utils={systemEndianness(){return _systemEndianness},getSystemEndianness(){const b=new ArrayBuffer(4);const a=new Uint32Array(b);const c=new Uint8Array(b);a[0]=3735928559;if(c[0]===239)return"LE";if(c[0]===222)return"BE";throw new Error("unknown endianness")},isFunction(funcObj){return typeof funcObj==="function"},isFunctionString(fn){if(typeof fn==="string"){return fn.slice(0,"function".length).toLowerCase()==="function"}return false},getFunctionNameFromString(funcStr){const result=FUNCTION_NAME.exec(funcStr);if(!result||result.length===0)return null;return result[1].trim()},getFunctionBodyFromString(funcStr){return funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"))},getArgumentNamesFromString(fn){const fnStr=fn.replace(STRIP_COMMENTS,"");let result=fnStr.slice(fnStr.indexOf("(")+1,fnStr.indexOf(")")).match(ARGUMENT_NAMES);if(result===null){result=[]}return result},clone(obj){if(obj===null||typeof obj!=="object"||obj.hasOwnProperty("isActiveClone"))return obj;const temp=obj.constructor();for(let key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){obj.isActiveClone=null;temp[key]=utils.clone(obj[key]);delete obj.isActiveClone}}return temp},isArray(array){return!isNaN(array.length)},getVariableType(value2,strictIntegers){if(utils.isArray(value2)){if(value2.length>0&&value2[0].nodeName==="IMG"){return"HTMLImageArray"}return"Array"}switch(value2.constructor){case Boolean:return"Boolean";case Number:if(strictIntegers&&Number.isInteger(value2)){return"Integer"}return"Float";case Texture:return value2.type;case Input:return"Input"}switch(value2.nodeName){case"IMG":return"HTMLImage";case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}if(value2.hasOwnProperty("type")){return value2.type}return"Unknown"},getKernelTextureSize(settings,dimensions){let[w,h,d]=dimensions;let texelCount=(w||1)*(h||1)*(d||1);if(settings.optimizeFloatMemory&&settings.precision==="single"){w=texelCount=Math.ceil(texelCount/4)}if(h>1&&w*h===texelCount){return new Int32Array([w,h])}return utils.closestSquareDimensions(texelCount)},closestSquareDimensions(length){const sqrt=Math.sqrt(length);let high=Math.ceil(sqrt);let low=Math.floor(sqrt);while(high*low0){return lines.join(";\n")+";\n"}else{return"\n"}},warnDeprecated(type,oldName,newName){if(newName){console.warn(`You are using a deprecated ${type} "${oldName}". It has been replaced with "${newName}". Fixing, but please upgrade as it will soon be removed.`)}else{console.warn(`You are using a deprecated ${type} "${oldName}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)}},flipPixels:(pixels,width,height)=>{const halfHeight=height/2|0;const bytesPerRow=width*4;const temp=new Uint8ClampedArray(width*4);const result=pixels.slice(0);for(let y=0;y{return array.subarray(0,width)},erect2DPackedFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{return array.subarray(0,width)},erectMemoryOptimized2DFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{const xResults=new Float32Array(width);let i=0;for(let x2=0;x2{const yResults=new Array(height);let i=0;for(let y=0;y{const zResults=new Array(depth);let i=0;for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const yResults=new Array(height);const XResultsMax=width*4;for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(array);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const{findDependency,thisLookup,doNotDefine}=settings;let flattened=settings.flattened;if(!flattened){flattened=settings.flattened={}}const ast=acorn.parse(source);const functionDependencies=[];let indent=0;function flatten(ast2){if(Array.isArray(ast2)){const results=[];for(let i=0;ir!==null);if(declarations.length<1){return""}else{return`${ast2.kind} ${declarations.join(",")}`}case"VariableDeclarator":if(ast2.init.object&&ast2.init.object.type==="ThisExpression"){const lookup=thisLookup(ast2.init.property.name,true);if(lookup){return`${ast2.id.name} = ${flatten(ast2.init)}`}else{return null}}else{return`${ast2.id.name} = ${flatten(ast2.init)}`}case"CallExpression":{if(ast2.callee.property.name==="subarray"){return`${flatten(ast2.callee.object)}.${flatten(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}if(ast2.callee.object.name==="gl"||ast2.callee.object.name==="context"){return`${flatten(ast2.callee.object)}.${flatten(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}if(ast2.callee.object.type==="ThisExpression"){functionDependencies.push(findDependency("this",ast2.callee.property.name));return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}else if(ast2.callee.object.name){const foundSource=findDependency(ast2.callee.object.name,ast2.callee.property.name);if(foundSource===null){return`${ast2.callee.object.name}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}else{functionDependencies.push(foundSource);return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}}else if(ast2.callee.object.type==="MemberExpression"){return`${flatten(ast2.callee.object)}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}else{throw new Error("unknown ast.callee")}}case"ReturnStatement":return`return ${flatten(ast2.argument)}`;case"BinaryExpression":return`(${flatten(ast2.left)}${ast2.operator}${flatten(ast2.right)})`;case"UnaryExpression":if(ast2.prefix){return`${ast2.operator} ${flatten(ast2.argument)}`}else{return`${flatten(ast2.argument)} ${ast2.operator}`}case"ExpressionStatement":return`${flatten(ast2.expression)}`;case"SequenceExpression":return`(${flatten(ast2.expressions)})`;case"ArrowFunctionExpression":return`(${ast2.params.map(flatten).join(", ")}) => ${flatten(ast2.body)}`;case"Literal":return ast2.raw;case"Identifier":return ast2.name;case"MemberExpression":if(ast2.object.type==="ThisExpression"){return thisLookup(ast2.property.name)}if(ast2.computed){return`${flatten(ast2.object)}[${flatten(ast2.property)}]`}return flatten(ast2.object)+"."+flatten(ast2.property);case"ThisExpression":return"this";case"NewExpression":return`new ${flatten(ast2.callee)}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`;case"ForStatement":return`for (${flatten(ast2.init)};${flatten(ast2.test)};${flatten(ast2.update)}) ${flatten(ast2.body)}`;case"AssignmentExpression":return`${flatten(ast2.left)}${ast2.operator}${flatten(ast2.right)}`;case"UpdateExpression":return`${flatten(ast2.argument)}${ast2.operator}`;case"IfStatement":return`if (${flatten(ast2.test)}) ${flatten(ast2.consequent)}`;case"ThrowStatement":return`throw ${flatten(ast2.argument)}`;case"ObjectPattern":return ast2.properties.map(flatten).join(", ");case"ArrayPattern":return ast2.elements.map(flatten).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${flatten(ast2.test)}?${flatten(ast2.consequent)}:${flatten(ast2.alternate)}`;case"Property":if(ast2.kind==="init"){return flatten(ast2.key)}}throw new Error(`unhandled ast.type of ${ast2.type}`)}const result=flatten(ast);if(functionDependencies.length>0){const flattenedFunctionDependencies=[];for(let i=0;i{if(ast.type!=="VariableDeclaration")throw new Error('Ast is not of type "VariableDeclaration"');const normalizedDeclarations=[];for(let declarationIndex=0;declarationIndex{const rKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.r*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const gKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.g*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const bKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.b*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const aKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.a*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const result=[rKernel(image),gKernel(image),bKernel(image),aKernel(image)];result.rKernel=rKernel;result.gKernel=gKernel;result.bKernel=bKernel;result.aKernel=aKernel;result.gpu=gpu;return result},splitRGBAToCanvases:(gpu,rgba,width,height)=>{const visualKernelR=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(pixel.r/255,0,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelR(rgba);const visualKernelG=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,pixel.g/255,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelG(rgba);const visualKernelB=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,0,pixel.b/255,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelB(rgba);const visualKernelA=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(255,255,255,pixel.a/255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelA(rgba);return[visualKernelR.canvas,visualKernelG.canvas,visualKernelB.canvas,visualKernelA.canvas]},getMinifySafeName:fn=>{try{const ast=acorn.parse(`const value = ${fn.toString()}`);const{init}=ast.body[0].declarations[0];return init.body.name||init.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(name2){if(dollarSign.test(name2)){name2=name2.replace(dollarSign,"S_S")}if(doubleUnderscore.test(name2)){name2=name2.replace(doubleUnderscore,"U_U")}else if(singleUnderscore.test(name2)){name2=name2.replace(singleUnderscore,"u_u")}return name2}};const dollarSign=/\$/;const doubleUnderscore=/__/;const singleUnderscore=/_/;const _systemEndianness=utils.getSystemEndianness();module3.exports={utils}},{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107)})}});var import_gpu_browser_min=__toESM(require_gpu_browser_min());function add(a,b){return a+b}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function cadd(a_real,a_imag,b_real,b_imag){return[a_real+b_real,a_imag+b_imag]}function csub(a_real,a_imag,b_real,b_imag){return[a_real-b_real,a_imag-b_imag]}function cmul(a_real,a_imag,b_real,b_imag){return[a_real*b_real-a_imag*b_imag,a_real*b_imag+a_imag*b_real]}function cexp(a_real,a_imag){const er=Math.exp(a_real);return[er*Math.cos(a_imag),er*Math.sin(a_imag)]}function mag(a,b){return Math.sqrt(a*a+b*b)}function conj(imag){return 0-imag}function lof(n){const sqrt_n=Math.sqrt(n);var factor=3;while(factor<=sqrt_n){if(n%factor===0)return factor;factor+=2}}function mean(arr,len){var mean2=0;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signal[j]*Math.cos(sharedi);imag=imag-signal[j]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function FFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=imag-signals[j+(len-1)*n]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function iDFT(fft,len,freq){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+fft[j]*Math.cos(sharedi);imag=fft[j]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function iFFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=signals[j+(len-1)*n]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function correlogramsKern(arrays,len){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=mean(arrays[k],len);var arr2mean=mean(arrays[k+1],len);var arr1Est=est(arrays[k],arr1mean,len);var arr2Est2=est(arrays[k+1],arr2mean,len);var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function correlogramsPCKern(arrays,len,means,estimators){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=means[k];var arr2mean=means[k+1];var arr1Est=estimators[k];var arr2Est2=estimators[k+1];var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function dftKern(signal,len,scalar){var result=DFT(signal,len,this.thread.x);return mag(result[0],result[1])*scalar}function idftKern(amplitudes,len,scalar){var result=iDFT(amplitudes,len,this.thread.x);return mag(result[0],result[1])*scalar}function fftKern(signal,len,scalar,sampleRate){var result=FFT(signal,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function ifftKern(amplitudes,len,scalar,sampleRate){var result=iFFT(amplitudes,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function listdft2DKern(signals,scalar){var len=this.output.x;var result=DFT(signals[this.thread.y],len,this.thread.x);return mag(result[0],result[1])*scalar}function listdft1DKern(signals,len,scalar){var result=[0,0];if(this.thread.x<=len){result=DFT(signals,len,this.thread.x)}else{var n=Math.floor(this.thread.x/len);result=DFTlist(signals,len,this.thread.x-n*len,n)}return mag(result[0],result[1])*scalar}function listfft1DKern(signals,len,scalar,sps){var result=[0,0];if(this.thread.x<=len){result=FFT(signals,len,this.thread.x,sps)}else{var n=Math.floor(this.thread.x/len);result=FFTlist(signals,len,this.thread.x-n*len,n,sps)}return mag(result[0],result[1])*scalar}function dft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=DFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function fft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=FFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function idft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iDFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function ifft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iFFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function listdft1D_windowedKern(signals,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];if(this.thread.x=width){i++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+i+kernelRadius;const weights=kernel[kernelOffset];const pixel=img[this.thread.y+i][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}i++}this.color(r,g,b)}function multiImgConv2DKern(img,width,height,kernels,kernelLengths,nKernels){let r=0,g=0,b=0;for(var i=0;i=width){k++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+k+kernelRadius;const weights=kernels[i][kernelOffset];const pixel=img[this.thread.y+k][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}k++}}this.color(r,g,b)}function transpose2DKern(mat2){return mat2[this.thread.y][this.thread.x]}var createGpuKernels={correlogramsKern,correlogramsPCKern,dftKern,idftKern,fftKern,ifftKern,dft_windowedKern,idft_windowedKern,fft_windowedKern,ifft_windowedKern,listdft2DKern,listdft1DKern,listfft1DKern,listfft1D_windowedKern,listdft1D_windowedKern,listidft1D_windowedKern,listifft1D_windowedKern,bulkArrayMulKern,multiImgConv2DKern,ImgConv2DKern,transpose2DKern};var addGpuFunctions=[add,sub,mul,div,cadd,csub,cmul,cexp,mag,conj,lof,mean,est,mse,rms,xcor,softmax,DFT,DFTlist,iDFT,iDFTlist,FFT,iFFT,iFFTlist];function makeKrnl(gpu,f,opts={setDynamicOutput:true,setDynamicArguments:true,setPipeline:true,setImmutable:true,setGraphical:false}){const k=gpu.createKernel(f);if(opts.setDynamicOutput)k.setDynamicOutput(true);if(opts.output)k.setOutput(opts.output);if(opts.setDynamicArguments)k.setDynamicArguments(true);if(opts.setPipeline)k.setPipeline(true);if(opts.setImmutable)k.setImmutable(true);if(opts.setGraphical)k.setGraphical(true);return k}function makeCanvasKrnl(gpu,f,opts={output:[300,300],setDynamicArguments:true,setDynamicOutput:true,setPipeline:false,setImmutable:true,setGraphical:true},divId){const k=makeKrnl(gpu,f,opts);const canvas=k.canvas;if(typeof divId==="string")document.getElementById(toAppend).appendChild(canvas);else if(divId)toAppend.appendChild(canvas);else document.body.appendChild(canvas);return k}var gpuUtils=class{constructor(gpu=new GPU){this.gpu=gpu;this.kernels=new Map;this.kernel;this.PI=3.141592653589793;this.SQRT1_2=.7071067811865476;this.addFunctions();this.imgkernels={edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],sobelLeft:[1,0,-1,2,0,-2,1,0,-1],sobelRight:[-1,0,1,-2,0,2,-1,0,1],sobelTop:[1,2,1,0,0,0,-1,-2,-1],sobelBottom:[-1,2,1,0,0,0,1,2,1],identity:[0,0,0,0,1,0,0,0,0],gaussian3x3:[1,2,1,2,4,2,1,2,1],guassian7x7:[0,0,0,5,0,0,0,0,5,18,32,18,5,0,0,18,64,100,64,18,0,5,32,100,100,100,32,5,0,18,64,100,64,18,0,0,5,18,32,18,5,0,0,0,0,5,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0]}}addFunction(func=function f(){}){this.gpu.addFunction(func)}addKernel(name2="",krnl=function foo(){},opts){let found=this.kernels.get(name2);if(!found){this.kernels.set(name2,makeKrnl(this.gpu,krnl,opts));return true}else{console.error("Kernel already exists");return false}}addCanvasKernel(name2,f,opts,divId){let found=this.kernels.get(name2);if(!found){let krnl=makeCanvasKrnl(this.gpu,f,opts,divId);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}combineKernels(name2,fs=[],ckrnl=function foo(){}){let found=this.kernels.get(name2);if(!found){fs.forEach((f,i)=>{if(typeof f==="string"){let found2=this.kernels.get(f);if(found2)fs[i]=found2;else return false}else if(typeof f==="function"){if(this.kernels.get(f.name)){}else{this.addKernel(f.name,f)}}});let krnl=this.gpu.combineKernels(...fs,ckrnl);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}callKernel(name2="",args=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}result=krnl(...args);return result}callCanvasKernel(name2="",args=[],outputDims=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}else{if(outputDims.length===2)krnl.setOutput(outputDims);result=krnl(...args);return result}}hasKernel(name2=""){let found=this.kernels.get(name2);if(!found){return false}else return true}addFunctions(){addGpuFunctions.forEach(f=>this.gpu.addFunction(f));this.correlograms=makeKrnl(this.gpu,createGpuKernels.correlogramsKern);this.correlogramsPC=makeKrnl(this.gpu,createGpuKernels.correlogramsPCKern);this.dft=makeKrnl(this.gpu,createGpuKernels.dftKern);this.idft=makeKrnl(this.gpu,createGpuKernels.idftKern);this.dft_windowed=makeKrnl(this.gpu,createGpuKernels.dft_windowedKern);this.idft_windowed=makeKrnl(this.gpu,createGpuKernels.idft_windowedKern);this.fft=makeKrnl(this.gpu,createGpuKernels.fftKern);this.ifft=makeKrnl(this.gpu,createGpuKernels.ifftKern);this.fft_windowed=makeKrnl(this.gpu,createGpuKernels.fft_windowedKern);this.ifft_windowed=makeKrnl(this.gpu,createGpuKernels.ifft_windowedKern);this.listdft2D=makeKrnl(this.gpu,createGpuKernels.listdft2DKern);this.listdft1D=makeKrnl(this.gpu,createGpuKernels.listdft1DKern);this.listdft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listdft1D_windowedKern);this.listfft1D=makeKrnl(this.gpu,createGpuKernels.listfft1DKern);this.listfft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listfft1D_windowedKern);this.listidft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listidft1D_windowedKern);this.listifft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listifft1D_windowedKern);this.bulkArrayMul=makeKrnl(this.gpu,createGpuKernels.bulkArrayMulKern);let kernels=[{name:"correlograms",krnl:this.correlograms},{name:"correlogramsPC",krnl:this.correlogramsPC},{name:"dft",krnl:this.dft},{name:"idft",krnl:this.idft},{name:"dft_windowed",krnl:this.idft_windowed},{name:"fft",krnl:this.fft},{name:"ifft",krnl:this.ifft},{name:"fft_windowed",krnl:this.fft_windowed},{name:"ifft_windowed",krnl:this.ifft_windowed},{name:"listdft2D",krnl:this.listdft2D},{name:"listdft1D",krnl:this.listdft1D},{name:"listdft1D_windowed",krnl:this.listdft1D_windowed},{name:"listfft1D",krnl:this.listfft1D},{name:"listfft1D_windowed",krnl:this.listfft1D_windowed},{name:"listidft1D_windowed",krnl:this.listidft1D_windowed},{name:"listifft1D_windowed",krnl:this.listifft1D_windowed},{name:"bulkArrayMul",krnl:this.bulkArrayMul}];kernels.forEach(k=>{this.kernels.set(k.name,k)});const signalBandpass=(signal,sampleRate,freqStart,freqEnd,scalar)=>{var dft2=this.fft_windowed(signal,sampleRate,freqStart,freqEnd,scalar,0);var filtered_signal=this.ifft_windowed(dft2,sampleRate,freqStart,freqEnd,scalar);return filtered_signal};const signalBandpassMulti=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var dfts=this.listdft1D_windowed(signals,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var filtered_signals=this.listifft1D_windowed(dfts,sampleRate,freqStart,freqEnd,scalar);return filtered_signals};this.gpuCoherence=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var xcors=this.correlograms(signals);var dfts=this.listfft1D_windowed(xcors,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var products=this.bulkArrayMul(dfts,sampleRate,5,1);return products}}gpuXCors(arrays,precompute=false,texOut=false){var outputTex;if(precompute===true){var means=[];var ests=[];arrays.forEach((arr,i2)=>{means.push(arr.reduce((prev,curr)=>curr+=prev)/arr.length);ests.push(Math.sqrt(means[i2].reduce((sum,item)=>sum+=Math.pow(item-mean1,2))))});var meansbuf=[];var estsbuf=[];var buffer=[];for(var i=0;i{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D.setOutput([signalBufferProcessed.length]);this.listdft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D(signalBufferProcessed,nSamplesPerChannel,scalar);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D_windowed.setOutput([signalBufferProcessed.length]);this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}gpuFFT(signalBuffer,nSeconds,scalar=1,sampleRate,texOut=false){var nSamples=signalBuffer.length;var sampleRate=nSamples/nSeconds;this.fft.setOutput([signalBuffer.length]);this.fft.setLoopMaxIterations(nSamples);var outputTex=this.fft(signalBuffer,nSamples,scalar,sampleRate);var output=null;if(texOut===false){var freqDist=this.makeFrequencyDistribution(nSamples,sampleRate);var signalBufferProcessed=outputTex.toArray();outputTex.delete();return[freqDist,this.orderMagnitudes(signalBufferProcessed)]}else{var tex=outputTex;outputTex.delete();return tex}}MultiChannelFFT(signalBuffer,nSeconds,scalar=1,texOut=false){var signalBufferProcessed=[];signalBuffer.forEach(row=>{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D.setOutput([signalBufferProcessed.length]);this.listfft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D(signalBufferProcessed,nSamplesPerChannel,scalar,sampleRate);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D_windowed.setOutput([signalBufferProcessed.length]);this.listfft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}orderMagnitudes(unorderedMags){return[...unorderedMags.slice(Math.ceil(unorderedMags.length*.5),unorderedMags.length),...unorderedMags.slice(0,Math.ceil(unorderedMags.length*.5))]}makeFrequencyDistribution(FFTlength,sampleRate){var N=FFTlength;var df=sampleRate/N;var freqDist=[];for(var i=-N/2;i1){magList.forEach((row,k)=>{summedMags.push([]);var _max=1/Math.max(...row);for(var i2=0;i2key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value:value2}):obj[key]=value2;var __publicField=(obj,key,value2)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value2);return value2};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean2=void 0){let avg=mean2;if(!mean2)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean2)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean2=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean2=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean2*mean2-det);let eig1=mean2+sqrt;let eig2=mean2-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean12=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean12=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(delaybuf[delay+i]-mean12));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean2=this.mean(smoothed);let std=this.std(smoothed,mean2);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean2)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean2)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}}}return value2}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx++}}}}}function checkValues(key,value2){let val;if(value2!=null){if(typeof value2==="object"){let c=value2.constructor.name;if(key&&c==="Object"){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}if(c==="Array"){if(value2.length>20){val=value2.slice(value2.length-20)}else val=value2}else if(c.includes("Set")){val=Array.from(value2)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value2){if(value2[prop]==null){obj[prop]=value2[prop]}else if(Array.isArray(value2[prop])){if(value2[prop].length>20)obj[prop]=value2[prop].slice(value2[prop].length-20);else obj[prop]=value2[prop]}else if(value2[prop].constructor.name==="Object"){obj[prop]={};for(const p in value2[prop]){if(Array.isArray(value2[prop][p])){if(value2[prop][p].length>20)obj[prop][p]=value2[prop][p].slice(value2[prop][p].length-20);else obj[prop][p]=value2[prop][p]}else{if(value2[prop][p]!=null){let con=value2[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value2[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value2[prop][p]}}else{obj[prop][p]=value2[prop][p]}}}}else{let con=value2[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value2[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value2[prop]}}}val=obj}else{val=value2}}else{val=value2}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var GPUService=class extends Service{constructor(options){super(options);this.gpu=new gpuUtils;this.addFunc=fn=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addFunction(fn)};this.addKernel=(name2,fn,options)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addKernel(name2,fn,options)};this.callKernel=(name2,...args)=>{this.gpu.callKernel(name2,...args)};this.dft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.gpuDFT(signalBuffer,nSeconds,scalar)};this.multidft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT(signalBuffer,nSeconds,scalar)};this.multidftbandpass=(buffered,nSeconds,freqStart,freqEnd,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT_Bandpass(buffered,nSeconds,freqStart,freqEnd,scalar)};this.coherence=(buffered,nSeconds,freqStart,freqEnd)=>{const correlograms=Math2.correlograms(buffered);const buffer=[...buffered,...correlograms];var dfts;var scalar=1;dfts=this.gpu.MultiChannelDFT_Bandpass(buffer,nSeconds,freqStart,freqEnd,scalar);const cordfts=dfts[1].splice(buffered.length,buffer.length-buffered.length);const coherenceResults=[];const nChannels=buffered.length;var k=0;var l=0;cordfts.forEach((row,i)=>{if(l+k===nChannels){var temp=cordfts.splice(i,1);k++;cordfts.splice(k,0,...temp);l=0}l++});var autoFFTproducts=[];k=0;l=1;cordfts.forEach((dft2,i)=>{var newdft=new Array(dft2.length).fill(0);if(i{newdft[j]=amp});autoFFTproducts.push(newdft)}else{dft2.forEach((amp,j)=>{let denom=autoFFTproducts[k][j]*autoFFTproducts[k+l][j];if(denom!==0)newdft[j]=amp*amp/denom;else newdft[j]=0;if(newdft[j]>1){newdft[j]=1}});l++;if(l+k===nChannels){k++;l=1}coherenceResults.push(newdft)}});return[dfts[0],dfts[1],coherenceResults]};this.setTree(this)}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var dft={structs:{sps:250,nSec:1,freqStart:0,freqEnd:125,watch:["0","1","2","3"],blocking:false},oncreate:ctx=>{},ondata:(ctx,arraybuffer)=>{let results=globalThis.gpu.multidftbandpass(arraybuffer,ctx.nSec,ctx.freqStart,ctx.freqEnd,1);let dft2={};ctx.watch.forEach((tag,i)=>{dft2[tag]=results[1][i]});return{frequencies:results[0],dft:dft2}}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var coherence={structs:{sps:250,nSec:1,freqStart:0,freqEnd:125,tags:["0","1","2","3"],coherenceTags:[]},oncreate:ctx=>{ctx.tags.forEach((tag,i)=>{if(i!==ctx.tags.length-1){for(let j=i+1;j{let ts=Date.now();let results=globalThis.gpu.coherence(arraybuffer,ctx.nSec,ctx.freqStart,ctx.freqEnd);let dft2={};ctx.tags.forEach((tag,i)=>{dft2[tag]=results[1][i]});let coherence2={};ctx.coherenceTags.forEach((tag,i)=>{coherence2[tag]=results[2][i]});return{timestamp:ts,frequencies:results[0],dft:dft2,coherence:coherence2}}};var gpualgorithms={dft,coherence};export{GPUService,gpualgorithms}; +/** + * gpu.js + * http://gpu.rocks/ + * + * GPU Accelerated JavaScript + * + * @version 2.11.0 + * @date Tue Jan 05 2021 15:55:59 GMT-0500 (Eastern Standard Time) + * + * @license MIT + * The MIT License + * + * Copyright (c) 2021 gpu.js Team + */ diff --git a/src/extras/dist/index.gpu.services.esm.js b/extras/dist/index.gpu.services.js similarity index 58% rename from src/extras/dist/index.gpu.services.esm.js rename to extras/dist/index.gpu.services.js index cdca3039..df39a906 100644 --- a/src/extras/dist/index.gpu.services.esm.js +++ b/extras/dist/index.gpu.services.js @@ -1,4 +1,4 @@ -var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var EventHandler=class{data={};triggers={};ctr=0;constructor(data){if(typeof data==="object")this.data=data}setState=updateObj=>{Object.assign(this.data,updateObj);let props=Object.getOwnPropertyNames(updateObj);for(const prop of props){this.triggerEvent(prop,this.data[prop])}if(this.triggers[statesubKey]){let run=fn=>{fn(updateObj)};const l=this.triggers[statesubKey].length;for(let i=l-1;i>=0;i--){run(this.triggers[statesubKey][i].onchange)}}return this.data};setValue=(key,value2)=>{this.data[key]=value2;this.triggerEvent(key,value2)};triggerEvent=(key,value2)=>{if(this.triggers[key]){let fn=obj=>{obj.onchange(value2)};const l=this.triggers[key].length;for(let i=l-1;i>=0;i--){fn(this.triggers[key][i])}}};subscribeState=onchange=>{return this.subscribeEvent(statesubKey,onchange)};unsubscribeState=sub2=>{return this.unsubscribeEvent(statesubKey,sub2)};subscribeEvent=(key,onchange,refObject,refKey)=>{if(key){if(refObject&&refKey&&!this.triggers[key]){Object.defineProperty(this.data,key,{get:()=>{return refObject[refKey]},set:value2=>{refObject[refKey]=value2},enumerable:true,configurable:true})}if(!this.triggers[key]){this.triggers[key]=[]}let l=this.ctr;this.ctr++;this.triggers[key].push({sub:l,onchange});return l}else return void 0};unsubscribeEvent=(key,sub2)=>{let triggers=this.triggers[key];if(triggers){if(sub2===void 0){delete this.triggers[key];delete this.data[key]}else{let idx=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){idx=i;return true}});if(obj)triggers.splice(idx,1);if(Object.keys(triggers).length===0){delete this.triggers[key];delete this.data[key]}if(this.onRemoved)this.onRemoved(obj);return true}}};subscribeEventOnce=(key,onchange)=>{let sub2;let changed=value2=>{onchange(value2);this.unsubscribeEvent(key,sub2)};sub2=this.subscribeEvent(key,changed);return sub2};getEvent=(key,sub2)=>{if(typeof sub2!=="number")return this.triggers[key];for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub2)return this.triggers[key][s]}};getSnapshot=()=>{const snapshot={};for(const key in this.data){snapshot[key]=this.data[key]}};onRemoved};var statesubKey="*s";var state=new EventHandler;var Callable=class extends Function{__bound;__call;constructor(){super("return this.__bound.__call.apply(this.__bound, arguments)");this.__bound=this.bind(this);return this.__bound}};var GraphNode=class _GraphNode{__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.floor(Math.random()*1e15)}`,state};__children;__parent;__operator;__listeners;__props;__args;constructor(properties,parent,graph){this.__setProperties(properties,parent,graph);if(typeof properties==="function"||properties?.__callable){const callableInstance=new Callable;callableInstance.__call=(...args)=>this.__operator(...args);const proxy=new Proxy(callableInstance,{get:(target,prop,receiver)=>{if(Reflect.has(this,prop)){return Reflect.get(this,prop,receiver)}return Reflect.get(target,prop,receiver)},set:(target,prop,value2,receiver)=>{if(Reflect.has(this,prop)){return Reflect.set(this,prop,value2,receiver)}return Reflect.set(target,prop,value2,receiver)}});Object.setPrototypeOf(proxy,this);return proxy}}get __graph(){return this.__node?.graph}set __graph(graph){this.__node.graph=graph}__setProperties=(properties,parent,graph)=>{let enforceProperties=()=>{let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!("__node"in properties))properties.__node={};if(!properties.__node.initial)properties.__node.initial=orig};enforceProperties();if(typeof properties==="object"){let assignState=()=>{if(properties.__node?.state)this.__node.state=properties.__node.state;else if(graph){properties.__node.state=graph.__node.state}};let setProps=()=>{if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}};let setTag=()=>{if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}};let setNode=()=>{if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties instanceof Graph)properties.__node.source=properties};let setParent=()=>{if(!properties.__parent&&parent)properties.__parent=parent;if(parent?.__node&&!(parent instanceof Graph||properties instanceof Graph))properties.__node.tag=parent.__node.tag+"."+properties.__node.tag;if(parent instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent.__node.loaders?parent.__node.loaders:{},properties.__node.loaders);if(parent.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}};let setOp=()=>{if(typeof properties.default==="function"&&!properties.__operator){properties.__operator=properties.default}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator);if(properties.default)properties.default=properties.__operator}};let assignProps=()=>{properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties).filter(v=>{if(!objProps[v])return true});for(const key of keys){if(key in properties&&key!=="name")this[key]=properties[key]}};let bindCallbacks=()=>{if(this.__onconnected){if(typeof this.__onconnected==="function"){this.__onconnected=this.__onconnected.bind(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected=this.__onconnected.map(f=>{return f.bind(this)})}if(typeof this.__ondisconnected==="function"){this.__ondisconnected=this.__ondisconnected.bind(this)}else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected=this.__ondisconnected.map(f=>{return f.bind(this)})}}};assignState();setTag();setProps();setNode();setParent();assignProps();bindCallbacks();setOp()}};__subscribe=(callback,key,subInput,target,tkey,args,callbackStr)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>target2?target2:callback2,triggerCallback=callback)=>{let wrappedArgs;if(args){let wrapped=wrapArgs(triggerCallback,args,this.__node.graph);triggerCallback=wrapped.__callback;wrappedArgs=wrapped.__args}let sub2=this.__node.state.subscribeEvent(k,triggerCallback,this,key);let trigger=this.__node.state.getEvent(k,sub2);if(!this.__listeners)this.__listeners={};this.__listeners[k]=this.__node.state.triggers[k];if(!trigger)return sub2;trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback,target);if(tkey)trigger.tkey=tkey;if(subInput)trigger.subInput=subInput;if(args){trigger.arguments=wrappedArgs;trigger.__args=args}if(callbackStr)trigger.__callback=callbackStr;trigger.node=this;trigger.graph=this.__node.graph;return sub2};const getCallbackFromGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){target=callback2.substring(0,callback2.lastIndexOf("."));let n=this.__node.graph.get(callback2.substring(0,target));tkey=callback2.lastIndexOf(".")+1;if(n&&typeof n[key]==="function")callback2=(...args2)=>{return n[tkey](...args2)}}else if(fn.__operator){callback2=fn.__operator;tkey="__operator"}return callback2};if(key){if(!this.__node.localState||!this.__node.localState[key]){this.__addLocalState(this,key)}if(typeof callback==="string"){callbackStr=this.__node.tag+"."+callback;tkey=callback;if(target){if(this.__node.graph?.get(target)){let n=this.__node.graph?.get(target);if(typeof n[callback]==="function"){let fn=n[callback];callback=(...inp)=>{fn(...inp)}}else{let k2=callback;let setter=inp=>{n[k2]=inp};callback=setter}}}else if(typeof this[callback]==="function"){let fn=this[callback];callback=(...inp)=>{fn(...inp)}}else if(this.__node.graph?.get(callback))callback=getCallbackFromGraph(callback);if(typeof callback!=="function")return void 0}let sub2;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)});return sub2}else{if(typeof callback==="string"){callbackStr=callback;if(!target)target=callback;if(this.__node.graph.get(callback))callback=this.__node.graph.get(callback);tkey="__operator";if(typeof callback!=="object")return void 0}let sub2;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function"&&!callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2,callback);else if(callback?.__node){sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,(...inp)=>{if(callback.__operator)callback.__operator(...inp)})}return sub2}};__unsubscribe=(sub2,key,unsubInput)=>{if(key){return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub2)}else return this.__node.state.unsubscribeEvent(unsubInput?this.__node.unique+"input":this.__node.unique,sub2)};__setOperator=fn=>{fn=fn.bind(this);if(this.__args&&this.__node.graph){fn=wrapArgs(fn,this.__args,this.__node.graph).__callback}let inpstr=`${this.__node.unique}input`;this.__operator=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(this.__parent instanceof _GraphNode&&!this.__subscribedToParent){if(this.__parent.__operator){let sub2=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub2);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};__addLocalState=(props,key)=>{if(!props)return;if(!this.__node.localState){this.__node.localState={}}const localState=this.__node.localState;const initState=(props2,k)=>{let str=this.__node.unique+"."+k;let inpstr=`${str}input`;let get,set;let obj,descriptor;if(typeof props2[k]==="function"&&k!=="__operator"){if(this.__props?.[k]){obj=this.__props}else{obj=localState}get=()=>{return obj[k]};set=fn=>{if(!this.__props?.[k])fn=fn.bind(this);obj[k]=(...args)=>{if(this.__node.state.triggers[inpstr])this.__node.state.setValue(inpstr,args);let result=fn(...args);if(this.__node.state.triggers[str]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.triggerEvent(str,res)}).catch(console.error)}else this.__node.state.triggerEvent(str,result)}return result}};localState[k]=props2[k].bind(this);descriptor={get,set,enumerable:true,configurable:true}}else if(k!=="__graph"){let get2,set2;let obj2;if(this.__props?.[k]){obj2=this.__props}else{obj2=localState}get2=()=>{return obj2[k]};set2=v=>{obj2[k]=v;if(this.__node.state.triggers[str])this.__node.state.triggerEvent(str,v)};localState[k]=props2[k];descriptor={get:get2,set:set2,enumerable:true,configurable:true}}Object.defineProperty(props2,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}};if(key)initState(props,key);else{for(let k in props){initState(props,k)}}};__proxyObject=obj=>{const allProps=getAllProperties(obj);for(const k of allProps){const descriptor={get:()=>{return obj[k]},set:value2=>{obj[k]=value2},enumerable:true,configurable:true};Object.defineProperty(this,k,descriptor);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,descriptor)}}}};__addOnconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__onconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){callback=callback.bind(this);if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){let fn=o=>{o(this)};this.__onconnected.forEach(fn)}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){let fn=o=>{o(this)};this.__ondisconnected.forEach(fn)}}};var Graph=class _Graph{__node={tag:`graph${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,nodes:new Map,state,roots:{}};constructor(options){this.init(options)}init=options=>{if(options){let cpy=Object.assign({},options);delete cpy.roots;recursivelyAssign(this.__node,cpy);if(options.roots)this.load(options.roots)}};load=(roots,overwrite=false)=>{function recursivelyAssignChildren(target,obj,inChildren=true,top=true){if(top){if(!target)target={};for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=obj[key];if(obj[key]?.__children){recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}recursivelyAssignChildren(target,obj,true,false)}else{if(obj?.__children&&!inChildren){if(obj.__children?.constructor.name==="Object"){if(target.__children?.constructor.name==="Object")target.__children=recursivelyAssignChildren(target.__children,obj.__children,true,false);else target.__children=recursivelyAssignChildren({},obj.__children,true,false)}else{target.__children=obj.__children}}else if(inChildren){for(const key in obj){if(!key.startsWith("__")&&obj[key]&&typeof obj[key]==="object"){target[key]=Object.assign({},obj[key]);if(obj[key]?.__children){target[key].__children=recursivelyAssignChildren({},obj[key].__children,false,false)}}else if(typeof obj[key]==="function")target[key]=obj[key]}}}return target}this.__node.roots=recursivelyAssignChildren(this.__node.roots?this.__node.roots:{},roots);let cpy=Object.assign({},roots);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,roots,overwrite);if(roots.__node){if(!roots.__node.tag)roots.__node._tag=`roots${Math.floor(Math.random()*1e15)}`;else if(!this.get(roots.__node.tag)){let node=new GraphNode(roots,this,this);this.set(node.__node.tag,node);this.runLoaders(node,this,roots,roots.__node.tag);if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(roots.__listeners){this.setListeners(roots.__listeners)}this.setListeners(listeners);return cpy};setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};runLoaders=(node,parent,properties,key)=>{for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders[l]==="function")this.__node.loaders[l](node,parent,this,this.__node.roots,properties,key)}};add=(properties,parent,overwrite=true)=>{let listeners={};if(typeof parent==="string")parent=this.get(parent);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent,this);instanced=true}else properties=new properties}else properties={__operator:properties,__callable:true}}else if(typeof properties==="string"){properties=this.__node.roots[properties]}if(!properties)return;if(!instanced){let keys=Object.getOwnPropertyNames(properties);let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(properties));keys.push(...nonArrowFunctions);keys=keys.filter(v=>!objProps.includes(v));let cpy={};for(const key of keys){cpy[key]=properties[key]}properties=cpy}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&this.get(properties.__node.tag)){if(overwrite)this.remove(properties.__node.tag,true);else return}else if(properties.__node.tag&&this.get(properties.__node.tag))return this.get(properties.__node.tag);let node;let root=recursivelyAssign({},properties,2);if(instanced)node=properties;else node=new GraphNode(properties,parent,this);this.set(node.__node.tag,node);this.runLoaders(node,parent,properties,node.__node.tag);this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key in node.__listeners){let listener=node.__listeners[key];if(node[key]){delete listeners[node.__node.tag][key];listeners[node.__node.tag][node.__node.tag+"."+key]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][key]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][key]=parent.__node.tag}}}}this.setListeners(listeners);node.__callConnected();return node};recursiveSet=(originCpy,parent,listeners={},origin,overwrite=false)=>{let keys=Object.getOwnPropertyNames(origin).filter(v=>!objProps.includes(v));let nonArrowFunctions=Object.getOwnPropertyNames(Object.getPrototypeOf(origin)).filter(v=>!objProps.includes(v));keys.push(...nonArrowFunctions);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent,this);instanced=true}}else p={__operator:p,__callable:true}}else if(typeof p==="string"){if(this.__node.nodes.get(p))p=this.__node.nodes.get(p);else p=this.__node.roots[p]}else if(typeof p==="boolean"){if(this.__node.nodes.get(key))p=this.__node.nodes.get(key);else p=this.__node.roots[key]}if(p&&typeof p==="object"){if(!instanced&&!(p instanceof GraphNode)){let ks=Object.getOwnPropertyNames(p).filter(v=>!objProps.includes(v));let nonArrowFunctions2=Object.getOwnPropertyNames(Object.getPrototypeOf(p)).filter(v=>!objProps.includes(v));nonArrowFunctions2.splice(nonArrowFunctions2.indexOf("constructor"),1);ks.push(...nonArrowFunctions2);let cpy={};for(const key2 of ks){cpy[key2]=p[key2]}p=cpy}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;if(!p.__node.initial)p.__node.initial=originCpy[key];if(overwrite&&this.get(p.__node.tag)){this.remove(p.__node.tag,true)}else if(this.get(p.__node.tag)&&!(!(parent instanceof _Graph)&&parent?.__node)||parent?.__node&&this.get(parent.__node.tag+"."+p.__node.tag))continue;let node;let newnode=false;let root=recursivelyAssign({},p,2);if(instanced||p instanceof GraphNode){node=p}else{node=new GraphNode(p,parent,this);newnode=true}if(!newnode&&p instanceof GraphNode&&!instanced&&parent instanceof GraphNode){let sub2=this.subscribe(parent.__node.tag,node.__node.tag);let ondelete=node2=>{this.unsubscribe(parent.__node.tag,sub2)};node.__addOndisconnected(ondelete)}else if(node){this.set(node.__node.tag,node);this.runLoaders(node,parent,originCpy[key],key);originCpy[key]=node;this.__node.roots[node.__node.tag]=root;if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}if(node.__listeners){listeners[node.__node.tag]=Object.assign({},node.__listeners);for(const key2 in node.__listeners){let listener=node.__listeners[key2];let k=key2;if(node[key2]){delete listeners[node.__node.tag][key2];k=node.__node.tag+"."+key2;listeners[node.__node.tag][k]=listener}if(typeof listener==="string"){if(node.__children?.[listener]){listeners[node.__node.tag][k]=node.__node.tag+"."+listener}else if(parent instanceof GraphNode&&(parent.__node.tag===listener||parent.__node.tag.includes(".")&&parent.__node.tag.split(".").pop()===listener)){listeners[node.__node.tag][k]=parent.__node.tag}}}}node.__callConnected()}}}return listeners};remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.roots[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.roots[t[key].__node.tag];this.delete(key);delete this.__node.roots[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}if(node?.__node.graph)node.__node.graph=void 0;return node};run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub2;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(node.__operator&&(listeners[key][k][kk].__callback===true||typeof listeners[key][k][kk].__callback==="undefined"))listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(nn){let prop=k.substring(k.lastIndexOf(".")+1);sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,prop,listeners[key][k][kk].subInput,key)}}else{sub2=this.subscribe(nn,listeners[key][k][kk].__callback,listeners[key][k][kk].__args,void 0,listeners[key][k][kk].subInput,key)}}}if("__callback"in listeners[key][k]){if(node){if(listeners[key][k].__callback===true||typeof listeners[key][k].__callback==="undefined")listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node)}if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,k.substring(k.lastIndexOf(".")+1),listeners[key][k].subInput,key)}}else{sub2=this.subscribe(n,listeners[key][k].__callback,listeners[key][k].__args,void 0,listeners[key][k].subInput,key)}}}}}};clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key]?.sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(typeof node.__listeners[key]==="object"&&!node.__listeners[key]?.__callback){for(const k in node.__listeners[key]){if(typeof node.__listeners[key][k]?.sub==="number"){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}else{if(typeof!node.__listeners[key]?.__callback==="number"){for(const k in node.__listeners[key]){if(node.__listeners[key][k]?.sub){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].subInput);node.__listeners[key][k].sub=void 0}}}else if(typeof node.__listeners[key]?.sub==="number"){this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].subInput);node.__listeners[key].sub=void 0}}}}};get=tag=>{return this.__node.nodes.get(tag)};getByUnique=unique=>{return Array.from(this.__node.nodes.values()).find(node=>{if(node.__node.unique===unique)return true})};set=(tag,node)=>{return this.__node.nodes.set(tag,node)};delete=tag=>{return this.__node.nodes.delete(tag)};list=()=>{return Array.from(this.__node.nodes.keys())};getListener=(nodeTag,key,sub2)=>{let node=this.get(nodeTag);if(node){let k=node.__node.unique;if(key){k+="."+key}return this.__node.state.getEvent(k,sub2)}};getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.roots[node.__node.tag]);else{cpy=Object.assign({},node);for(const key in cpy){if(key.includes("__"))delete cpy[key]}}}};subscribe=(nodeEvent,onEvent,args,key,subInput,target,tkey)=>{let nd=nodeEvent;if(typeof nodeEvent==="string"){nd=this.get(nodeEvent);if(!nd&&nodeEvent.includes(".")){nd=this.get(nodeEvent.substring(0,nodeEvent.lastIndexOf(".")));key=nodeEvent.substring(nodeEvent.lastIndexOf(".")+1)}}if(target instanceof GraphNode)target=target.__node.tag;let callbackStr;if(typeof onEvent==="string"){callbackStr=onEvent;let setOnEventFromString=onEvent2=>{if(this.get(onEvent2)?.__operator){let node=this.get(onEvent2);target=onEvent2;onEvent2=function(...inp){return node.__operator(...inp)}}else if(onEvent2.includes(".")){target=onEvent2.substring(0,onEvent2.lastIndexOf("."));let n=this.get(target);let k=onEvent2.substring(onEvent2.lastIndexOf(".")+1);tkey=k;if(typeof n[k]==="function"){if(n[k]instanceof GraphNode)onEvent2=n[k];else onEvent2=function(...inp){return n[k](...inp)}}else{onEvent2=function(inp){n[k]=inp;return n[k]}}}return onEvent2};if(target){let node=this.get(target);if(typeof node?.[onEvent]==="function"){tkey=onEvent;onEvent=function(...inp){return node[key](...inp)}}else if(node?.[key]){tkey=key;if(node[key]instanceof GraphNode)onEvent=node[key];else onEvent=function(inp){node[key]=inp;return node[key]}}else{onEvent=setOnEventFromString(onEvent)}}else{onEvent=setOnEventFromString(onEvent)}}let sub2;if(nd instanceof GraphNode){const doSub=()=>{sub2=nd.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)nd.__unsubscribe(sub2,key,subInput);sub2=void 0};nd.__addOndisconnected(()=>{ondelete();nd.__addOnconnected(()=>{if(sub2===void 0&&nd.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))onEvent=this.get(onEvent);if(onEvent instanceof GraphNode){onEvent.__addOndisconnected(()=>{ondelete()})}};doSub()}else if(typeof nodeEvent==="string"){let node=this.get(nodeEvent);if(node){if(onEvent instanceof GraphNode&&onEvent.__operator){const doSub=()=>{sub2=node.__subscribe(onEvent.__operator,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput)};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});onEvent.__addOndisconnected(ondelete)};doSub()}else if(typeof onEvent==="function"||typeof onEvent==="string"){const doSub=()=>{sub2=node.__subscribe(onEvent,key,subInput,target,tkey,args,callbackStr);let ondelete=()=>{if(sub2!==void 0)node.__unsubscribe(sub2,key,subInput);sub2=void 0};node.__addOndisconnected(()=>{ondelete();node.__addOnconnected(()=>{if(sub2===void 0&&node.__node.graph.__node.tag===this.__node.tag)doSub()})});if(typeof onEvent==="string"&&this.get(onEvent))this.get(onEvent).__addOndisconnected(ondelete)};doSub()}}else{if(typeof onEvent==="string")onEvent=this.__node.nodes.get(onEvent).__operator;if(typeof onEvent==="function"&&!onEvent?.__node)sub2=this.__node.state.subscribeEvent(nodeEvent,onEvent)}}return sub2};unsubscribe=(node,sub2,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub2,key,subInput)}else return this.get(node)?.__unsubscribe(sub2,key,subInput)};setState=update=>{this.__node.state.setState(update)}};function recursivelyAssign(target,obj,maxDepth=Infinity,curDepth=0){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&curDepth{if(graph.get(a)?.__operator){let node=graph.get(a);return(...inp)=>{node.__operator(...inp)}}else if(a.includes(".")){let split=a.split(".");let popped=split.pop();let joined=split.join(".");let node=graph.get(joined);if(typeof graph.get(joined)?.[popped]==="function"){return(...inp)=>{return node[popped](...inp)}}else return()=>{return node[popped]}}else if(graph.get(a)){let node=graph.get(a);return()=>{return node}}else{let arg=a;return()=>{return arg}}};var wrapArgs=(callback,argOrder,graph)=>{let args=[];let forArg=(a,i)=>{if(a==="__output"||a==="__input"||a==="__callback"){args[i]={__callback:inp=>{return inp},__args:void 0,idx:i}}else if(typeof a==="string"){args[i]={__callback:getCallbackFromString(a,graph),__args:void 0,idx:i}}else if(typeof a==="function"){let fn2=a;args[i]={__callback:(...inp)=>{return fn2(...inp)},__args:void 0,idx:i}}else if(typeof a==="object"&&(a.__input||a.__callback)){let recursivelyCreateCallback=function(c){let input=c.__input?c.__input:c.__callback;if(typeof c.__input==="string"){input={__callback:getCallbackFromString(c.__input,graph),__args:void 0,idx:i}}if(c.__args){let wrapped=wrapArgs(input,c.__args,graph);input={__callback:wrapped.__callback,__args:wrapped.__args,idx:i}}else{input={__callback:input,__args:void 0,idx:i}}if(c.__output){let output=c.__output;if(typeof c.__output==="string"){output={__callback:getCallbackFromString(output,graph),__args:void 0,idx:i}}else if(typeof a.__output==="object"){output=recursivelyCreateCallback(output)}if(typeof output?.__callback==="function"){let fn2=input.__callback;let callback2=output.__callback;input={__callback:(...inp)=>{return callback2(fn2(...inp))},__args:output.__args,idx:i}}}return input};args[i]=recursivelyCreateCallback(a)}else{let arg=a;args[i]={__callback:()=>{return arg},__args:void 0,idx:i}}};argOrder.forEach(forArg);if(typeof callback==="string")callback={__callback:getCallbackFromString(callback,graph),__args:void 0};let fn=typeof callback==="function"?callback:callback.__callback;callback=function(...inp){let mapArg=arg=>{return arg.__callback(...inp)};const result=fn(...args.map(mapArg));return result};return{__callback:callback,__args:args}};var objProps=Object.getOwnPropertyNames(Object.getPrototypeOf({}));var backprop=(node,parent,graph)=>{if(node.__node.backward&&parent instanceof GraphNode){graph.setListeners({[parent.__node.tag]:{[node.__node.tag]:parent}})}};var loop=(node,parent,graph)=>{if(node.__operator){let loopId=Math.random();if(!node.__node.loops)node.__node.loops={};if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{node.__node.loops[loopId]=requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;let time=node.__node.loop;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){let last=performance.now();fn(...args);node.__node.loops[loopId]=setTimeout(()=>{let now=performance.now();let overshoot=now-last-node.__node.loop;if(overshoot>0)time=node.__node.loop-overshoot;else time=node.__node.loop;if(time<=0)time=node.__node.loop;node.__operator(...args)},time)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false;if(node2.__node.loops[loopId]){clearTimeout(node2.__node.loops[loopId]);cancelAnimationFrame(node2.__node.loops[loopId])}};node.__addOndisconnected(ondelete)}}};var animate=(node,parent,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);node.__node.animationFrame=requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{node.__node.animationFrame=requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false;if(node2.__node.animationFrame)cancelAnimationFrame(node2.__node.animationFrame)};node.__addOndisconnected(ondelete)}};var branching=(node,parent,graph)=>{if(typeof node.__branch==="object"&&node.__operator&&!node.__branchApplied){let fn=node.__operator;node.__branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__branch){let triggered=()=>{if(typeof node.__branch[key].then==="function"){node.__branch[key].then(result)}else if(node.__branch[key].then instanceof GraphNode&&node.__branch[key].then.__operator){node.__branch[key].then.__operator(result)}else result=node.__branch[key].then};if(typeof node.__branch[key].if==="function"){if(node.__branch[key].if(result)==true){triggered()}}else if(node.__branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.roots?.[node.__node.tag]==="object"&&node.get)graph.__node.roots[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{name=`service${Math.floor(Math.random()*1e15)}`;restrict;constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});if(options?.services)this.addServices(options.services);if(options?.restrict)this.restrict=options.restrict;this.load(this)}addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.load(services[s])}}};handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.roots[route]}if(src?.[m]){if(typeof src[m]!=="function"){if(args){if(Array.isArray(args)&&args.length===1)src[m]=args[0];else src[m]=args;return}return src[m]}else{if(Array.isArray(args))return src[m](...args);else return src[m](args)}}else return this.handleServiceMessage({route,args,method})};handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}transmit=(...args)=>{if(typeof args[0]==="object"){const message=args[0];if(message.method){return this.handleMethod(message.route,message.method,message.args)}else if(message.route){return this.handleServiceMessage(message)}else if(message.node){return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}else return void 0};receive=(...args)=>{if(args[0]){let message=args[0];if(typeof message==="string"){let substr=message.substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))message=message.replace(/\\/g,"");if(message[0]==='"'){message=message.substring(1,message.length-1)};message=JSON.parse(message)}}if(typeof message==="object"){if(message.method){if(this.restrict?.[message.route])return void 0;return this.handleMethod(message.route,message.method,message.args)}else if(message.route){if(this.restrict?.[message.route])return void 0;return this.handleServiceMessage(message)}else if(message.node){if(typeof message.node==="string"&&this.restrict?.[message.node])return void 0;return this.handleGraphNodeCall(message.node,message.args)}else if(this.__node.keepState){if(message.route)this.setState({[message.route]:message.args});if(message.node)this.setState({[message.node]:message.args})}return void 0}}return void 0};pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeEventOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeEventOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeEventOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};terminate=(...args)=>{};isTypedArray=isTypedArray;recursivelyAssign=recursivelyAssign2;spliceTypedArray=spliceTypedArray;ping=()=>{console.log("pinged!");return"pong"};echo=(...args)=>{this.transmit(...args);return args};log=(...args)=>{console.log(...args);return true};error=(...args)=>{console.error(...args);return true}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require2=(x2=>typeof __require!=="undefined"?__require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof __require!=="undefined"?__require:a)[b]}):x2)(function(x2){if(typeof __require!=="undefined")return __require.apply(this,arguments);throw Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require22(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_gpu_browser_min=__commonJS({"src/gpu-browser.min.js"(exports,module){"use strict";(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}f()}})(function(){var define2,module2,exports2;return function(){function r(e,n,t){function o(i2,f){if(!n[i2]){if(!e[i2]){var c="function"==typeof __require2&&__require2;if(!f&&c)return c(i2,true);if(u)return u(i2,true);var a=new Error("Cannot find module '"+i2+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i2]={exports:{}};e[i2][0].call(p.exports,function(r2){var n2=e[i2][1][r2];return o(n2||r2)},p,p.exports,r,e,n,t)}return n[i2].exports}for(var u="function"==typeof __require2&&__require2,i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType2(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name2,prec){return new TokenType(name2,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name2,options){if(options===void 0)options={};options.keyword=name2;return keywords$1[name2]=new TokenType(name2,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position2(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation2(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start,end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser2(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse2(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports5);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports5){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports5,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports5,node.declaration.declarations)}else{this.checkExport(exports5,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports5);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value2=this.value;node=this.parseLiteral(value2.value);node.regex={pattern:value2.pattern,flags:value2.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value2){var node=this.startNode();node.value=value2;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref2){if(ref2===void 0)ref2={};var isTagged=ref2.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name2)>-1||scope.var.indexOf(name2)>-1;scope.lexical.push(name2);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name2]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name2)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name2)>-1}else{redeclared=scope$2.lexical.indexOf(name2)>-1||scope$2.var.indexOf(name2)>-1}scope$2.functions.push(name2)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name2)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name2)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name2)>-1){redeclared=true;break}scope$3.var.push(name2);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name2]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name2+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node2(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext2(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState2(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state2){var validFlags=state2.validFlags;var flags=state2.flags;for(var i=0;i-1){this.raise(state2.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state2){this.regexp_pattern(state2);if(!state2.switchN&&this.options.ecmaVersion>=9&&state2.groupNames.length>0){state2.switchN=true;this.regexp_pattern(state2)}};pp$8.regexp_pattern=function(state2){state2.pos=0;state2.lastIntValue=0;state2.lastStringValue="";state2.lastAssertionIsQuantifiable=false;state2.numCapturingParens=0;state2.maxBackReference=0;state2.groupNames.length=0;state2.backReferenceNames.length=0;this.regexp_disjunction(state2);if(state2.pos!==state2.source.length){if(state2.eat(41)){state2.raise("Unmatched ')'")}if(state2.eat(93)||state2.eat(125)){state2.raise("Lone quantifier brackets")}}if(state2.maxBackReference>state2.numCapturingParens){state2.raise("Invalid escape")}for(var i=0,list=state2.backReferenceNames;i=9){lookbehind=state2.eat(60)}if(state2.eat(61)||state2.eat(33)){this.regexp_disjunction(state2);if(!state2.eat(41)){state2.raise("Unterminated group")}state2.lastAssertionIsQuantifiable=!lookbehind;return true}}state2.pos=start;return false};pp$8.regexp_eatQuantifier=function(state2,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state2,noError)){state2.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state2,noError){return state2.eat(42)||state2.eat(43)||state2.eat(63)||this.regexp_eatBracedQuantifier(state2,noError)};pp$8.regexp_eatBracedQuantifier=function(state2,noError){var start=state2.pos;if(state2.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state2)){min=state2.lastIntValue;if(state2.eat(44)&&this.regexp_eatDecimalDigits(state2)){max=state2.lastIntValue}if(state2.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state2)}else if(state2.current()===63){state2.raise("Invalid group")}this.regexp_disjunction(state2);if(state2.eat(41)){state2.numCapturingParens+=1;return true}state2.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state2){return state2.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state2)||this.regexp_eatCharacterClass(state2)||this.regexp_eatUncapturingGroup(state2)||this.regexp_eatCapturingGroup(state2)||this.regexp_eatInvalidBracedQuantifier(state2)||this.regexp_eatExtendedPatternCharacter(state2)};pp$8.regexp_eatInvalidBracedQuantifier=function(state2){if(this.regexp_eatBracedQuantifier(state2,true)){state2.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state2){var ch=state2.current();if(isSyntaxCharacter(ch)){state2.lastIntValue=ch;state2.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state2){var start=state2.pos;var ch=0;while((ch=state2.current())!==-1&&!isSyntaxCharacter(ch)){state2.advance()}return state2.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state2){var ch=state2.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state2.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state2){if(state2.eat(63)){if(this.regexp_eatGroupName(state2)){if(state2.groupNames.indexOf(state2.lastStringValue)!==-1){state2.raise("Duplicate capture group name")}state2.groupNames.push(state2.lastStringValue);return}state2.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state2){state2.lastStringValue="";if(state2.eat(60)){if(this.regexp_eatRegExpIdentifierName(state2)&&state2.eat(62)){return true}state2.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state2){state2.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierStart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierPart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state2){if(this.regexp_eatBackReference(state2)||this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)||state2.switchN&&this.regexp_eatKGroupName(state2)){return true}if(state2.switchU){if(state2.current()===99){state2.raise("Invalid unicode escape")}state2.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state2){var start=state2.pos;if(this.regexp_eatDecimalEscape(state2)){var n=state2.lastIntValue;if(state2.switchU){if(n>state2.maxBackReference){state2.maxBackReference=n}return true}if(n<=state2.numCapturingParens){return true}state2.pos=start}return false};pp$8.regexp_eatKGroupName=function(state2){if(state2.eat(107)){if(this.regexp_eatGroupName(state2)){state2.backReferenceNames.push(state2.lastStringValue);return true}state2.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state2){return this.regexp_eatControlEscape(state2)||this.regexp_eatCControlLetter(state2)||this.regexp_eatZero(state2)||this.regexp_eatHexEscapeSequence(state2)||this.regexp_eatRegExpUnicodeEscapeSequence(state2)||!state2.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state2)||this.regexp_eatIdentityEscape(state2)};pp$8.regexp_eatCControlLetter=function(state2){var start=state2.pos;if(state2.eat(99)){if(this.regexp_eatControlLetter(state2)){return true}state2.pos=start}return false};pp$8.regexp_eatZero=function(state2){if(state2.current()===48&&!isDecimalDigit(state2.lookahead())){state2.lastIntValue=0;state2.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state2){var ch=state2.current();if(ch===116){state2.lastIntValue=9;state2.advance();return true}if(ch===110){state2.lastIntValue=10;state2.advance();return true}if(ch===118){state2.lastIntValue=11;state2.advance();return true}if(ch===102){state2.lastIntValue=12;state2.advance();return true}if(ch===114){state2.lastIntValue=13;state2.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state2){var ch=state2.current();if(isControlLetter(ch)){state2.lastIntValue=ch%32;state2.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(117)){if(this.regexp_eatFixedHexDigits(state2,4)){var lead=state2.lastIntValue;if(state2.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state2.pos;if(state2.eat(92)&&state2.eat(117)&&this.regexp_eatFixedHexDigits(state2,4)){var trail=state2.lastIntValue;if(trail>=56320&&trail<=57343){state2.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state2.pos=leadSurrogateEnd;state2.lastIntValue=lead}return true}if(state2.switchU&&state2.eat(123)&&this.regexp_eatHexDigits(state2)&&state2.eat(125)&&isValidUnicode(state2.lastIntValue)){return true}if(state2.switchU){state2.raise("Invalid unicode escape")}state2.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state2){if(state2.switchU){if(this.regexp_eatSyntaxCharacter(state2)){return true}if(state2.eat(47)){state2.lastIntValue=47;return true}return false}var ch=state2.current();if(ch!==99&&(!state2.switchN||ch!==107)){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state2){state2.lastIntValue=0;var ch=state2.current();if(ch>=49&&ch<=57){do{state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}while((ch=state2.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state2){var ch=state2.current();if(isCharacterClassEscape(ch)){state2.lastIntValue=-1;state2.advance();return true}if(state2.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state2.lastIntValue=-1;state2.advance();if(state2.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state2)&&state2.eat(125)){return true}state2.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state2){var start=state2.pos;if(this.regexp_eatUnicodePropertyName(state2)&&state2.eat(61)){var name2=state2.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state2)){var value2=state2.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state2,name2,value2);return true}}state2.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state2)){var nameOrValue=state2.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state2,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state2,name2,value2){if(!has(state2.unicodeProperties.nonBinary,name2)){state2.raise("Invalid property name")}if(!state2.unicodeProperties.nonBinary[name2].test(value2)){state2.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state2,nameOrValue){if(!state2.unicodeProperties.binary.test(nameOrValue)){state2.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state2){return this.regexp_eatUnicodePropertyValue(state2)};pp$8.regexp_eatCharacterClass=function(state2){if(state2.eat(91)){state2.eat(94);this.regexp_classRanges(state2);if(state2.eat(93)){return true}state2.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state2){while(this.regexp_eatClassAtom(state2)){var left=state2.lastIntValue;if(state2.eat(45)&&this.regexp_eatClassAtom(state2)){var right=state2.lastIntValue;if(state2.switchU&&(left===-1||right===-1)){state2.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state2.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state2){var start=state2.pos;if(state2.eat(92)){if(this.regexp_eatClassEscape(state2)){return true}if(state2.switchU){var ch$1=state2.current();if(ch$1===99||isOctalDigit(ch$1)){state2.raise("Invalid class escape")}state2.raise("Invalid escape")}state2.pos=start}var ch=state2.current();if(ch!==93){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state2){var start=state2.pos;if(state2.eat(98)){state2.lastIntValue=8;return true}if(state2.switchU&&state2.eat(45)){state2.lastIntValue=45;return true}if(!state2.switchU&&state2.eat(99)){if(this.regexp_eatClassControlLetter(state2)){return true}state2.pos=start}return this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)};pp$8.regexp_eatClassControlLetter=function(state2){var ch=state2.current();if(isDecimalDigit(ch)||ch===95){state2.lastIntValue=ch%32;state2.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(120)){if(this.regexp_eatFixedHexDigits(state2,2)){return true}if(state2.switchU){state2.raise("Invalid escape")}state2.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isDecimalDigit(ch=state2.current())){state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}return state2.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isHexDigit(ch=state2.current())){state2.lastIntValue=16*state2.lastIntValue+hexToInt(ch);state2.advance()}return state2.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state2){if(this.regexp_eatOctalDigit(state2)){var n1=state2.lastIntValue;if(this.regexp_eatOctalDigit(state2)){var n2=state2.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state2)){state2.lastIntValue=n1*64+n2*8+state2.lastIntValue}else{state2.lastIntValue=n1*8+n2}}else{state2.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state2){var ch=state2.current();if(isOctalDigit(ch)){state2.lastIntValue=ch-48;state2.advance();return true}state2.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state2,length){var start=state2.pos;state2.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state2=this.regexpState||(this.regexpState=new RegExpValidationState(this));state2.reset(start,pattern,flags);this.validateRegExpFlags(state2);this.validateRegExpPattern(state2);var value2=null;try{value2=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern,flags,value:value2})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos0){recording.pop()}}function insertVariable(name2,value2){variables[name2]=value2}function getEntity(value2){const name2=entityNames[value2];if(name2){return contextName+"."+name2}return value2}function setIndent(spaces){indent=" ".repeat(spaces)}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;recording.push(`${indent}const ${variableName} = ${source};`);contextVariables.push(value2);return variableName}function writePPM(width,height){const sourceVariable=`${contextName}Variable${contextVariables.length}`;const imageVariable=`imageDatum${imageCount}`;recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`);recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`);recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`);recording.push(`${indent}}`);recording.push(`${indent}if (typeof require !== "undefined") {`);recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`);recording.push(`${indent}}`);imageCount++}function addComment(value2){recording.push(`${indent}// ${value2}`)}function checkThrowError(){recording.push(`${indent}(() => { +(()=>{var __require=(x2=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x2)(function(x2){if(typeof require!=="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+x2+'" is not supported')});var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value2)=>{this.data[key]=value2;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub2)=>{let triggers=this.triggers[key];if(triggers){if(!sub2)delete this.triggers[key];else{let sub3=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub3){sub3=i;return true}});if(obj)triggers.splice(sub3,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub2;let changed=value2=>{onchange(value2);this.unsubscribeTrigger(key,sub2)};sub2=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub2)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub2)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub2=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub2);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub2};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub2;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub2=subscribeToFunction(k);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub2}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub2;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub2=subscribeToFunction(k);else if(callback?.__node)sub2=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub2}};this.__unsubscribe=(sub2,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub2)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub2)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub2=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub2);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value2=>{obj[k]=value2;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value2)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v=>{localState[k]=v;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub2;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub2=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub2}}else{sub2=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub2}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub2=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub2}}else{sub2=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub2}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub2;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub2=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub2,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub2=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub2)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub2=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub2).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub2=this.__node.state.subscribeTrigger(node,callback)}}return sub2};this.unsubscribe=(node,sub2,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub2,key,subInput)}else return this.get(node)?.__unsubscribe(sub2,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x2){return ArrayBuffer.isView(x2)&&Object.prototype.toString.call(x2)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __require2=(x2=>typeof __require!=="undefined"?__require:typeof Proxy!=="undefined"?new Proxy(x2,{get:(a,b)=>(typeof __require!=="undefined"?__require:a)[b]}):x2)(function(x2){if(typeof __require!=="undefined")return __require.apply(this,arguments);throw new Error('Dynamic require of "'+x2+'" is not supported')});var __commonJS=(cb,mod)=>function __require22(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_gpu_browser_min=__commonJS({"src/gpu-browser.min.js"(exports,module){"use strict";(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}f()}})(function(){var define2,module2,exports2;return function(){function r(e,n,t){function o(i2,f){if(!n[i2]){if(!e[i2]){var c="function"==typeof __require2&&__require2;if(!f&&c)return c(i2,true);if(u)return u(i2,true);var a=new Error("Cannot find module '"+i2+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i2]={exports:{}};e[i2][0].call(p.exports,function(r2){var n2=e[i2][1][r2];return o(n2||r2)},p,p.exports,r,e,n,t)}return n[i2].exports}for(var u="function"==typeof __require2&&__require2,i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType2(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name2,prec){return new TokenType(name2,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name2,options){if(options===void 0)options={};options.keyword=name2;return keywords$1[name2]=new TokenType(name2,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position2(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation2(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start,end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser2(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse2(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports5);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports5){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports5,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports5,node.declaration.declarations)}else{this.checkExport(exports5,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports5);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value2=this.value;node=this.parseLiteral(value2.value);node.regex={pattern:value2.pattern,flags:value2.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value2){var node=this.startNode();node.value=value2;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref2){var isTagged=ref2.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref2){if(ref2===void 0)ref2={};var isTagged=ref2.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name2)>-1||scope.var.indexOf(name2)>-1;scope.lexical.push(name2);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name2]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name2)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name2)>-1}else{redeclared=scope$2.lexical.indexOf(name2)>-1||scope$2.var.indexOf(name2)>-1}scope$2.functions.push(name2)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name2)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name2)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name2)>-1){redeclared=true;break}scope$3.var.push(name2);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name2]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name2+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node2(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext2(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent2=this.curContext();if(parent2===types$1.f_expr||parent2===types$1.f_stat){return true}if(prevType===types.colon&&(parent2===types$1.b_stat||parent2===types$1.b_expr)){return!parent2.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent2===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState2(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state2){var validFlags=state2.validFlags;var flags=state2.flags;for(var i=0;i-1){this.raise(state2.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state2){this.regexp_pattern(state2);if(!state2.switchN&&this.options.ecmaVersion>=9&&state2.groupNames.length>0){state2.switchN=true;this.regexp_pattern(state2)}};pp$8.regexp_pattern=function(state2){state2.pos=0;state2.lastIntValue=0;state2.lastStringValue="";state2.lastAssertionIsQuantifiable=false;state2.numCapturingParens=0;state2.maxBackReference=0;state2.groupNames.length=0;state2.backReferenceNames.length=0;this.regexp_disjunction(state2);if(state2.pos!==state2.source.length){if(state2.eat(41)){state2.raise("Unmatched ')'")}if(state2.eat(93)||state2.eat(125)){state2.raise("Lone quantifier brackets")}}if(state2.maxBackReference>state2.numCapturingParens){state2.raise("Invalid escape")}for(var i=0,list=state2.backReferenceNames;i=9){lookbehind=state2.eat(60)}if(state2.eat(61)||state2.eat(33)){this.regexp_disjunction(state2);if(!state2.eat(41)){state2.raise("Unterminated group")}state2.lastAssertionIsQuantifiable=!lookbehind;return true}}state2.pos=start;return false};pp$8.regexp_eatQuantifier=function(state2,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state2,noError)){state2.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state2,noError){return state2.eat(42)||state2.eat(43)||state2.eat(63)||this.regexp_eatBracedQuantifier(state2,noError)};pp$8.regexp_eatBracedQuantifier=function(state2,noError){var start=state2.pos;if(state2.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state2)){min=state2.lastIntValue;if(state2.eat(44)&&this.regexp_eatDecimalDigits(state2)){max=state2.lastIntValue}if(state2.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state2)}else if(state2.current()===63){state2.raise("Invalid group")}this.regexp_disjunction(state2);if(state2.eat(41)){state2.numCapturingParens+=1;return true}state2.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state2){return state2.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state2)||this.regexp_eatCharacterClass(state2)||this.regexp_eatUncapturingGroup(state2)||this.regexp_eatCapturingGroup(state2)||this.regexp_eatInvalidBracedQuantifier(state2)||this.regexp_eatExtendedPatternCharacter(state2)};pp$8.regexp_eatInvalidBracedQuantifier=function(state2){if(this.regexp_eatBracedQuantifier(state2,true)){state2.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state2){var ch=state2.current();if(isSyntaxCharacter(ch)){state2.lastIntValue=ch;state2.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state2){var start=state2.pos;var ch=0;while((ch=state2.current())!==-1&&!isSyntaxCharacter(ch)){state2.advance()}return state2.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state2){var ch=state2.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state2.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state2){if(state2.eat(63)){if(this.regexp_eatGroupName(state2)){if(state2.groupNames.indexOf(state2.lastStringValue)!==-1){state2.raise("Duplicate capture group name")}state2.groupNames.push(state2.lastStringValue);return}state2.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state2){state2.lastStringValue="";if(state2.eat(60)){if(this.regexp_eatRegExpIdentifierName(state2)&&state2.eat(62)){return true}state2.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state2){state2.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state2)){state2.lastStringValue+=codePointToString(state2.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierStart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state2){var start=state2.pos;var ch=state2.current();state2.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state2)){ch=state2.lastIntValue}if(isRegExpIdentifierPart(ch)){state2.lastIntValue=ch;return true}state2.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state2){if(this.regexp_eatBackReference(state2)||this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)||state2.switchN&&this.regexp_eatKGroupName(state2)){return true}if(state2.switchU){if(state2.current()===99){state2.raise("Invalid unicode escape")}state2.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state2){var start=state2.pos;if(this.regexp_eatDecimalEscape(state2)){var n=state2.lastIntValue;if(state2.switchU){if(n>state2.maxBackReference){state2.maxBackReference=n}return true}if(n<=state2.numCapturingParens){return true}state2.pos=start}return false};pp$8.regexp_eatKGroupName=function(state2){if(state2.eat(107)){if(this.regexp_eatGroupName(state2)){state2.backReferenceNames.push(state2.lastStringValue);return true}state2.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state2){return this.regexp_eatControlEscape(state2)||this.regexp_eatCControlLetter(state2)||this.regexp_eatZero(state2)||this.regexp_eatHexEscapeSequence(state2)||this.regexp_eatRegExpUnicodeEscapeSequence(state2)||!state2.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state2)||this.regexp_eatIdentityEscape(state2)};pp$8.regexp_eatCControlLetter=function(state2){var start=state2.pos;if(state2.eat(99)){if(this.regexp_eatControlLetter(state2)){return true}state2.pos=start}return false};pp$8.regexp_eatZero=function(state2){if(state2.current()===48&&!isDecimalDigit(state2.lookahead())){state2.lastIntValue=0;state2.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state2){var ch=state2.current();if(ch===116){state2.lastIntValue=9;state2.advance();return true}if(ch===110){state2.lastIntValue=10;state2.advance();return true}if(ch===118){state2.lastIntValue=11;state2.advance();return true}if(ch===102){state2.lastIntValue=12;state2.advance();return true}if(ch===114){state2.lastIntValue=13;state2.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state2){var ch=state2.current();if(isControlLetter(ch)){state2.lastIntValue=ch%32;state2.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(117)){if(this.regexp_eatFixedHexDigits(state2,4)){var lead=state2.lastIntValue;if(state2.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state2.pos;if(state2.eat(92)&&state2.eat(117)&&this.regexp_eatFixedHexDigits(state2,4)){var trail=state2.lastIntValue;if(trail>=56320&&trail<=57343){state2.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state2.pos=leadSurrogateEnd;state2.lastIntValue=lead}return true}if(state2.switchU&&state2.eat(123)&&this.regexp_eatHexDigits(state2)&&state2.eat(125)&&isValidUnicode(state2.lastIntValue)){return true}if(state2.switchU){state2.raise("Invalid unicode escape")}state2.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state2){if(state2.switchU){if(this.regexp_eatSyntaxCharacter(state2)){return true}if(state2.eat(47)){state2.lastIntValue=47;return true}return false}var ch=state2.current();if(ch!==99&&(!state2.switchN||ch!==107)){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state2){state2.lastIntValue=0;var ch=state2.current();if(ch>=49&&ch<=57){do{state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}while((ch=state2.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state2){var ch=state2.current();if(isCharacterClassEscape(ch)){state2.lastIntValue=-1;state2.advance();return true}if(state2.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state2.lastIntValue=-1;state2.advance();if(state2.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state2)&&state2.eat(125)){return true}state2.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state2){var start=state2.pos;if(this.regexp_eatUnicodePropertyName(state2)&&state2.eat(61)){var name2=state2.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state2)){var value2=state2.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state2,name2,value2);return true}}state2.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state2)){var nameOrValue=state2.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state2,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state2,name2,value2){if(!has(state2.unicodeProperties.nonBinary,name2)){state2.raise("Invalid property name")}if(!state2.unicodeProperties.nonBinary[name2].test(value2)){state2.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state2,nameOrValue){if(!state2.unicodeProperties.binary.test(nameOrValue)){state2.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state2){var ch=0;state2.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state2.current())){state2.lastStringValue+=codePointToString(ch);state2.advance()}return state2.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state2){return this.regexp_eatUnicodePropertyValue(state2)};pp$8.regexp_eatCharacterClass=function(state2){if(state2.eat(91)){state2.eat(94);this.regexp_classRanges(state2);if(state2.eat(93)){return true}state2.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state2){while(this.regexp_eatClassAtom(state2)){var left=state2.lastIntValue;if(state2.eat(45)&&this.regexp_eatClassAtom(state2)){var right=state2.lastIntValue;if(state2.switchU&&(left===-1||right===-1)){state2.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state2.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state2){var start=state2.pos;if(state2.eat(92)){if(this.regexp_eatClassEscape(state2)){return true}if(state2.switchU){var ch$1=state2.current();if(ch$1===99||isOctalDigit(ch$1)){state2.raise("Invalid class escape")}state2.raise("Invalid escape")}state2.pos=start}var ch=state2.current();if(ch!==93){state2.lastIntValue=ch;state2.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state2){var start=state2.pos;if(state2.eat(98)){state2.lastIntValue=8;return true}if(state2.switchU&&state2.eat(45)){state2.lastIntValue=45;return true}if(!state2.switchU&&state2.eat(99)){if(this.regexp_eatClassControlLetter(state2)){return true}state2.pos=start}return this.regexp_eatCharacterClassEscape(state2)||this.regexp_eatCharacterEscape(state2)};pp$8.regexp_eatClassControlLetter=function(state2){var ch=state2.current();if(isDecimalDigit(ch)||ch===95){state2.lastIntValue=ch%32;state2.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state2){var start=state2.pos;if(state2.eat(120)){if(this.regexp_eatFixedHexDigits(state2,2)){return true}if(state2.switchU){state2.raise("Invalid escape")}state2.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isDecimalDigit(ch=state2.current())){state2.lastIntValue=10*state2.lastIntValue+(ch-48);state2.advance()}return state2.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state2){var start=state2.pos;var ch=0;state2.lastIntValue=0;while(isHexDigit(ch=state2.current())){state2.lastIntValue=16*state2.lastIntValue+hexToInt(ch);state2.advance()}return state2.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state2){if(this.regexp_eatOctalDigit(state2)){var n1=state2.lastIntValue;if(this.regexp_eatOctalDigit(state2)){var n2=state2.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state2)){state2.lastIntValue=n1*64+n2*8+state2.lastIntValue}else{state2.lastIntValue=n1*8+n2}}else{state2.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state2){var ch=state2.current();if(isOctalDigit(ch)){state2.lastIntValue=ch-48;state2.advance();return true}state2.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state2,length){var start=state2.pos;state2.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state2=this.regexpState||(this.regexpState=new RegExpValidationState(this));state2.reset(start,pattern,flags);this.validateRegExpFlags(state2);this.validateRegExpPattern(state2);var value2=null;try{value2=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern,flags,value:value2})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos0){recording.pop()}}function insertVariable(name2,value2){variables[name2]=value2}function getEntity(value2){const name2=entityNames[value2];if(name2){return contextName+"."+name2}return value2}function setIndent(spaces){indent=" ".repeat(spaces)}function addVariable(value2,source){const variableName=`${contextName}Variable${contextVariables.length}`;recording.push(`${indent}const ${variableName} = ${source};`);contextVariables.push(value2);return variableName}function writePPM(width,height){const sourceVariable=`${contextName}Variable${contextVariables.length}`;const imageVariable=`imageDatum${imageCount}`;recording.push(`${indent}let ${imageVariable} = ["P3\\n# ${readPixelsFile}.ppm\\n", ${width}, ' ', ${height}, "\\n255\\n"].join("");`);recording.push(`${indent}for (let i = 0; i < ${imageVariable}.length; i += 4) {`);recording.push(`${indent} ${imageVariable} += ${sourceVariable}[i] + ' ' + ${sourceVariable}[i + 1] + ' ' + ${sourceVariable}[i + 2] + ' ';`);recording.push(`${indent}}`);recording.push(`${indent}if (typeof require !== "undefined") {`);recording.push(`${indent} require('fs').writeFileSync('./${readPixelsFile}.ppm', ${imageVariable});`);recording.push(`${indent}}`);imageCount++}function addComment(value2){recording.push(`${indent}// ${value2}`)}function checkThrowError(){recording.push(`${indent}(() => { ${indent}const error = ${contextName}.getError(); ${indent}if (error !== ${contextName}.NONE) { ${indent} const names = Object.getOwnPropertyNames(gl); @@ -1262,7 +1262,7 @@ ${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whil void main(void) { gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1); vTexCoord = aTexCoord; - }`;module3.exports={vertexShader}},{}],107:[function(require2,module3,exports3){const lib=require2("./index");const GPU=lib.GPU;for(const p in lib){if(!lib.hasOwnProperty(p))continue;if(p==="GPU")continue;GPU[p]=lib[p]}if(typeof window!=="undefined"){bindTo(window)}if(typeof self!=="undefined"){bindTo(self)}function bindTo(target){if(target.GPUjs)return;Object.defineProperty(target,"GPUjs",{get(){return GPU}})}module3.exports=lib},{"./index":109}],108:[function(require2,module3,exports3){const{gpuMock}=require2("gpu-mock.js");const{utils}=require2("./utils");const{Kernel}=require2("./backend/kernel");const{CPUKernel}=require2("./backend/cpu/kernel");const{HeadlessGLKernel}=require2("./backend/headless-gl/kernel");const{WebGL2Kernel}=require2("./backend/web-gl2/kernel");const{WebGLKernel}=require2("./backend/web-gl/kernel");const{kernelRunShortcut}=require2("./kernel-run-shortcut");const kernelOrder=[HeadlessGLKernel,WebGL2Kernel,WebGLKernel];const kernelTypes=["gpu","cpu"];const internalKernels={"headlessgl":HeadlessGLKernel,"webgl2":WebGL2Kernel,"webgl":WebGLKernel};let validate=true;class GPU{static disableValidation(){validate=false}static enableValidation(){validate=true}static get isGPUSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported)}static get isKernelMapSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.kernelMap)}static get isOffscreenCanvasSupported(){return typeof Worker!=="undefined"&&typeof OffscreenCanvas!=="undefined"||typeof importScripts!=="undefined"}static get isWebGLSupported(){return WebGLKernel.isSupported}static get isWebGL2Supported(){return WebGL2Kernel.isSupported}static get isHeadlessGLSupported(){return HeadlessGLKernel.isSupported}static get isCanvasSupported(){return typeof HTMLCanvasElement!=="undefined"}static get isGPUHTMLImageArraySupported(){return WebGL2Kernel.isSupported}static get isSinglePrecisionSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.isFloatRead&&Kernel2.features.isTextureFloat)}constructor(settings){settings=settings||{};this.canvas=settings.canvas||null;this.context=settings.context||null;this.mode=settings.mode;this.Kernel=null;this.kernels=[];this.functions=[];this.nativeFunctions=[];this.injectedNative=null;if(this.mode==="dev")return;this.chooseKernel();if(settings.functions){for(let i=0;isettings.argumentTypes[argumentName])}function onRequestFallback(args){console.warn("Falling back to CPU");const fallbackKernel=new CPUKernel(source,{argumentTypes:kernelRun.argumentTypes,constantTypes:kernelRun.constantTypes,graphical:kernelRun.graphical,loopMaxIterations:kernelRun.loopMaxIterations,constants:kernelRun.constants,dynamicOutput:kernelRun.dynamicOutput,dynamicArgument:kernelRun.dynamicArguments,output:kernelRun.output,precision:kernelRun.precision,pipeline:kernelRun.pipeline,immutable:kernelRun.immutable,optimizeFloatMemory:kernelRun.optimizeFloatMemory,fixIntegerDivisionAccuracy:kernelRun.fixIntegerDivisionAccuracy,functions:kernelRun.functions,nativeFunctions:kernelRun.nativeFunctions,injectedNative:kernelRun.injectedNative,subKernels:kernelRun.subKernels,strictIntegers:kernelRun.strictIntegers,debug:kernelRun.debug});fallbackKernel.build.apply(fallbackKernel,args);const result=fallbackKernel.run.apply(fallbackKernel,args);kernelRun.replaceKernel(fallbackKernel);return result}function onRequestSwitchKernel(reasons,args,_kernel){if(_kernel.debug){console.warn("Switching kernels")}let newOutput=null;if(_kernel.signature&&!switchableKernels[_kernel.signature]){switchableKernels[_kernel.signature]=_kernel}if(_kernel.dynamicOutput){for(let i=reasons.length-1;i>=0;i--){const reason=reasons[i];if(reason.type==="outputPrecisionMismatch"){newOutput=reason.needed}}}const Constructor=_kernel.constructor;const argumentTypes=Constructor.getArgumentTypes(_kernel,args);const signature=Constructor.getSignature(_kernel,argumentTypes);const existingKernel=switchableKernels[signature];if(existingKernel){existingKernel.onActivate(_kernel);return existingKernel}const newKernel=switchableKernels[signature]=new Constructor(source,{argumentTypes,constantTypes:_kernel.constantTypes,graphical:_kernel.graphical,loopMaxIterations:_kernel.loopMaxIterations,constants:_kernel.constants,dynamicOutput:_kernel.dynamicOutput,dynamicArgument:_kernel.dynamicArguments,context:_kernel.context,canvas:_kernel.canvas,output:newOutput||_kernel.output,precision:_kernel.precision,pipeline:_kernel.pipeline,immutable:_kernel.immutable,optimizeFloatMemory:_kernel.optimizeFloatMemory,fixIntegerDivisionAccuracy:_kernel.fixIntegerDivisionAccuracy,functions:_kernel.functions,nativeFunctions:_kernel.nativeFunctions,injectedNative:_kernel.injectedNative,subKernels:_kernel.subKernels,strictIntegers:_kernel.strictIntegers,debug:_kernel.debug,gpu:_kernel.gpu,validate,returnType:_kernel.returnType,tactic:_kernel.tactic,onRequestFallback,onRequestSwitchKernel,texture:_kernel.texture,mappedTextures:_kernel.mappedTextures,drawBuffersMap:_kernel.drawBuffersMap});newKernel.build.apply(newKernel,args);kernelRun.replaceKernel(newKernel);kernels.push(newKernel);return newKernel}const mergedSettings=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate,onRequestFallback,onRequestSwitchKernel},settingsCopy);const kernel=new this.Kernel(source,mergedSettings);const kernelRun=kernelRunShortcut(kernel);if(!this.canvas){this.canvas=kernel.canvas}if(!this.context){this.context=kernel.context}kernels.push(kernel);return kernelRun}createKernelMap(){let fn;let settings;const argument2Type=typeof arguments[arguments.length-2];if(argument2Type==="function"||argument2Type==="string"){fn=arguments[arguments.length-2];settings=arguments[arguments.length-1]}else{fn=arguments[arguments.length-1]}if(this.mode!=="dev"){if(!this.Kernel.isSupported||!this.Kernel.features.kernelMap){if(this.mode&&kernelTypes.indexOf(this.mode)<0){throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}}}const settingsCopy=upgradeDeprecatedCreateKernelSettings(settings);if(settings&&typeof settings.argumentTypes==="object"){settingsCopy.argumentTypes=Object.keys(settings.argumentTypes).map(argumentName=>settings.argumentTypes[argumentName])}if(Array.isArray(arguments[0])){settingsCopy.subKernels=[];const functions=arguments[0];for(let i=0;i0){throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.')}this.nativeFunctions.push(Object.assign({name:name2,source},settings));return this}injectNative(source){this.injectedNative=source;return this}destroy(){return new Promise((resolve,reject)=>{if(!this.kernels){resolve()}setTimeout(()=>{try{for(let i=0;i{try{accept(run.apply(this,arguments))}catch(e){reject(e)}})};shortcut.replaceKernel=function(replacementKernel){kernel=replacementKernel;bindKernelToShortcut(kernel,shortcut)};bindKernelToShortcut(kernel,shortcut);return shortcut}function bindKernelToShortcut(kernel,shortcut){if(shortcut.kernel){shortcut.kernel=kernel;return}const properties=utils.allPropertiesOf(kernel);for(let i=0;ishortcut.kernel[property]);shortcut.__defineSetter__(property,value2=>{shortcut.kernel[property]=value2})}}shortcut.kernel=kernel}module3.exports={kernelRunShortcut}},{"./utils":114}],112:[function(require2,module3,exports3){const source=`// https://www.shadertoy.com/view/4t2SDh + }`;module3.exports={vertexShader}},{}],107:[function(require2,module3,exports3){const lib=require2("./index");const GPU2=lib.GPU;for(const p in lib){if(!lib.hasOwnProperty(p))continue;if(p==="GPU")continue;GPU2[p]=lib[p]}if(typeof window!=="undefined"){bindTo(window)}if(typeof self!=="undefined"){bindTo(self)}function bindTo(target){if(target.GPU)return;Object.defineProperty(target,"GPU",{get(){return GPU2}})}module3.exports=lib},{"./index":109}],108:[function(require2,module3,exports3){const{gpuMock}=require2("gpu-mock.js");const{utils}=require2("./utils");const{Kernel}=require2("./backend/kernel");const{CPUKernel}=require2("./backend/cpu/kernel");const{HeadlessGLKernel}=require2("./backend/headless-gl/kernel");const{WebGL2Kernel}=require2("./backend/web-gl2/kernel");const{WebGLKernel}=require2("./backend/web-gl/kernel");const{kernelRunShortcut}=require2("./kernel-run-shortcut");const kernelOrder=[HeadlessGLKernel,WebGL2Kernel,WebGLKernel];const kernelTypes=["gpu","cpu"];const internalKernels={"headlessgl":HeadlessGLKernel,"webgl2":WebGL2Kernel,"webgl":WebGLKernel};let validate=true;class GPU2{static disableValidation(){validate=false}static enableValidation(){validate=true}static get isGPUSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported)}static get isKernelMapSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.kernelMap)}static get isOffscreenCanvasSupported(){return typeof Worker!=="undefined"&&typeof OffscreenCanvas!=="undefined"||typeof importScripts!=="undefined"}static get isWebGLSupported(){return WebGLKernel.isSupported}static get isWebGL2Supported(){return WebGL2Kernel.isSupported}static get isHeadlessGLSupported(){return HeadlessGLKernel.isSupported}static get isCanvasSupported(){return typeof HTMLCanvasElement!=="undefined"}static get isGPUHTMLImageArraySupported(){return WebGL2Kernel.isSupported}static get isSinglePrecisionSupported(){return kernelOrder.some(Kernel2=>Kernel2.isSupported&&Kernel2.features.isFloatRead&&Kernel2.features.isTextureFloat)}constructor(settings){settings=settings||{};this.canvas=settings.canvas||null;this.context=settings.context||null;this.mode=settings.mode;this.Kernel=null;this.kernels=[];this.functions=[];this.nativeFunctions=[];this.injectedNative=null;if(this.mode==="dev")return;this.chooseKernel();if(settings.functions){for(let i=0;isettings.argumentTypes[argumentName])}function onRequestFallback(args){console.warn("Falling back to CPU");const fallbackKernel=new CPUKernel(source,{argumentTypes:kernelRun.argumentTypes,constantTypes:kernelRun.constantTypes,graphical:kernelRun.graphical,loopMaxIterations:kernelRun.loopMaxIterations,constants:kernelRun.constants,dynamicOutput:kernelRun.dynamicOutput,dynamicArgument:kernelRun.dynamicArguments,output:kernelRun.output,precision:kernelRun.precision,pipeline:kernelRun.pipeline,immutable:kernelRun.immutable,optimizeFloatMemory:kernelRun.optimizeFloatMemory,fixIntegerDivisionAccuracy:kernelRun.fixIntegerDivisionAccuracy,functions:kernelRun.functions,nativeFunctions:kernelRun.nativeFunctions,injectedNative:kernelRun.injectedNative,subKernels:kernelRun.subKernels,strictIntegers:kernelRun.strictIntegers,debug:kernelRun.debug});fallbackKernel.build.apply(fallbackKernel,args);const result=fallbackKernel.run.apply(fallbackKernel,args);kernelRun.replaceKernel(fallbackKernel);return result}function onRequestSwitchKernel(reasons,args,_kernel){if(_kernel.debug){console.warn("Switching kernels")}let newOutput=null;if(_kernel.signature&&!switchableKernels[_kernel.signature]){switchableKernels[_kernel.signature]=_kernel}if(_kernel.dynamicOutput){for(let i=reasons.length-1;i>=0;i--){const reason=reasons[i];if(reason.type==="outputPrecisionMismatch"){newOutput=reason.needed}}}const Constructor=_kernel.constructor;const argumentTypes=Constructor.getArgumentTypes(_kernel,args);const signature=Constructor.getSignature(_kernel,argumentTypes);const existingKernel=switchableKernels[signature];if(existingKernel){existingKernel.onActivate(_kernel);return existingKernel}const newKernel=switchableKernels[signature]=new Constructor(source,{argumentTypes,constantTypes:_kernel.constantTypes,graphical:_kernel.graphical,loopMaxIterations:_kernel.loopMaxIterations,constants:_kernel.constants,dynamicOutput:_kernel.dynamicOutput,dynamicArgument:_kernel.dynamicArguments,context:_kernel.context,canvas:_kernel.canvas,output:newOutput||_kernel.output,precision:_kernel.precision,pipeline:_kernel.pipeline,immutable:_kernel.immutable,optimizeFloatMemory:_kernel.optimizeFloatMemory,fixIntegerDivisionAccuracy:_kernel.fixIntegerDivisionAccuracy,functions:_kernel.functions,nativeFunctions:_kernel.nativeFunctions,injectedNative:_kernel.injectedNative,subKernels:_kernel.subKernels,strictIntegers:_kernel.strictIntegers,debug:_kernel.debug,gpu:_kernel.gpu,validate,returnType:_kernel.returnType,tactic:_kernel.tactic,onRequestFallback,onRequestSwitchKernel,texture:_kernel.texture,mappedTextures:_kernel.mappedTextures,drawBuffersMap:_kernel.drawBuffersMap});newKernel.build.apply(newKernel,args);kernelRun.replaceKernel(newKernel);kernels.push(newKernel);return newKernel}const mergedSettings=Object.assign({context:this.context,canvas:this.canvas,functions:this.functions,nativeFunctions:this.nativeFunctions,injectedNative:this.injectedNative,gpu:this,validate,onRequestFallback,onRequestSwitchKernel},settingsCopy);const kernel=new this.Kernel(source,mergedSettings);const kernelRun=kernelRunShortcut(kernel);if(!this.canvas){this.canvas=kernel.canvas}if(!this.context){this.context=kernel.context}kernels.push(kernel);return kernelRun}createKernelMap(){let fn;let settings;const argument2Type=typeof arguments[arguments.length-2];if(argument2Type==="function"||argument2Type==="string"){fn=arguments[arguments.length-2];settings=arguments[arguments.length-1]}else{fn=arguments[arguments.length-1]}if(this.mode!=="dev"){if(!this.Kernel.isSupported||!this.Kernel.features.kernelMap){if(this.mode&&kernelTypes.indexOf(this.mode)<0){throw new Error(`kernelMap not supported on ${this.Kernel.name}`)}}}const settingsCopy=upgradeDeprecatedCreateKernelSettings(settings);if(settings&&typeof settings.argumentTypes==="object"){settingsCopy.argumentTypes=Object.keys(settings.argumentTypes).map(argumentName=>settings.argumentTypes[argumentName])}if(Array.isArray(arguments[0])){settingsCopy.subKernels=[];const functions=arguments[0];for(let i=0;i0){throw new Error('Cannot call "addNativeFunction" after "createKernels" has been called.')}this.nativeFunctions.push(Object.assign({name:name2,source},settings));return this}injectNative(source){this.injectedNative=source;return this}destroy(){return new Promise((resolve,reject)=>{if(!this.kernels){resolve()}setTimeout(()=>{try{for(let i=0;i{try{accept(run.apply(this,arguments))}catch(e){reject(e)}})};shortcut.replaceKernel=function(replacementKernel){kernel=replacementKernel;bindKernelToShortcut(kernel,shortcut)};bindKernelToShortcut(kernel,shortcut);return shortcut}function bindKernelToShortcut(kernel,shortcut){if(shortcut.kernel){shortcut.kernel=kernel;return}const properties=utils.allPropertiesOf(kernel);for(let i=0;ishortcut.kernel[property]);shortcut.__defineSetter__(property,value2=>{shortcut.kernel[property]=value2})}}shortcut.kernel=kernel}module3.exports={kernelRunShortcut}},{"./utils":114}],112:[function(require2,module3,exports3){const source=`// https://www.shadertoy.com/view/4t2SDh //note: uniformly distributed, normalized rand, [0,1] highp float randomSeedShift = 1.0; highp float slide = 1.0; @@ -1278,23 +1278,19 @@ ${updateArr.join("")};`);retArr.push("}\n")}return retArr}astWhileStatement(whil slide += 0.0009; } return result; - }`;const name2="math-random-uniformly-distributed";const functionMatch=`Math.random()`;const functionReplace=`nrand(vTexCoord)`;const functionReturnType="Number";const onBeforeRun=kernel=>{kernel.setUniform1f("randomSeed1",Math.random());kernel.setUniform1f("randomSeed2",Math.random())};const plugin={name:name2,onBeforeRun,functionMatch,functionReplace,functionReturnType,source};module3.exports=plugin},{}],113:[function(require2,module3,exports3){class Texture{constructor(settings){const{texture,size,dimensions,output,context,type="NumberTexture",kernel,internalFormat,textureFormat}=settings;if(!output)throw new Error('settings property "output" required.');if(!context)throw new Error('settings property "context" required.');if(!texture)throw new Error('settings property "texture" required.');if(!kernel)throw new Error('settings property "kernel" required.');this.texture=texture;if(texture._refs){texture._refs++}else{texture._refs=1}this.size=size;this.dimensions=dimensions;this.output=output;this.context=context;this.kernel=kernel;this.type=type;this._deleted=false;this.internalFormat=internalFormat;this.textureFormat=textureFormat}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}module3.exports={Texture}},{}],114:[function(require2,module3,exports3){const acorn=require2("acorn");const{Input}=require2("./input");const{Texture}=require2("./texture");const FUNCTION_NAME=/function ([^(]*)/;const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const ARGUMENT_NAMES=/([^\s,]+)/g;const utils={systemEndianness(){return _systemEndianness},getSystemEndianness(){const b=new ArrayBuffer(4);const a=new Uint32Array(b);const c=new Uint8Array(b);a[0]=3735928559;if(c[0]===239)return"LE";if(c[0]===222)return"BE";throw new Error("unknown endianness")},isFunction(funcObj){return typeof funcObj==="function"},isFunctionString(fn){if(typeof fn==="string"){return fn.slice(0,"function".length).toLowerCase()==="function"}return false},getFunctionNameFromString(funcStr){const result=FUNCTION_NAME.exec(funcStr);if(!result||result.length===0)return null;return result[1].trim()},getFunctionBodyFromString(funcStr){return funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"))},getArgumentNamesFromString(fn){const fnStr=fn.replace(STRIP_COMMENTS,"");let result=fnStr.slice(fnStr.indexOf("(")+1,fnStr.indexOf(")")).match(ARGUMENT_NAMES);if(result===null){result=[]}return result},clone(obj){if(obj===null||typeof obj!=="object"||obj.hasOwnProperty("isActiveClone"))return obj;const temp=obj.constructor();for(let key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){obj.isActiveClone=null;temp[key]=utils.clone(obj[key]);delete obj.isActiveClone}}return temp},isArray(array){return!isNaN(array.length)},getVariableType(value2,strictIntegers){if(utils.isArray(value2)){if(value2.length>0&&value2[0].nodeName==="IMG"){return"HTMLImageArray"}return"Array"}switch(value2.constructor){case Boolean:return"Boolean";case Number:if(strictIntegers&&Number.isInteger(value2)){return"Integer"}return"Float";case Texture:return value2.type;case Input:return"Input"}switch(value2.nodeName){case"IMG":return"HTMLImage";case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}if(value2.hasOwnProperty("type")){return value2.type}return"Unknown"},getKernelTextureSize(settings,dimensions){let[w,h,d]=dimensions;let texelCount=(w||1)*(h||1)*(d||1);if(settings.optimizeFloatMemory&&settings.precision==="single"){w=texelCount=Math.ceil(texelCount/4)}if(h>1&&w*h===texelCount){return new Int32Array([w,h])}return utils.closestSquareDimensions(texelCount)},closestSquareDimensions(length){const sqrt=Math.sqrt(length);let high=Math.ceil(sqrt);let low=Math.floor(sqrt);while(high*low0){return lines.join(";\n")+";\n"}else{return"\n"}},warnDeprecated(type,oldName,newName){if(newName){console.warn(`You are using a deprecated ${type} "${oldName}". It has been replaced with "${newName}". Fixing, but please upgrade as it will soon be removed.`)}else{console.warn(`You are using a deprecated ${type} "${oldName}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)}},flipPixels:(pixels,width,height)=>{const halfHeight=height/2|0;const bytesPerRow=width*4;const temp=new Uint8ClampedArray(width*4);const result=pixels.slice(0);for(let y=0;y{return array.subarray(0,width)},erect2DPackedFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{return array.subarray(0,width)},erectMemoryOptimized2DFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{const xResults=new Float32Array(width);let i=0;for(let x2=0;x2{const yResults=new Array(height);let i=0;for(let y=0;y{const zResults=new Array(depth);let i=0;for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const yResults=new Array(height);const XResultsMax=width*4;for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(array);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const{findDependency,thisLookup,doNotDefine}=settings;let flattened=settings.flattened;if(!flattened){flattened=settings.flattened={}}const ast=acorn.parse(source);const functionDependencies=[];let indent=0;function flatten2(ast2){if(Array.isArray(ast2)){const results=[];for(let i=0;ir!==null);if(declarations.length<1){return""}else{return`${ast2.kind} ${declarations.join(",")}`}case"VariableDeclarator":if(ast2.init.object&&ast2.init.object.type==="ThisExpression"){const lookup=thisLookup(ast2.init.property.name,true);if(lookup){return`${ast2.id.name} = ${flatten2(ast2.init)}`}else{return null}}else{return`${ast2.id.name} = ${flatten2(ast2.init)}`}case"CallExpression":{if(ast2.callee.property.name==="subarray"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.name==="gl"||ast2.callee.object.name==="context"){return`${flatten2(ast2.callee.object)}.${flatten2(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}if(ast2.callee.object.type==="ThisExpression"){functionDependencies.push(findDependency("this",ast2.callee.property.name));return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else if(ast2.callee.object.name){const foundSource=findDependency(ast2.callee.object.name,ast2.callee.property.name);if(foundSource===null){return`${ast2.callee.object.name}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{functionDependencies.push(foundSource);return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}}else if(ast2.callee.object.type==="MemberExpression"){return`${flatten2(ast2.callee.object)}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`}else{throw new Error("unknown ast.callee")}}case"ReturnStatement":return`return ${flatten2(ast2.argument)}`;case"BinaryExpression":return`(${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)})`;case"UnaryExpression":if(ast2.prefix){return`${ast2.operator} ${flatten2(ast2.argument)}`}else{return`${flatten2(ast2.argument)} ${ast2.operator}`}case"ExpressionStatement":return`${flatten2(ast2.expression)}`;case"SequenceExpression":return`(${flatten2(ast2.expressions)})`;case"ArrowFunctionExpression":return`(${ast2.params.map(flatten2).join(", ")}) => ${flatten2(ast2.body)}`;case"Literal":return ast2.raw;case"Identifier":return ast2.name;case"MemberExpression":if(ast2.object.type==="ThisExpression"){return thisLookup(ast2.property.name)}if(ast2.computed){return`${flatten2(ast2.object)}[${flatten2(ast2.property)}]`}return flatten2(ast2.object)+"."+flatten2(ast2.property);case"ThisExpression":return"this";case"NewExpression":return`new ${flatten2(ast2.callee)}(${ast2.arguments.map(value2=>flatten2(value2)).join(", ")})`;case"ForStatement":return`for (${flatten2(ast2.init)};${flatten2(ast2.test)};${flatten2(ast2.update)}) ${flatten2(ast2.body)}`;case"AssignmentExpression":return`${flatten2(ast2.left)}${ast2.operator}${flatten2(ast2.right)}`;case"UpdateExpression":return`${flatten2(ast2.argument)}${ast2.operator}`;case"IfStatement":return`if (${flatten2(ast2.test)}) ${flatten2(ast2.consequent)}`;case"ThrowStatement":return`throw ${flatten2(ast2.argument)}`;case"ObjectPattern":return ast2.properties.map(flatten2).join(", ");case"ArrayPattern":return ast2.elements.map(flatten2).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${flatten2(ast2.test)}?${flatten2(ast2.consequent)}:${flatten2(ast2.alternate)}`;case"Property":if(ast2.kind==="init"){return flatten2(ast2.key)}}throw new Error(`unhandled ast.type of ${ast2.type}`)}const result=flatten2(ast);if(functionDependencies.length>0){const flattenedFunctionDependencies=[];for(let i=0;i{if(ast.type!=="VariableDeclaration")throw new Error('Ast is not of type "VariableDeclaration"');const normalizedDeclarations=[];for(let declarationIndex=0;declarationIndex{const rKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.r*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const gKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.g*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const bKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.b*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const aKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.a*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const result=[rKernel(image),gKernel(image),bKernel(image),aKernel(image)];result.rKernel=rKernel;result.gKernel=gKernel;result.bKernel=bKernel;result.aKernel=aKernel;result.gpu=gpu;return result},splitRGBAToCanvases:(gpu,rgba,width,height)=>{const visualKernelR=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(pixel.r/255,0,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelR(rgba);const visualKernelG=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,pixel.g/255,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelG(rgba);const visualKernelB=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,0,pixel.b/255,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelB(rgba);const visualKernelA=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(255,255,255,pixel.a/255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelA(rgba);return[visualKernelR.canvas,visualKernelG.canvas,visualKernelB.canvas,visualKernelA.canvas]},getMinifySafeName:fn=>{try{const ast=acorn.parse(`const value = ${fn.toString()}`);const{init}=ast.body[0].declarations[0];return init.body.name||init.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(name2){if(dollarSign.test(name2)){name2=name2.replace(dollarSign,"S_S")}if(doubleUnderscore.test(name2)){name2=name2.replace(doubleUnderscore,"U_U")}else if(singleUnderscore.test(name2)){name2=name2.replace(singleUnderscore,"u_u")}return name2}};const dollarSign=/\$/;const doubleUnderscore=/__/;const singleUnderscore=/_/;const _systemEndianness=utils.getSystemEndianness();module3.exports={utils}},{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107)})}});var import_gpu_browser_min=__toESM(require_gpu_browser_min());function add(a,b){return a+b}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function cadd(a_real,a_imag,b_real,b_imag){return[a_real+b_real,a_imag+b_imag]}function csub(a_real,a_imag,b_real,b_imag){return[a_real-b_real,a_imag-b_imag]}function cmul(a_real,a_imag,b_real,b_imag){return[a_real*b_real-a_imag*b_imag,a_real*b_imag+a_imag*b_real]}function cexp(a_real,a_imag){const er=Math.exp(a_real);return[er*Math.cos(a_imag),er*Math.sin(a_imag)]}function mag(a,b){return Math.sqrt(a*a+b*b)}function conj(imag){return 0-imag}function lof(n){const sqrt_n=Math.sqrt(n);var factor=3;while(factor<=sqrt_n){if(n%factor===0)return factor;factor+=2}}function mean(arr,len){var mean2=0;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signal[j]*Math.cos(sharedi);imag=imag-signal[j]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function FFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=imag-signals[j+(len-1)*n]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function iDFT(fft,len,freq){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+fft[j]*Math.cos(sharedi);imag=fft[j]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function iFFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=signals[j+(len-1)*n]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function correlogramsKern(arrays,len){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=mean(arrays[k],len);var arr2mean=mean(arrays[k+1],len);var arr1Est=est(arrays[k],arr1mean,len);var arr2Est2=est(arrays[k+1],arr2mean,len);var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function correlogramsPCKern(arrays,len,means,estimators){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=means[k];var arr2mean=means[k+1];var arr1Est=estimators[k];var arr2Est2=estimators[k+1];var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function dftKern(signal,len,scalar){var result=DFT(signal,len,this.thread.x);return mag(result[0],result[1])*scalar}function idftKern(amplitudes,len,scalar){var result=iDFT(amplitudes,len,this.thread.x);return mag(result[0],result[1])*scalar}function fftKern(signal,len,scalar,sampleRate){var result=FFT(signal,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function ifftKern(amplitudes,len,scalar,sampleRate){var result=iFFT(amplitudes,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function listdft2DKern(signals,scalar){var len=this.output.x;var result=DFT(signals[this.thread.y],len,this.thread.x);return mag(result[0],result[1])*scalar}function listdft1DKern(signals,len,scalar){var result=[0,0];if(this.thread.x<=len){result=DFT(signals,len,this.thread.x)}else{var n=Math.floor(this.thread.x/len);result=DFTlist(signals,len,this.thread.x-n*len,n)}return mag(result[0],result[1])*scalar}function listfft1DKern(signals,len,scalar,sps){var result=[0,0];if(this.thread.x<=len){result=FFT(signals,len,this.thread.x,sps)}else{var n=Math.floor(this.thread.x/len);result=FFTlist(signals,len,this.thread.x-n*len,n,sps)}return mag(result[0],result[1])*scalar}function dft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=DFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function fft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=FFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function idft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iDFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function ifft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iFFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function listdft1D_windowedKern(signals,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];if(this.thread.x=width){i++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+i+kernelRadius;const weights=kernel[kernelOffset];const pixel=img[this.thread.y+i][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}i++}this.color(r,g,b)}function multiImgConv2DKern(img,width,height,kernels,kernelLengths,nKernels){let r=0,g=0,b=0;for(var i=0;i=width){k++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+k+kernelRadius;const weights=kernels[i][kernelOffset];const pixel=img[this.thread.y+k][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}k++}}this.color(r,g,b)}function transpose2DKern(mat2){return mat2[this.thread.y][this.thread.x]}var createGpuKernels={correlogramsKern,correlogramsPCKern,dftKern,idftKern,fftKern,ifftKern,dft_windowedKern,idft_windowedKern,fft_windowedKern,ifft_windowedKern,listdft2DKern,listdft1DKern,listfft1DKern,listfft1D_windowedKern,listdft1D_windowedKern,listidft1D_windowedKern,listifft1D_windowedKern,bulkArrayMulKern,multiImgConv2DKern,ImgConv2DKern,transpose2DKern};var addGpuFunctions=[add,sub,mul,div,cadd,csub,cmul,cexp,mag,conj,lof,mean,est,mse,rms,xcor,softmax,DFT,DFTlist,iDFT,iDFTlist,FFT,iFFT,iFFTlist];function makeKrnl(gpu,f,opts={setDynamicOutput:true,setDynamicArguments:true,setPipeline:true,setImmutable:true,setGraphical:false}){const k=gpu.createKernel(f);if(opts.setDynamicOutput)k.setDynamicOutput(true);if(opts.output)k.setOutput(opts.output);if(opts.setDynamicArguments)k.setDynamicArguments(true);if(opts.setPipeline)k.setPipeline(true);if(opts.setImmutable)k.setImmutable(true);if(opts.setGraphical)k.setGraphical(true);return k}function makeCanvasKrnl(gpu,f,opts={output:[300,300],setDynamicArguments:true,setDynamicOutput:true,setPipeline:false,setImmutable:true,setGraphical:true},divId){const k=makeKrnl(gpu,f,opts);const canvas=k.canvas;if(typeof divId==="string")document.getElementById(toAppend).appendChild(canvas);else if(divId)toAppend.appendChild(canvas);else document.body.appendChild(canvas);return k}var gpuUtils=class{constructor(gpu=new GPUjs){this.gpu=gpu;this.kernels=new Map;this.kernel;this.PI=3.141592653589793;this.SQRT1_2=.7071067811865476;this.addFunctions();this.imgkernels={edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],sobelLeft:[1,0,-1,2,0,-2,1,0,-1],sobelRight:[-1,0,1,-2,0,2,-1,0,1],sobelTop:[1,2,1,0,0,0,-1,-2,-1],sobelBottom:[-1,2,1,0,0,0,1,2,1],identity:[0,0,0,0,1,0,0,0,0],gaussian3x3:[1,2,1,2,4,2,1,2,1],guassian7x7:[0,0,0,5,0,0,0,0,5,18,32,18,5,0,0,18,64,100,64,18,0,5,32,100,100,100,32,5,0,18,64,100,64,18,0,0,5,18,32,18,5,0,0,0,0,5,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0]}}addFunction(func=function f(){}){this.gpu.addFunction(func)}addKernel(name2="",krnl=function foo(){},opts){let found=this.kernels.get(name2);if(!found){this.kernels.set(name2,makeKrnl(this.gpu,krnl,opts));return true}else{console.error("Kernel already exists");return false}}addCanvasKernel(name2,f,opts,divId){let found=this.kernels.get(name2);if(!found){let krnl=makeCanvasKrnl(this.gpu,f,opts,divId);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}combineKernels(name2,fs=[],ckrnl=function foo(){}){let found=this.kernels.get(name2);if(!found){fs.forEach((f,i)=>{if(typeof f==="string"){let found2=this.kernels.get(f);if(found2)fs[i]=found2;else return false}else if(typeof f==="function"){if(this.kernels.get(f.name)){}else{this.addKernel(f.name,f)}}});let krnl=this.gpu.combineKernels(...fs,ckrnl);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}callKernel(name2="",args=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}result=krnl(...args);return result}callCanvasKernel(name2="",args=[],outputDims=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}else{if(outputDims.length===2)krnl.setOutput(outputDims);result=krnl(...args);return result}}hasKernel(name2=""){let found=this.kernels.get(name2);if(!found){return false}else return true}addFunctions(){addGpuFunctions.forEach(f=>this.gpu.addFunction(f));this.correlograms=makeKrnl(this.gpu,createGpuKernels.correlogramsKern);this.correlogramsPC=makeKrnl(this.gpu,createGpuKernels.correlogramsPCKern);this.dft=makeKrnl(this.gpu,createGpuKernels.dftKern);this.idft=makeKrnl(this.gpu,createGpuKernels.idftKern);this.dft_windowed=makeKrnl(this.gpu,createGpuKernels.dft_windowedKern);this.idft_windowed=makeKrnl(this.gpu,createGpuKernels.idft_windowedKern);this.fft=makeKrnl(this.gpu,createGpuKernels.fftKern);this.ifft=makeKrnl(this.gpu,createGpuKernels.ifftKern);this.fft_windowed=makeKrnl(this.gpu,createGpuKernels.fft_windowedKern);this.ifft_windowed=makeKrnl(this.gpu,createGpuKernels.ifft_windowedKern);this.listdft2D=makeKrnl(this.gpu,createGpuKernels.listdft2DKern);this.listdft1D=makeKrnl(this.gpu,createGpuKernels.listdft1DKern);this.listdft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listdft1D_windowedKern);this.listfft1D=makeKrnl(this.gpu,createGpuKernels.listfft1DKern);this.listfft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listfft1D_windowedKern);this.listidft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listidft1D_windowedKern);this.listifft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listifft1D_windowedKern);this.bulkArrayMul=makeKrnl(this.gpu,createGpuKernels.bulkArrayMulKern);let kernels=[{name:"correlograms",krnl:this.correlograms},{name:"correlogramsPC",krnl:this.correlogramsPC},{name:"dft",krnl:this.dft},{name:"idft",krnl:this.idft},{name:"dft_windowed",krnl:this.idft_windowed},{name:"fft",krnl:this.fft},{name:"ifft",krnl:this.ifft},{name:"fft_windowed",krnl:this.fft_windowed},{name:"ifft_windowed",krnl:this.ifft_windowed},{name:"listdft2D",krnl:this.listdft2D},{name:"listdft1D",krnl:this.listdft1D},{name:"listdft1D_windowed",krnl:this.listdft1D_windowed},{name:"listfft1D",krnl:this.listfft1D},{name:"listfft1D_windowed",krnl:this.listfft1D_windowed},{name:"listidft1D_windowed",krnl:this.listidft1D_windowed},{name:"listifft1D_windowed",krnl:this.listifft1D_windowed},{name:"bulkArrayMul",krnl:this.bulkArrayMul}];kernels.forEach(k=>{this.kernels.set(k.name,k)});const signalBandpass=(signal,sampleRate,freqStart,freqEnd,scalar)=>{var dft2=this.fft_windowed(signal,sampleRate,freqStart,freqEnd,scalar,0);var filtered_signal=this.ifft_windowed(dft2,sampleRate,freqStart,freqEnd,scalar);return filtered_signal};const signalBandpassMulti=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var dfts=this.listdft1D_windowed(signals,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var filtered_signals=this.listifft1D_windowed(dfts,sampleRate,freqStart,freqEnd,scalar);return filtered_signals};this.gpuCoherence=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var xcors=this.correlograms(signals);var dfts=this.listfft1D_windowed(xcors,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var products=this.bulkArrayMul(dfts,sampleRate,5,1);return products}}gpuXCors(arrays,precompute=false,texOut=false){var outputTex;if(precompute===true){var means=[];var ests=[];arrays.forEach((arr,i2)=>{means.push(arr.reduce((prev,curr)=>curr+=prev)/arr.length);ests.push(Math.sqrt(means[i2].reduce((sum,item)=>sum+=Math.pow(item-mean1,2))))});var meansbuf=[];var estsbuf=[];var buffer=[];for(var i=0;i{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D.setOutput([signalBufferProcessed.length]);this.listdft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D(signalBufferProcessed,nSamplesPerChannel,scalar);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D_windowed.setOutput([signalBufferProcessed.length]);this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}gpuFFT(signalBuffer,nSeconds,scalar=1,sampleRate,texOut=false){var nSamples=signalBuffer.length;var sampleRate=nSamples/nSeconds;this.fft.setOutput([signalBuffer.length]);this.fft.setLoopMaxIterations(nSamples);var outputTex=this.fft(signalBuffer,nSamples,scalar,sampleRate);var output=null;if(texOut===false){var freqDist=this.makeFrequencyDistribution(nSamples,sampleRate);var signalBufferProcessed=outputTex.toArray();outputTex.delete();return[freqDist,this.orderMagnitudes(signalBufferProcessed)]}else{var tex=outputTex;outputTex.delete();return tex}}MultiChannelFFT(signalBuffer,nSeconds,scalar=1,texOut=false){var signalBufferProcessed=[];signalBuffer.forEach(row=>{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D.setOutput([signalBufferProcessed.length]);this.listfft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D(signalBufferProcessed,nSamplesPerChannel,scalar,sampleRate);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D_windowed.setOutput([signalBufferProcessed.length]);this.listfft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}orderMagnitudes(unorderedMags){return[...unorderedMags.slice(Math.ceil(unorderedMags.length*.5),unorderedMags.length),...unorderedMags.slice(0,Math.ceil(unorderedMags.length*.5))]}makeFrequencyDistribution(FFTlength,sampleRate){var N=FFTlength;var df=sampleRate/N;var freqDist=[];for(var i=-N/2;i1){magList.forEach((row,k)=>{summedMags.push([]);var _max=1/Math.max(...row);for(var i2=0;i2{s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]};static genSineWave=(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1)=>{var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ti{return Math.sin(this.TWO_PI*frequency*ti+tOffset)*peakAmplitude};static mean=arr=>{var sum=arr.reduce((prev,curr)=>curr+=prev);return sum/arr.length};static median=data=>{const sortedData=data.slice().sort((a,b)=>a-b);const middle=Math.floor(sortedData.length/2);if(sortedData.length%2===0){return(sortedData[middle-1]+sortedData[middle])/2}else{return sortedData[middle]}};static mode=arr=>{return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()};static range=data=>{return Math.max(...data)-Math.min(...data)};static std=(arr,mean2=void 0)=>{let avg=mean2;if(!mean2)avg=this.mean(arr);let summed=0;for(let i=0;i{if(actual.length!==forecast.length)throw new Error("Input arrays of same length!");let i=actual.length;let d=new Array(actual.length);for(let j=0;j{let len=probabilities.length;let entropy=new Array(len);for(let i=0;i{let mean2=this.mean(arr);let std=this.std(arr,mean2);let z=new Array(arr.length);for(let i=0;ia+(b-mean2)**2,0)/arr.length}static coeffVariation=(arr,populationMean)=>{let mean2=this.mean(arr);let std=this.std(arr,mean2);return populationMean?std/populationMean:std/mean2};static coeffDetermination=(observed,expected)=>{const meanY=this.mean(observed);const ssTotal=observed.reduce((acc,y)=>acc+Math.pow(y-meanY,2),0);const ssResidual=observed.reduce((acc,y,i)=>acc+Math.pow(y-expected[i],2),0);return 1-ssResidual/ssTotal};static percentile=(arr,p)=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(p*(sortedData.length-1));return sortedData[index]};static interquartileRange=arr=>{const sortedData=arr.slice().sort((a,b)=>a-b);const index=Math.ceil(.25*(sortedData.length-1));const index2=Math.ceil(.75*(sortedData.length-1));const q1=sortedData[index];const q3=sortedData[index2];return q3-q1};static skewness=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumCubedDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,3),0);const skew=sumCubedDeviation/(n*Math.pow(stdDevValue,3));return skew};static kurtosis=arr=>{const n=arr.length;const meanValue=this.mean(arr);const stdDevValue=this.std(arr);const sumFourthDeviation=arr.reduce((acc,value2)=>acc+Math.pow(value2-meanValue,4),0);const kurt=sumFourthDeviation/(n*Math.pow(stdDevValue,4))-3;return kurt};static chiSquareTest=(observed,expected)=>{const chiSquared=observed.reduce((acc,obs,i)=>{const exp=expected[i];return acc+Math.pow(obs-exp,2)/exp},0);return chiSquared};static simpleLinearRegression=(xCoords,yCoords)=>{const n=xCoords.length;const sumX=xCoords.reduce((sum,x2)=>sum+x2,0);const sumY=yCoords.reduce((sum,y)=>sum+y,0);const sumXY=xCoords.reduce((sum,x2,i)=>sum+x2*yCoords[i],0);const sumX2=xCoords.reduce((sum,x2)=>sum+x2*x2,0);const slope=(n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);const intercept=(sumY-slope*sumX)/n;return{slope,intercept}};static pad=(arr,pad=1,padValue=0)=>{if(Array.isArray(arr[0]))return pad2D(arr,pad);if(pad>0){let pads=new Array(pad).fill(padValue);arr=[...pads,...arr,...pads]}return arr};static pad2D=(array,pad,padValue=0)=>{let pads=new Array(pad).fill(padValue);const paddedArray=array.map(row=>{return[...pads,...row,...pads]});const paddedRow=new Array(array[0].length+2*pad).fill(padValue);for(let i=0;i{const firstElem=array[0];const lastElem=array[array.length-1];const startPadding=new Array(padSize).fill(firstElem);const endPadding=new Array(padSize).fill(lastElem);return startPadding.concat(array,endPadding)};static edgePad2D=(matrix,padSize)=>{const topRows=Array(padSize).fill(matrix[0]);const bottomRows=Array(padSize).fill(matrix[matrix.length-1]);const paddedMatrix=topRows.concat(matrix,bottomRows);for(let i=0;i{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{const nVecs=vectors.length;return vectors[0].map((v,i)=>{for(let j=1;j{return vec.map((v,i)=>v-subvec[i])};static vecdiv=(numvec,denvec)=>{return numvec.map((v,i)=>v/denvec[i])};static vecscale=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecaddScalar=(vec,scalar)=>{return vec.map((v,i)=>v+scalar)};static vecmulScalar=(vec,scalar)=>{return vec.map((v,i)=>v*scalar)};static vecsubScalar=(vec,scalar)=>{return vec.map((v,i)=>v-scalar)};static vecdivScalar=(vec,scalar)=>{return vec.map((v,i)=>v/scalar)};static dot=(vec1,vec2)=>{var dot=0;for(var i=0;i{return[vec1[1]*vec2[2]-vec1[2]*vec2[1],vec1[2]*vec2[0]-vec1[0]*vec2[2],vec1[0]*vec2[1]-vec1[1]*vec2[0]]};static sphericalToCartesian=(r,theta,phi)=>{return{x:r*Math.sin(phi)*Math.cos(theta),y:r*Math.sin(phi)*Math.sin(theta),z:r*Math.cos(phi)}};static cartesianToSpherical=(x2,y,z)=>{var r=Math.sqrt(x2*x2+y*y+z*z);var theta=Math.atan2(y,x2);var phi=Math.acos(z/r);return{r,theta,phi}};static magnitude=vec=>{var sqrd=0;vec.forEach(c=>{sqrd+=c*c});return Math.sqrt(sqrd)};static distance=(point1,point2)=>{var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)};static midpoint=(point1=[1,2,3],point2=[3,4,5])=>{return point1.map((c,i)=>{return(c+point2[i])*.5})};static project=(vec1,vec2)=>{const dot=this.dot(vec1,vec2);const magSqrd=this.magnitude(vec2)**2;return this.vecmulScalar(vec2,dot/magSqrd)};static angleBetween=(vec1,vec2)=>{const dotProduct=this.dot(vec1,vec2);const magProduct=this.magnitude(vec1)*this.magnitude(vec2);return Math.acos(dotProduct/magProduct)};static normalize=vec=>{var norm=0;norm=1/this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn};static normalizeSeries=(arr=[],fromZero=true)=>{let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))};static quadraticFormula=(a,b,c)=>{let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]};static newtonsMethod1D=(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10)=>{let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){let y=x2;return y},range=[0,1],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[0,1],[0,1]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[0,1],[0,1],[0,1]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[0,1],stepx=.01)=>{let length=0;let y0=func(range[0]);for(let i=range[0]+stepx;i<=range[1];i+=stepx){let yi=func(i);length+=Math.sqrt(stepx**2+(yi-y0)**2);y0=yi}return length};static pathIntegral2D=(xFunc=t=>{let x2=Math.cos(t);return x2},yFunc=t=>{let y=Math.sin(t);return y},range=[[0,1],[0,1]],stept=.01)=>{let length=0;let x0=xFunc(range[0][0]);let y0=yFunc(range[1][0]);let tMaxX=range[0][1];let tMaxY=range[1][1];let tMax=Math.max(tMaxX,tMaxY);for(let t=0;t<=tMax;t+=stept){let xi=xFunc(Math.min(t,tMaxX));let yi=yFunc(Math.min(t,tMaxY));length+=Math.sqrt((xi-x0)**2+(yi-y0)**2);x0=xi;y0=yi}return length};static pathIntegral3D=(xFunc=(u,v)=>u,yFunc=(u,v)=>v,zFunc=(u,v)=>u+v,rangeU=[0,1],rangeV=[0,1],stepU=.01,stepV=.01)=>{let area=0;for(let u=rangeU[0];u{var vec=[];point1.forEach((c,i)=>{vec.push(point2[i]-c)});return vec};static getBufferedValueByCoordinates=(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0)=>{let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}};static forBufferedMat=(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y})=>{let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j})=>{let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result};static combinations=(choices=["a","b","c"],vecsize=3)=>{var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result};static generateCoordinateSpace=(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0)=>{for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result};static meshgrid=_Math2.generateCoordinateSpace;static calcVectorField=(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]})=>{return coordinates.map(vec=>formula(...vec))};static randomMatrix=(rows,cols)=>{return Array.from({length:rows},()=>Array.from({length:cols},()=>Math.random()))};static identityMatrix=size=>{return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>i===j?1:0))};static diagonalMatrix=values=>{return values.map((value2,index)=>{const row=Array(values.length).fill(0);row[index]=value2;return row})};static householderMatrix=v=>{const size=v.length;const vvT=v.map(rowVal=>v.map(colVal=>rowVal*colVal));const vTv=this.normalize(v)**2;return Array.from({length:size},(_,i)=>Array.from({length:size},(_2,j)=>(i===j?1:0)-2*vvT[i][j]/vTv))};static transpose=mat=>{return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))};static clone=mat=>{return mat.map(row=>{if(Array.isArray(row[0]))return this.clone(row);else return[...row]})};static getColumn(matrix,col){return matrix.map(row=>row[col])}static matmul=(A,B)=>{return A.map(row=>B[0].map((_,colIndex)=>row.reduce((sum,cell,rowIndex)=>sum+cell*B[rowIndex][colIndex],0)))};static matscale=(mat,scalar)=>{return mat.map(row=>row.map(cell=>cell*scalar))};static matadd=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell+B[rowIndex][colIndex]))};static matsub=(A,B)=>{return A.map((row,rowIndex)=>row.map((cell,colIndex)=>cell-B[rowIndex][colIndex]))};static inverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows!==numCols){throw new Error("Matrix must be square to compute its inverse.")}const augmentedMatrix=matrix.map((row,rowIndex)=>{const identityRow=Array(numRows).fill(0);identityRow[rowIndex]=1;return row.concat(identityRow)});for(let pivotRow=0;pivotRowrow.slice(numCols))};static pseudoInverse=matrix=>{const numRows=matrix.length;const numCols=matrix[0].length;if(numRows>numCols){const ata=this.matmul(this.transpose(matrix),matrix);const ataInv=this.inverse(ata);return this.matmul(ataInv,this.transpose(matrix))}else{const aat=this.matmul(matrix,this.transpose(matrix));const aatInv=this.inverse(aat);return this.matmul(this.transpose(matrix),aatInv)}};static histogram=(arr=[],binSize=1,nBins=void 0)=>{let copy=[...arr];copy.sort(function(a,b){return a-b});let binStart=Math.min(...copy);if(typeof nBins==="number"){let binEnd=Math.max(...copy);binSize=Math.abs((binEnd-binStart)/(nBins-1))}let j=binStart;let binx=[];let biny=[];for(let i=0;ibinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]};static normalDistribution=(samples=[],normalize=true,cutoff=1e-4)=>{let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities};static expectedValue=(samples=[],probabilities=this.normalDistribution(samples))=>{return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])};static originMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])};static centralMoment=(samples=[],probabilities=this.normalDistribution(samples),order=1)=>{let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)};static linearDiscriminantAnalysis=(samples=[],classifier=[])=>{let mean2=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i{const padlen=deconstructionLowPass.length;let sg=this.edgePad(signal,padlen);let approxCoeffs=this.conv1D(sg,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let detailCoeffs=this.conv1D(sg,deconstructionHighPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0);let results=[detailCoeffs];for(let i=0;iidx%2===0));approxCoeffs=this.conv1D(approxCoeffs,deconstructionLowPass).slice(1+padlen,-padlen).filter((_,idx)=>idx%2===0)}return[approxCoeffs].concat(results.reverse())};static idwt=(approxCoeffs=[],detailCoeffs=[],reconstructionHighPass=[],reconstructionLowPass=[])=>{if(approxCoeffs.length!==detailCoeffs.length){approxCoeffs.pop()}const _ca=this.dyadicUpsample(approxCoeffs,true);const _cd=this.dyadicUpsample(detailCoeffs,true);const halfa=this.conv1D(_ca,reconstructionLowPass);const halfb=this.conv1D(_cd,reconstructionHighPass);const sig=halfa.map((val,idx)=>val+halfb[idx]);const padlen=reconstructionLowPass.length;const lo=padlen-1;const hi=sig.length-(padlen-2);return sig.slice(lo,hi)};static dwtMaxLevel=(dataLength,waveletLength)=>{return Math.floor(Math.log2(dataLength/(waveletLength-1)))};static minMaxScaler=data=>{const min=Math.min(...data);const max=Math.max(...data);return data.map(value2=>(value2-min)/(max-min))};static garroteThreshold=(data,value2)=>{return data.map(x2=>{if(Math.abs(x2)<=value2){return 0}else{return x2-value2*value2/x2}})};static conv1D=(s,kernel)=>{const revKernel=[...kernel].reverse();const padsize=kernel.length-1;const paddedS=new Array(padsize).fill(0).concat(s).concat(new Array(padsize).fill(0));const nSteps=paddedS.length-kernel.length+1;const result=new Array(nSteps).fill(0);const nKer=kernel.length;for(let i=0;i{const rows=matrix.length;const cols=matrix[0].length;const kRows=kernel.length;const kCols=kernel[0].length;const halfKRows=Math.floor(kRows/2);const halfKCols=Math.floor(kCols/2);const output=new Array(rows).fill(0).map(()=>new Array(cols).fill(0));for(let i=0;i=0&&xi=0&&yj{if(matrix.length===0||kernel.length===0)return[];function getShape(arr){const shape=[];while(Array.isArray(arr)){shape.push(arr.length);arr=arr[0]}return shape}function convolveRecurse(mat,ker,matrixShape2,kernelShape2,matIndices=[],kerIndices=[]){const depth=matIndices.length;if(depth===matrixShape2.length){let sum=0;for(let i=0;i=0&&matIndex{const mean12=this.mean(arr1);const mean2=this.mean(arr2);return arr1.map((v,i)=>(v-mean12)*(arr2[i]-mean2))};static cov1d=(arr1,arr2)=>{this.mean(this.covVec(arr1,arr2))};static cov2d=mat=>{var mattransposed=this.transpose(mat);var matproducts=[];var rowmeans=[];var colmeans=[];mat.forEach((row,idx)=>{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{return[[this.cov1d(x2,x2),this.cov1d(x2,y),this.cov1d(x2,z)],[this.cov1d(y,x2),this.cov1d(y,y),this.cov1d(y,z)],[this.cov1d(z,x2),this.cov1d(z,y),this.cov1d(z,z)]]};static covNd=(dimensionalData=[])=>{let covariance=[];dimensionalData.forEach((arr,i)=>{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})};static correlationCoeff=(arr1,arr2)=>{const cov=this.cov1d(arr1,arr2);const stdDev1=this.std(arr1);const stdDev2=this.std(arr2);return cov/(stdDev1*stdDev2)};static pearsonCorrelation=(arr1,arr2)=>{let sumX=0,sumY=0,sumXY=0,sumX2=0,sumY2=0;const n=arr1.length>arr2.length?arr2.length:arr1.length;for(let i=0;i{let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean2=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean2*mean2-det);let eig1=mean2+sqrt;let eig2=mean2-sqrt;return[eig1,eig2]};static eigenvectors2x2=(mat=[[1,2],[3,4]],eigens=[1,2])=>{let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]};static fastpca2d=(xarr,yarr)=>{let covMat=this.cov2d(xarr,yarr);let eigs=this.eigens2x2(covMat);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(covMat,eigs);return[eigs,evs]};static centerData=data=>{const mean2=data.reduce((sum,val)=>sum+val,0)/data.length;return data.map(v=>v-mean2)};static crosscorrelation=(signalA,signalB,posOnly=false)=>{const N=signalA.length;const M=signalB.length;const result=[];const normFactor=1/Math.sqrt(signalA.reduce((acc,val)=>acc+val*val,0)*signalB.reduce((acc,val)=>acc+val*val,0));if(posOnly){result.length=signalA.length;for(let lag=0;lag=0&&m{const lags=[];const timeResolution=samplingRate?1/samplingRate:0;const center=centered?correlogram.length/2:null;const len=correlogram.length-1;for(let i=1;icorrelogram[i-1]&&correlogram[i]>correlogram[i+1]){let lag={offset:centered?i-center:i,value:correlogram[i]};if(timeResolution)lag.offset*=timeResolution;lags.push(lag)}}if(getMax)return lags.reduce((maxObj,currentObj)=>{return currentObj.value>maxObj.value?currentObj:maxObj},lags[0]);else return lags};static autocorrelation=arr1=>{var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean12=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(delaybuf[delay+i]-mean12));correlations[delay]=r*_arr1estsqrd}return correlations};static autocorrelation2d=mat2d2=>{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{let result=[];for(let y=0;y{var correlograms=[];dat.forEach((row1,i)=>{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms};static dft=(sineWave=[],sampleRate=250,frequencyResolution=.25)=>{const N=sineWave.length;const NyquistLimit=Math.floor(sampleRate/2);const totalFreqs=Math.floor(NyquistLimit/frequencyResolution);const Npadded=Math.ceil(sampleRate/frequencyResolution);const TWOPI=2*3.141592653589793;const real=new Array(Npadded).fill(0);const imag=new Array(Npadded).fill(0);const amplitudes=new Array(Npadded);const zerosToAdd=Npadded-N;if(zerosToAdd<0){throw new Error("Desired resolution is not achievable with current sample size.")}const paddedSineWave=zerosToAdd?[...sineWave,...Array(zerosToAdd).fill(0)]:sineWave;let orderedFrequencies;if(totalFreqs%2===0){orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>i*frequencyResolution)]}else{orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}for(let k=0;k-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs).fill(0).map((x2,i)=>(i+1)*frequencyResolution)]}else{orderedMagnitudes=[...amplitudes.slice(totalFreqs,2*totalFreqs),...amplitudes.slice(0,totalFreqs+1)];orderedFrequencies=[...new Array(totalFreqs).fill(0).map((x2,i)=>-NyquistLimit+i*frequencyResolution),...new Array(totalFreqs+1).fill(0).map((x2,i)=>i*frequencyResolution)]}return{real,imag,freqs:orderedFrequencies,amplitudes:orderedMagnitudes}};static eulerTransform=(dataSeries=[],timeTransform=(j,dataSeries2,real,imag,magnitudes)=>{return dataSeries2[j]},stepTransform=(k,j,length,real,imag,magnitudes)=>{return 2*Math.PI*k*j/length},kN=dataSeries.length)=>{var real=[];var imag=[];var magnitudes=[];for(var k=0;k{var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr};static sum=(arr=[])=>{if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}};static reduceArrByFactor=(arr,factor=2)=>{let x2=arr.filter((element,index)=>{return index%factor===0});return x2};static makeArr=(startValue,stopValue,nSteps)=>{var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;i{if(array?.length===0)return array;let max=Math.max(...array);let min=Math.min(...array);let _lines=1/stackedLines;let scalar;if(centerZero){let absmax=Math.max(Math.abs(min),Math.abs(max));scalar=_lines/absmax;return array.map(y=>y*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}};static absmax=array=>{return Math.max(Math.abs(Math.min(...array)),Math.max(...array))};static downsample=(array,fitCount,scalar=1)=>{if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j{var linearInterpolate=function(before2,after2,atPoint2){return(before2+(after2-before2)*atPoint2)*scalar};var newData=new Array;var springFactor=(array.length-1)/(fitCount-1);newData[0]=array[0];for(var i=1;i{const start=even?1:0;const out=new Array(a.length*2).fill(0);for(let i=0;i{if(array.length===fitCount)return array;if(array.length>fitCount){return this.downsample(array,fitCount,scalar)}else{return this.upsample(array,fitCount,scalar)}};static lerp=(v0,v1,t)=>{return(1-t)*v0+t*v1};static linspace=(start,end,num,floor=false)=>{const arr=new Array(num);const step=(end-start)/(num-1);for(let i=0;i{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0};static isCriticalPoint=(arr,critical="peak")=>{let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0};static peakDetect=(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold};static column=(mat,x2)=>{let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;i{let v_new=[];for(let i=0;i{let sum=0;for(let i=0;i{let len=Math.sqrt(this.matmul(this.transpose(eigenvector),eigenvector));let U=this.matscale(eigenvector,1/len);let delta=this.matscale(this.matmul(U,this.transpose(U)),eigenvalue);let M_new=this.matsub(mat,delta);return M_new};static eigenvalue_of_vector=(mat,eigenvector)=>{ev=this.matmul(this.matmul(this.transpose(eigenvector),mat),eigenvector);return ev};static power_iteration=(A,numIter=100)=>{let b=Array(A.length).fill(1);for(let i=0;i{let eigenvalues=[];let eigenvectors=[];for(let i=0;i{if(A[0].length>A.length){A=this.transpose(A)}const m=A.length;const n=A[0].length;const prec=Number.EPSILON;const tolerance=1e-64/prec;const itmax=50;const leftSingularVectors=this.clone(A);const offDiagonalValues=Array(n).fill(0);const singularValues=Array(n).fill(0);const rightSingularVectors=Array.from({length:n},()=>Array(n).fill(0));function pythag(a,b){if(a===0||b===0)return a+b;const absA=Math.abs(a),absB=Math.abs(b);if(absA>absB){const t=absB/absA;return absA*Math.sqrt(1+t*t)}else{const t=absA/absB;return absB*Math.sqrt(1+t*t)}}let scaleFactorF=0;let scaleFactorG=0;let scaleFactorH=0;let maxMagnitude=0;let intermediateY=0;let intermediateZ=0;let sumValue=0;let cosineTheta=0;let limitIndex=0;for(let i=0;i=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i]=scaleFactorF-scaleFactorG;for(let j=limitIndex;j=0)scaleFactorG=-scaleFactorG;scaleFactorH=scaleFactorF*scaleFactorG-sumValue;leftSingularVectors[i][i+1]=scaleFactorF-scaleFactorG;for(let j=limitIndex;jmaxMagnitude)maxMagnitude=intermediateY}for(let i=n-1;i>=0;i--){if(scaleFactorG!==0){scaleFactorH=scaleFactorG*leftSingularVectors[i][i+1];for(let j=limitIndex;j=0;i--){limitIndex=i+1;scaleFactorG=singularValues[i];for(let j=limitIndex;j=0;k--){for(let iteration=0;iteration=0;limitIndex--){if(Math.abs(offDiagonalValues[limitIndex])<=eps){testConvergence=true;break}if(Math.abs(singularValues[limitIndex-1])<=eps)break}if(!testConvergence){cosineTheta=0;sumValue=1;const l1=limitIndex-1;for(let i=limitIndex;i=itmax-1)throw new Error("No convergence.");maxMagnitude=singularValues[limitIndex];intermediateY=singularValues[k-1];scaleFactorG=offDiagonalValues[k-1];scaleFactorH=offDiagonalValues[k];scaleFactorF=((intermediateY-intermediateZ)*(intermediateY+intermediateZ)+(scaleFactorG-scaleFactorH)*(scaleFactorG+scaleFactorH))/(2*scaleFactorH*intermediateY);scaleFactorG=pythag(scaleFactorF,1);if(scaleFactorF<0)scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF-scaleFactorG)-scaleFactorH))/maxMagnitude;else scaleFactorF=((maxMagnitude-intermediateZ)*(maxMagnitude+intermediateZ)+scaleFactorH*(intermediateY/(scaleFactorF+scaleFactorG)-scaleFactorH))/maxMagnitude;cosineTheta=1;sumValue=1;for(let i=limitIndex+1;i=0;j--){if(singularValues[j]row.slice());for(let k=0;k0?-this.normalize(x2):this.normalize(x2);const u=this.vecsub(x2,e);const normU=this.normalize(u);const v=u.map(val=>val/normU);const Qk=this.householderMatrix(v);const QkFull=this.identityMatrix(numRows);for(let row=k;row{const numRowsOriginal=matrixA.length;const numColsOriginal=matrixA[0].length;if(!numComponents){numComponents=Math.min(numRowsOriginal,numColsOriginal)}let matrixACopy=[...matrixA.map(row=>[...row])];if(numRowsOriginal>numColsOriginal){matrixA=this.matmul(this.transpose(matrixA),matrixA)}else if(numRowsOriginalsum+row.reduce((rowSum,val)=>rowSum+val*val,0),0);previousMatrixQ=matrixQ;if(errorMath.sqrt(row[row.indexOf(Math.max(...row))]));let leftVectors,rightVectors;if(numRowsOriginalval*val)}else{rightVectors=this.transpose(matrixQ);leftVectors=this.matmul(this.matmul(matrixACopy,rightVectors),this.inverse(this.diagonalMatrix(singularValues)))}return{U:leftVectors,S:singularValues,V:rightVectors}};static pca=(mat,tolerance=1e-5)=>{let dims=mat.length;let t=new Array(dims);let p=new Array(dims);let mat_t=this.transpose(mat);t[0]=this.column(mat,0);let epsilon=1;let iter=0;while(espilon>tolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components};static circularBuffer=(arr,newEntries)=>{if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr};static reshape=(arr,shape)=>{const totalSize=shape.reduce((acc,val)=>acc*val,1);const flatArr=this.flatten(arr);if(flatArr.length!==totalSize){throw new Error("The given shape is incompatible with the array size.")}function buildArray(shape2,flatData){const dim=shape2[0];if(shape2.length===1){return flatData.splice(0,dim)}let result=[];for(let i=0;i{if(!Array.isArray(arr)){return[arr]}return arr.reduce((acc,val)=>acc.concat(flatten(val)),[])};static p300=(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256)=>{let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean2=this.mean(smoothed);let std=this.std(smoothed,mean2);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean2)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean2)/std})})}return candidates};static dec_lo=[-.07576571478927333,-.02963552764599851,.49761866763201545,.8037387518059161,.29785779560527736,-.09921954357684722,-.012603967262037833,.0322231006040427];static dec_hi=[-.0322231006040427,-.012603967262037833,.09921954357684722,.29785779560527736,-.8037387518059161,.49761866763201545,.02963552764599851,-.07576571478927333];static rec_lo=[.0322231006040427,-.012603967262037833,-.09921954357684722,.29785779560527736,.8037387518059161,.49761866763201545,-.02963552764599851,-.07576571478927333];static rec_hi=[-.07576571478927333,.02963552764599851,.49761866763201545,-.8037387518059161,.29785779560527736,.09921954357684722,-.012603967262037833,-.0322231006040427];static waveletFiltering=(signal=[],wavelets={dec_hi:this.dec_hi,dec_lo:this.dec_lo,rec_hi:this.rec_hi,rec_lo:this.rec_lo})=>{let maxlevel=this.dwtMaxLevel(signal.length,wavelets.dec_lo.length);let decomposed=this.decompose(signal,maxlevel,wavelets.dec_hi,wavelets.dec_lo);for(let i=2;i{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};function parseFunctionFromText(method=""){let getFunctionBody=methodString=>{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.substring(newFuncHead.indexOf("(")+1,newFuncHead.lastIndexOf(")"));newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(method)}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}}}return value2}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyWithFunctionsAndCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(typeof value2==="function"?value2.toString():value2,path.join("."))}}}return typeof value2==="function"?value2.toString():value2}return function stringifyWithFunctionsAndCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithFunctionsAndCircularRefs===void 0){JSON.stringifyWithFunctionsAndCircularRefs=stringifyWithFunctionsAndCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx++}}}}}function checkValues(key,value2){let val;if(value2!=null){if(typeof value2==="object"){let c=value2.constructor.name;if(key&&c==="Object"){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}if(c==="Array"){if(value2.length>20){val=value2.slice(value2.length-20)}else val=value2}else if(c.includes("Set")){val=Array.from(value2)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value2){if(value2[prop]==null){obj[prop]=value2[prop]}else if(Array.isArray(value2[prop])){if(value2[prop].length>20)obj[prop]=value2[prop].slice(value2[prop].length-20);else obj[prop]=value2[prop]}else if(value2[prop].constructor.name==="Object"){obj[prop]={};for(const p in value2[prop]){if(Array.isArray(value2[prop][p])){if(value2[prop][p].length>20)obj[prop][p]=value2[prop][p].slice(value2[prop][p].length-20);else obj[prop][p]=value2[prop][p]}else{if(value2[prop][p]!=null){let con=value2[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value2[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value2[prop][p]}}else{obj[prop][p]=value2[prop][p]}}}}else{let con=value2[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value2[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value2[prop]}}}val=obj}else{val=value2}}else{val=value2}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var GPUService=class extends Service{gpu=new gpuUtils;constructor(options){super(options);this.load(this)}addFunc=fn=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addFunction(fn)};addKernel=(name2,fn,options)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addKernel(name2,fn,options)};combineKernels=(name2,fs,ckrnl)=>{for(let i=0;i{this.gpu.callKernel(name2,args)};dft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.gpuDFT(signalBuffer,nSeconds,scalar)};multidft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT(signalBuffer,nSeconds,scalar)};multidftbandpass=(buffered,nSeconds,freqStart,freqEnd,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT_Bandpass(buffered,nSeconds,freqStart,freqEnd,scalar)};coherence=(buffered,nSeconds,freqStart,freqEnd)=>{const correlograms=Math2.correlograms(buffered);const buffer=[...buffered,...correlograms];var dfts;var scalar=1;dfts=this.gpu.MultiChannelDFT_Bandpass(buffer,nSeconds,freqStart,freqEnd,scalar);const cordfts=dfts[1].splice(buffered.length,buffer.length-buffered.length);const coherenceResults=[];const nChannels=buffered.length;var k=0;var l=0;cordfts.forEach((row,i)=>{if(l+k===nChannels){var temp=cordfts.splice(i,1);k++;cordfts.splice(k,0,...temp);l=0}l++});var autoFFTproducts=[];k=0;l=1;cordfts.forEach((dft2,i)=>{var newdft=new Array(dft2.length).fill(0);if(i{newdft[j]=amp});autoFFTproducts.push(newdft)}else{dft2.forEach((amp,j)=>{let denom=autoFFTproducts[k][j]*autoFFTproducts[k+l][j];if(denom!==0)newdft[j]=amp*amp/denom;else newdft[j]=0;if(newdft[j]>1){newdft[j]=1}});l++;if(l+k===nChannels){k++;l=1}coherenceResults.push(newdft)}});return[dfts[0],dfts[1],coherenceResults]}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var dft={sps:250,nSec:1,freqStart:0,freqEnd:125,watch:["0","1","2","3"],blocking:false,__operator:function(arraybuffer){let results=globalThis.gpu.multidftbandpass(arraybuffer,this.nSec,this.freqStart,this.freqEnd,1);let dft2={};this.watch.forEach((tag,i)=>{dft2[tag]=results[1][i]});return{frequencies:results[0],dft:dft2}}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var coherence={sps:250,nSec:1,freqStart:0,freqEnd:125,tags:["0","1","2","3"],coherenceTags:[],__onconnected:function(node){node.tags.forEach((tag,i)=>{if(i!==node.tags.length-1){for(let j=i+1;j{dft2[tag]=results[1][i]});let coherence2={};this.coherenceTags.forEach((tag,i)=>{coherence2[tag]=results[2][i]});return{timestamp:ts,frequencies:results[0],dft:dft2,coherence:coherence2}}};var gpualgorithms={dft,coherence};export{GPUService,gpualgorithms}; -/*! Bundled license information: - -gpujsutils/dist/index.esm.js: - (** - * gpu.js - * http://gpu.rocks/ - * - * GPU Accelerated JavaScript - * - * @version 2.11.0 - * @date Tue Jan 05 2021 15:55:59 GMT-0500 (Eastern Standard Time) - * - * @license MIT - * The MIT License - * - * Copyright (c) 2021 gpu.js Team - *) -*/ + }`;const name2="math-random-uniformly-distributed";const functionMatch=`Math.random()`;const functionReplace=`nrand(vTexCoord)`;const functionReturnType="Number";const onBeforeRun=kernel=>{kernel.setUniform1f("randomSeed1",Math.random());kernel.setUniform1f("randomSeed2",Math.random())};const plugin={name:name2,onBeforeRun,functionMatch,functionReplace,functionReturnType,source};module3.exports=plugin},{}],113:[function(require2,module3,exports3){class Texture{constructor(settings){const{texture,size,dimensions,output,context,type="NumberTexture",kernel,internalFormat,textureFormat}=settings;if(!output)throw new Error('settings property "output" required.');if(!context)throw new Error('settings property "context" required.');if(!texture)throw new Error('settings property "texture" required.');if(!kernel)throw new Error('settings property "kernel" required.');this.texture=texture;if(texture._refs){texture._refs++}else{texture._refs=1}this.size=size;this.dimensions=dimensions;this.output=output;this.context=context;this.kernel=kernel;this.type=type;this._deleted=false;this.internalFormat=internalFormat;this.textureFormat=textureFormat}toArray(){throw new Error(`Not implemented on ${this.constructor.name}`)}clone(){throw new Error(`Not implemented on ${this.constructor.name}`)}delete(){throw new Error(`Not implemented on ${this.constructor.name}`)}clear(){throw new Error(`Not implemented on ${this.constructor.name}`)}}module3.exports={Texture}},{}],114:[function(require2,module3,exports3){const acorn=require2("acorn");const{Input}=require2("./input");const{Texture}=require2("./texture");const FUNCTION_NAME=/function ([^(]*)/;const STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;const ARGUMENT_NAMES=/([^\s,]+)/g;const utils={systemEndianness(){return _systemEndianness},getSystemEndianness(){const b=new ArrayBuffer(4);const a=new Uint32Array(b);const c=new Uint8Array(b);a[0]=3735928559;if(c[0]===239)return"LE";if(c[0]===222)return"BE";throw new Error("unknown endianness")},isFunction(funcObj){return typeof funcObj==="function"},isFunctionString(fn){if(typeof fn==="string"){return fn.slice(0,"function".length).toLowerCase()==="function"}return false},getFunctionNameFromString(funcStr){const result=FUNCTION_NAME.exec(funcStr);if(!result||result.length===0)return null;return result[1].trim()},getFunctionBodyFromString(funcStr){return funcStr.substring(funcStr.indexOf("{")+1,funcStr.lastIndexOf("}"))},getArgumentNamesFromString(fn){const fnStr=fn.replace(STRIP_COMMENTS,"");let result=fnStr.slice(fnStr.indexOf("(")+1,fnStr.indexOf(")")).match(ARGUMENT_NAMES);if(result===null){result=[]}return result},clone(obj){if(obj===null||typeof obj!=="object"||obj.hasOwnProperty("isActiveClone"))return obj;const temp=obj.constructor();for(let key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)){obj.isActiveClone=null;temp[key]=utils.clone(obj[key]);delete obj.isActiveClone}}return temp},isArray(array){return!isNaN(array.length)},getVariableType(value2,strictIntegers){if(utils.isArray(value2)){if(value2.length>0&&value2[0].nodeName==="IMG"){return"HTMLImageArray"}return"Array"}switch(value2.constructor){case Boolean:return"Boolean";case Number:if(strictIntegers&&Number.isInteger(value2)){return"Integer"}return"Float";case Texture:return value2.type;case Input:return"Input"}switch(value2.nodeName){case"IMG":return"HTMLImage";case"CANVAS":return"HTMLImage";case"VIDEO":return"HTMLVideo"}if(value2.hasOwnProperty("type")){return value2.type}return"Unknown"},getKernelTextureSize(settings,dimensions){let[w,h,d]=dimensions;let texelCount=(w||1)*(h||1)*(d||1);if(settings.optimizeFloatMemory&&settings.precision==="single"){w=texelCount=Math.ceil(texelCount/4)}if(h>1&&w*h===texelCount){return new Int32Array([w,h])}return utils.closestSquareDimensions(texelCount)},closestSquareDimensions(length){const sqrt=Math.sqrt(length);let high=Math.ceil(sqrt);let low=Math.floor(sqrt);while(high*low0){return lines.join(";\n")+";\n"}else{return"\n"}},warnDeprecated(type,oldName,newName){if(newName){console.warn(`You are using a deprecated ${type} "${oldName}". It has been replaced with "${newName}". Fixing, but please upgrade as it will soon be removed.`)}else{console.warn(`You are using a deprecated ${type} "${oldName}". It has been removed. Fixing, but please upgrade as it will soon be removed.`)}},flipPixels:(pixels,width,height)=>{const halfHeight=height/2|0;const bytesPerRow=width*4;const temp=new Uint8ClampedArray(width*4);const result=pixels.slice(0);for(let y=0;y{return array.subarray(0,width)},erect2DPackedFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{return array.subarray(0,width)},erectMemoryOptimized2DFloat:(array,width,height)=>{const yResults=new Array(height);for(let y=0;y{const zResults=new Array(depth);for(let z=0;z{const xResults=new Float32Array(width);let i=0;for(let x2=0;x2{const yResults=new Array(height);let i=0;for(let y=0;y{const zResults=new Array(depth);let i=0;for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const yResults=new Array(height);const XResultsMax=width*4;for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(width);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const xResults=new Array(array);const xResultsMax=width*4;let i=0;for(let x2=0;x2{const xResultsMax=width*4;const yResults=new Array(height);for(let y=0;y{const xResultsMax=width*4;const zResults=new Array(depth);for(let z=0;z{const{findDependency,thisLookup,doNotDefine}=settings;let flattened=settings.flattened;if(!flattened){flattened=settings.flattened={}}const ast=acorn.parse(source);const functionDependencies=[];let indent=0;function flatten(ast2){if(Array.isArray(ast2)){const results=[];for(let i=0;ir!==null);if(declarations.length<1){return""}else{return`${ast2.kind} ${declarations.join(",")}`}case"VariableDeclarator":if(ast2.init.object&&ast2.init.object.type==="ThisExpression"){const lookup=thisLookup(ast2.init.property.name,true);if(lookup){return`${ast2.id.name} = ${flatten(ast2.init)}`}else{return null}}else{return`${ast2.id.name} = ${flatten(ast2.init)}`}case"CallExpression":{if(ast2.callee.property.name==="subarray"){return`${flatten(ast2.callee.object)}.${flatten(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}if(ast2.callee.object.name==="gl"||ast2.callee.object.name==="context"){return`${flatten(ast2.callee.object)}.${flatten(ast2.callee.property)}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}if(ast2.callee.object.type==="ThisExpression"){functionDependencies.push(findDependency("this",ast2.callee.property.name));return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}else if(ast2.callee.object.name){const foundSource=findDependency(ast2.callee.object.name,ast2.callee.property.name);if(foundSource===null){return`${ast2.callee.object.name}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}else{functionDependencies.push(foundSource);return`${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}}else if(ast2.callee.object.type==="MemberExpression"){return`${flatten(ast2.callee.object)}.${ast2.callee.property.name}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`}else{throw new Error("unknown ast.callee")}}case"ReturnStatement":return`return ${flatten(ast2.argument)}`;case"BinaryExpression":return`(${flatten(ast2.left)}${ast2.operator}${flatten(ast2.right)})`;case"UnaryExpression":if(ast2.prefix){return`${ast2.operator} ${flatten(ast2.argument)}`}else{return`${flatten(ast2.argument)} ${ast2.operator}`}case"ExpressionStatement":return`${flatten(ast2.expression)}`;case"SequenceExpression":return`(${flatten(ast2.expressions)})`;case"ArrowFunctionExpression":return`(${ast2.params.map(flatten).join(", ")}) => ${flatten(ast2.body)}`;case"Literal":return ast2.raw;case"Identifier":return ast2.name;case"MemberExpression":if(ast2.object.type==="ThisExpression"){return thisLookup(ast2.property.name)}if(ast2.computed){return`${flatten(ast2.object)}[${flatten(ast2.property)}]`}return flatten(ast2.object)+"."+flatten(ast2.property);case"ThisExpression":return"this";case"NewExpression":return`new ${flatten(ast2.callee)}(${ast2.arguments.map(value2=>flatten(value2)).join(", ")})`;case"ForStatement":return`for (${flatten(ast2.init)};${flatten(ast2.test)};${flatten(ast2.update)}) ${flatten(ast2.body)}`;case"AssignmentExpression":return`${flatten(ast2.left)}${ast2.operator}${flatten(ast2.right)}`;case"UpdateExpression":return`${flatten(ast2.argument)}${ast2.operator}`;case"IfStatement":return`if (${flatten(ast2.test)}) ${flatten(ast2.consequent)}`;case"ThrowStatement":return`throw ${flatten(ast2.argument)}`;case"ObjectPattern":return ast2.properties.map(flatten).join(", ");case"ArrayPattern":return ast2.elements.map(flatten).join(", ");case"DebuggerStatement":return"debugger;";case"ConditionalExpression":return`${flatten(ast2.test)}?${flatten(ast2.consequent)}:${flatten(ast2.alternate)}`;case"Property":if(ast2.kind==="init"){return flatten(ast2.key)}}throw new Error(`unhandled ast.type of ${ast2.type}`)}const result=flatten(ast);if(functionDependencies.length>0){const flattenedFunctionDependencies=[];for(let i=0;i{if(ast.type!=="VariableDeclaration")throw new Error('Ast is not of type "VariableDeclaration"');const normalizedDeclarations=[];for(let declarationIndex=0;declarationIndex{const rKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.r*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const gKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.g*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const bKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.b*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const aKernel=gpu.createKernel(function(a){const pixel=a[this.thread.y][this.thread.x];return pixel.a*255},{output:[image.width,image.height],precision:"unsigned",argumentTypes:{a:"HTMLImage"}});const result=[rKernel(image),gKernel(image),bKernel(image),aKernel(image)];result.rKernel=rKernel;result.gKernel=gKernel;result.bKernel=bKernel;result.aKernel=aKernel;result.gpu=gpu;return result},splitRGBAToCanvases:(gpu,rgba,width,height)=>{const visualKernelR=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(pixel.r/255,0,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelR(rgba);const visualKernelG=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,pixel.g/255,0,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelG(rgba);const visualKernelB=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(0,0,pixel.b/255,255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelB(rgba);const visualKernelA=gpu.createKernel(function(v){const pixel=v[this.thread.y][this.thread.x];this.color(255,255,255,pixel.a/255)},{output:[width,height],graphical:true,argumentTypes:{v:"Array2D(4)"}});visualKernelA(rgba);return[visualKernelR.canvas,visualKernelG.canvas,visualKernelB.canvas,visualKernelA.canvas]},getMinifySafeName:fn=>{try{const ast=acorn.parse(`const value = ${fn.toString()}`);const{init}=ast.body[0].declarations[0];return init.body.name||init.body.body[0].argument.name}catch(e){throw new Error("Unrecognized function type. Please use `() => yourFunctionVariableHere` or function() { return yourFunctionVariableHere; }")}},sanitizeName:function(name2){if(dollarSign.test(name2)){name2=name2.replace(dollarSign,"S_S")}if(doubleUnderscore.test(name2)){name2=name2.replace(doubleUnderscore,"U_U")}else if(singleUnderscore.test(name2)){name2=name2.replace(singleUnderscore,"u_u")}return name2}};const dollarSign=/\$/;const doubleUnderscore=/__/;const singleUnderscore=/_/;const _systemEndianness=utils.getSystemEndianness();module3.exports={utils}},{"./input":110,"./texture":113,"acorn":1}]},{},[107])(107)})}});var import_gpu_browser_min=__toESM(require_gpu_browser_min());function add(a,b){return a+b}function sub(a,b){return a-b}function mul(a,b){return a*b}function div(a,b){return a/b}function cadd(a_real,a_imag,b_real,b_imag){return[a_real+b_real,a_imag+b_imag]}function csub(a_real,a_imag,b_real,b_imag){return[a_real-b_real,a_imag-b_imag]}function cmul(a_real,a_imag,b_real,b_imag){return[a_real*b_real-a_imag*b_imag,a_real*b_imag+a_imag*b_real]}function cexp(a_real,a_imag){const er=Math.exp(a_real);return[er*Math.cos(a_imag),er*Math.sin(a_imag)]}function mag(a,b){return Math.sqrt(a*a+b*b)}function conj(imag){return 0-imag}function lof(n){const sqrt_n=Math.sqrt(n);var factor=3;while(factor<=sqrt_n){if(n%factor===0)return factor;factor+=2}}function mean(arr,len){var mean2=0;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signal[j]*Math.cos(sharedi);imag=imag-signal[j]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function FFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=imag-signals[j+(len-1)*n]*Math.sin(sharedi);N+=1}return[real/N,imag/N]}function iDFT(fft,len,freq){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+fft[j]*Math.cos(sharedi);imag=fft[j]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function iFFTlist(signals,len,freq,n,sr){var real=0;var imag=0;var _len=1/len;var shared=6.28318530718*freq*_len;var skip=1;var N=0;var factor=sr*.25;if(freq<=factor){while(freq<=factor){factor=factor*.5;skip+=1}}for(var i=0;ilen){j=len}var sharedi=shared*j;real=real+signals[j+(len-1)*n]*Math.cos(sharedi);imag=signals[j+(len-1)*n]*Math.sin(sharedi)-imag;N+=1}return[real/N,imag/N]}function correlogramsKern(arrays,len){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=mean(arrays[k],len);var arr2mean=mean(arrays[k+1],len);var arr1Est=est(arrays[k],arr1mean,len);var arr2Est2=est(arrays[k+1],arr2mean,len);var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function correlogramsPCKern(arrays,len,means,estimators){var k=Math.floor(this.thread.x/len)*2;var delay=this.thread.x-Math.floor(this.thread.x/len)*len;var arr1mean=means[k];var arr2mean=means[k+1];var arr1Est=estimators[k];var arr2Est2=estimators[k+1];var y_x=xcor(arrays[k],arr1mean,arr1Est,arrays[k+1],arr2mean,arr2Est2,len,delay);return y_x}function dftKern(signal,len,scalar){var result=DFT(signal,len,this.thread.x);return mag(result[0],result[1])*scalar}function idftKern(amplitudes,len,scalar){var result=iDFT(amplitudes,len,this.thread.x);return mag(result[0],result[1])*scalar}function fftKern(signal,len,scalar,sampleRate){var result=FFT(signal,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function ifftKern(amplitudes,len,scalar,sampleRate){var result=iFFT(amplitudes,len,this.thread.x,sampleRate);return mag(result[0],result[1])*scalar}function listdft2DKern(signals,scalar){var len=this.output.x;var result=DFT(signals[this.thread.y],len,this.thread.x);return mag(result[0],result[1])*scalar}function listdft1DKern(signals,len,scalar){var result=[0,0];if(this.thread.x<=len){result=DFT(signals,len,this.thread.x)}else{var n=Math.floor(this.thread.x/len);result=DFTlist(signals,len,this.thread.x-n*len,n)}return mag(result[0],result[1])*scalar}function listfft1DKern(signals,len,scalar,sps){var result=[0,0];if(this.thread.x<=len){result=FFT(signals,len,this.thread.x,sps)}else{var n=Math.floor(this.thread.x/len);result=FFTlist(signals,len,this.thread.x-n*len,n,sps)}return mag(result[0],result[1])*scalar}function dft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=DFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function fft_windowedKern(signal,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=FFT(signal,sampleRate,freq);return mag(result[0],result[1])*scalar}function idft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iDFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function ifft_windowedKern(amplitudes,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];var freq=this.thread.x/sampleRate*(freqEnd-freqStart)+freqStart;result=iFFT(amplitudes,sampleRate,freq);return mag(result[0],result[1])*scalar}function listdft1D_windowedKern(signals,sampleRate,freqStart,freqEnd,scalar){var result=[0,0];if(this.thread.x=width){i++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+i+kernelRadius;const weights=kernel[kernelOffset];const pixel=img[this.thread.y+i][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}i++}this.color(r,g,b)}function multiImgConv2DKern(img,width,height,kernels,kernelLengths,nKernels){let r=0,g=0,b=0;for(var i=0;i=width){k++;continue}let j=-kernelRadius;while(j<=kernelRadius){if(this.thread.y+j<0||this.thread.y+j>=height){j++;continue}kernelOffset=(j+kernelRadius)*kSize+k+kernelRadius;const weights=kernels[i][kernelOffset];const pixel=img[this.thread.y+k][this.thread.x+j];r+=pixel.r*weights;g+=pixel.g*weights;b+=pixel.b*weights;j++}k++}}this.color(r,g,b)}function transpose2DKern(mat2){return mat2[this.thread.y][this.thread.x]}var createGpuKernels={correlogramsKern,correlogramsPCKern,dftKern,idftKern,fftKern,ifftKern,dft_windowedKern,idft_windowedKern,fft_windowedKern,ifft_windowedKern,listdft2DKern,listdft1DKern,listfft1DKern,listfft1D_windowedKern,listdft1D_windowedKern,listidft1D_windowedKern,listifft1D_windowedKern,bulkArrayMulKern,multiImgConv2DKern,ImgConv2DKern,transpose2DKern};var addGpuFunctions=[add,sub,mul,div,cadd,csub,cmul,cexp,mag,conj,lof,mean,est,mse,rms,xcor,softmax,DFT,DFTlist,iDFT,iDFTlist,FFT,iFFT,iFFTlist];function makeKrnl(gpu,f,opts={setDynamicOutput:true,setDynamicArguments:true,setPipeline:true,setImmutable:true,setGraphical:false}){const k=gpu.createKernel(f);if(opts.setDynamicOutput)k.setDynamicOutput(true);if(opts.output)k.setOutput(opts.output);if(opts.setDynamicArguments)k.setDynamicArguments(true);if(opts.setPipeline)k.setPipeline(true);if(opts.setImmutable)k.setImmutable(true);if(opts.setGraphical)k.setGraphical(true);return k}function makeCanvasKrnl(gpu,f,opts={output:[300,300],setDynamicArguments:true,setDynamicOutput:true,setPipeline:false,setImmutable:true,setGraphical:true},divId){const k=makeKrnl(gpu,f,opts);const canvas=k.canvas;if(typeof divId==="string")document.getElementById(toAppend).appendChild(canvas);else if(divId)toAppend.appendChild(canvas);else document.body.appendChild(canvas);return k}var gpuUtils=class{constructor(gpu=new GPU){this.gpu=gpu;this.kernels=new Map;this.kernel;this.PI=3.141592653589793;this.SQRT1_2=.7071067811865476;this.addFunctions();this.imgkernels={edgeDetection:[-1,-1,-1,-1,8,-1,-1,-1,-1],boxBlur:[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],sobelLeft:[1,0,-1,2,0,-2,1,0,-1],sobelRight:[-1,0,1,-2,0,2,-1,0,1],sobelTop:[1,2,1,0,0,0,-1,-2,-1],sobelBottom:[-1,2,1,0,0,0,1,2,1],identity:[0,0,0,0,1,0,0,0,0],gaussian3x3:[1,2,1,2,4,2,1,2,1],guassian7x7:[0,0,0,5,0,0,0,0,5,18,32,18,5,0,0,18,64,100,64,18,0,5,32,100,100,100,32,5,0,18,64,100,64,18,0,0,5,18,32,18,5,0,0,0,0,5,0,0,0],emboss:[-2,-1,0,-1,1,1,0,1,2],sharpen:[0,-1,0,-1,5,-1,0,-1,0]}}addFunction(func=function f(){}){this.gpu.addFunction(func)}addKernel(name2="",krnl=function foo(){},opts){let found=this.kernels.get(name2);if(!found){this.kernels.set(name2,makeKrnl(this.gpu,krnl,opts));return true}else{console.error("Kernel already exists");return false}}addCanvasKernel(name2,f,opts,divId){let found=this.kernels.get(name2);if(!found){let krnl=makeCanvasKrnl(this.gpu,f,opts,divId);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}combineKernels(name2,fs=[],ckrnl=function foo(){}){let found=this.kernels.get(name2);if(!found){fs.forEach((f,i)=>{if(typeof f==="string"){let found2=this.kernels.get(f);if(found2)fs[i]=found2;else return false}else if(typeof f==="function"){if(this.kernels.get(f.name)){}else{this.addKernel(f.name,f)}}});let krnl=this.gpu.combineKernels(...fs,ckrnl);this.kernels.set(name2,krnl);return krnl}else{console.error("Kernel already exists");return false}}callKernel(name2="",args=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}result=krnl(...args);return result}callCanvasKernel(name2="",args=[],outputDims=[]){let result;let krnl=this.kernels.get(name2);if(!krnl){console.error("Kernel not found");return false}else{if(outputDims.length===2)krnl.setOutput(outputDims);result=krnl(...args);return result}}hasKernel(name2=""){let found=this.kernels.get(name2);if(!found){return false}else return true}addFunctions(){addGpuFunctions.forEach(f=>this.gpu.addFunction(f));this.correlograms=makeKrnl(this.gpu,createGpuKernels.correlogramsKern);this.correlogramsPC=makeKrnl(this.gpu,createGpuKernels.correlogramsPCKern);this.dft=makeKrnl(this.gpu,createGpuKernels.dftKern);this.idft=makeKrnl(this.gpu,createGpuKernels.idftKern);this.dft_windowed=makeKrnl(this.gpu,createGpuKernels.dft_windowedKern);this.idft_windowed=makeKrnl(this.gpu,createGpuKernels.idft_windowedKern);this.fft=makeKrnl(this.gpu,createGpuKernels.fftKern);this.ifft=makeKrnl(this.gpu,createGpuKernels.ifftKern);this.fft_windowed=makeKrnl(this.gpu,createGpuKernels.fft_windowedKern);this.ifft_windowed=makeKrnl(this.gpu,createGpuKernels.ifft_windowedKern);this.listdft2D=makeKrnl(this.gpu,createGpuKernels.listdft2DKern);this.listdft1D=makeKrnl(this.gpu,createGpuKernels.listdft1DKern);this.listdft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listdft1D_windowedKern);this.listfft1D=makeKrnl(this.gpu,createGpuKernels.listfft1DKern);this.listfft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listfft1D_windowedKern);this.listidft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listidft1D_windowedKern);this.listifft1D_windowed=makeKrnl(this.gpu,createGpuKernels.listifft1D_windowedKern);this.bulkArrayMul=makeKrnl(this.gpu,createGpuKernels.bulkArrayMulKern);let kernels=[{name:"correlograms",krnl:this.correlograms},{name:"correlogramsPC",krnl:this.correlogramsPC},{name:"dft",krnl:this.dft},{name:"idft",krnl:this.idft},{name:"dft_windowed",krnl:this.idft_windowed},{name:"fft",krnl:this.fft},{name:"ifft",krnl:this.ifft},{name:"fft_windowed",krnl:this.fft_windowed},{name:"ifft_windowed",krnl:this.ifft_windowed},{name:"listdft2D",krnl:this.listdft2D},{name:"listdft1D",krnl:this.listdft1D},{name:"listdft1D_windowed",krnl:this.listdft1D_windowed},{name:"listfft1D",krnl:this.listfft1D},{name:"listfft1D_windowed",krnl:this.listfft1D_windowed},{name:"listidft1D_windowed",krnl:this.listidft1D_windowed},{name:"listifft1D_windowed",krnl:this.listifft1D_windowed},{name:"bulkArrayMul",krnl:this.bulkArrayMul}];kernels.forEach(k=>{this.kernels.set(k.name,k)});const signalBandpass=(signal,sampleRate,freqStart,freqEnd,scalar)=>{var dft2=this.fft_windowed(signal,sampleRate,freqStart,freqEnd,scalar,0);var filtered_signal=this.ifft_windowed(dft2,sampleRate,freqStart,freqEnd,scalar);return filtered_signal};const signalBandpassMulti=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var dfts=this.listdft1D_windowed(signals,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var filtered_signals=this.listifft1D_windowed(dfts,sampleRate,freqStart,freqEnd,scalar);return filtered_signals};this.gpuCoherence=(signals,sampleRate,freqStart,freqEnd,scalar)=>{var xcors=this.correlograms(signals);var dfts=this.listfft1D_windowed(xcors,sampleRate,freqStart,freqEnd,scalar,new Array(Math.ceil(signals/sampleRate)).fill(0));var products=this.bulkArrayMul(dfts,sampleRate,5,1);return products}}gpuXCors(arrays,precompute=false,texOut=false){var outputTex;if(precompute===true){var means=[];var ests=[];arrays.forEach((arr,i2)=>{means.push(arr.reduce((prev,curr)=>curr+=prev)/arr.length);ests.push(Math.sqrt(means[i2].reduce((sum,item)=>sum+=Math.pow(item-mean1,2))))});var meansbuf=[];var estsbuf=[];var buffer=[];for(var i=0;i{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D.setOutput([signalBufferProcessed.length]);this.listdft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D(signalBufferProcessed,nSamplesPerChannel,scalar);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listdft1D_windowed.setOutput([signalBufferProcessed.length]);this.listdft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listdft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}gpuFFT(signalBuffer,nSeconds,scalar=1,sampleRate,texOut=false){var nSamples=signalBuffer.length;var sampleRate=nSamples/nSeconds;this.fft.setOutput([signalBuffer.length]);this.fft.setLoopMaxIterations(nSamples);var outputTex=this.fft(signalBuffer,nSamples,scalar,sampleRate);var output=null;if(texOut===false){var freqDist=this.makeFrequencyDistribution(nSamples,sampleRate);var signalBufferProcessed=outputTex.toArray();outputTex.delete();return[freqDist,this.orderMagnitudes(signalBufferProcessed)]}else{var tex=outputTex;outputTex.delete();return tex}}MultiChannelFFT(signalBuffer,nSeconds,scalar=1,texOut=false){var signalBufferProcessed=[];signalBuffer.forEach(row=>{signalBufferProcessed.push(...row)});var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D.setOutput([signalBufferProcessed.length]);this.listfft1D.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D(signalBufferProcessed,nSamplesPerChannel,scalar,sampleRate);if(texOut===false){var orderedMagsList=[];var freqDist=this.makeFrequencyDistribution(nSamplesPerChannel,sampleRate);signalBufferProcessed=outputTex.toArray();for(var i=0;i{signalBufferProcessed.push(...row)});var freqEnd_nyquist=freqEnd*2;var nSamplesPerChannel=signalBuffer[0].length;var sampleRate=nSamplesPerChannel/nSeconds;this.listfft1D_windowed.setOutput([signalBufferProcessed.length]);this.listfft1D_windowed.setLoopMaxIterations(nSamplesPerChannel);var outputTex=this.listfft1D_windowed(signalBufferProcessed,sampleRate,freqStart,freqEnd_nyquist,scalar);if(texOut===true){return outputTex}signalBufferProcessed=outputTex.toArray();outputTex.delete();var freqDist=this.bandPassWindow(freqStart,freqEnd,sampleRate);return[freqDist,this.orderBPMagnitudes(signalBufferProcessed,nSeconds,sampleRate,nSamplesPerChannel)]}orderMagnitudes(unorderedMags){return[...unorderedMags.slice(Math.ceil(unorderedMags.length*.5),unorderedMags.length),...unorderedMags.slice(0,Math.ceil(unorderedMags.length*.5))]}makeFrequencyDistribution(FFTlength,sampleRate){var N=FFTlength;var df=sampleRate/N;var freqDist=[];for(var i=-N/2;i1){magList.forEach((row,k)=>{summedMags.push([]);var _max=1/Math.max(...row);for(var i2=0;i2key in obj?__defProp2(obj,key,{enumerable:true,configurable:true,writable:true,value:value2}):obj[key]=value2;var __publicField=(obj,key,value2)=>{__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value2);return value2};var _Math2=class{constructor(){}static genSineWave(freq=20,peakAmp=1,nSec=1,fs=512,freq2=0,peakAmp2=1){var sineWave=[];var t=[];var increment=1/fs;for(var ti=0;ticurr+=prev);return sum/arr.length}static mode(arr){return arr.sort((a,b)=>arr.filter(v=>v===a).length-arr.filter(v=>v===b).length).pop()}static std(arr,mean2=void 0){let avg=mean2;if(!mean2)avg=this.mean(arr);let summed=0;for(let i=0;ia+(b-mean2)**2,0)/arr.length}static dot(vec1,vec2){var dot=0;for(var i=0;i{sqrd+=c*c});return Math.sqrt(sqrd)}static distance(point1,point2){var dsqrd=0;point1.forEach((c,i)=>{dsqrd+=(point2[i]-c)*(point2[i]-c)});return Math.sqrt(dsqrd)}static midpoint(point1=[1,2,3],point2=[3,4,5]){return point1.map((c,i)=>{return(c+point2[i])*.5})}static normalize(vec){var norm=0;norm=this.magnitude(vec);var vecn=new Array(vec.length);vec.forEach((c,i)=>{vecn[i]=c*norm});return vecn}static normalizeSeries(arr=[],fromZero=true){let max=Math.max(...arr);let min=Math.min(...arr);if(fromZero==false){max=Math.max(max,Math.abs(min));min=0}if(max-min===0){min=0;if(max===0)max=1e-13}return arr.map(v=>(v-min)/(max-min))}static quadraticFormula(a,b,c){let bbmac4=Math.sqrt(b*b-4*a*c);if(!isNaN(bbmac4))return["complex","complex"];let _a2=1/(2*a);if(bbmac4===0)return[b*_a2];let nb=-b;return[(nb+bbmac4)*_a2,(nb-bbmac4)*_a2]}static newtonsMethod(foo=x2=>{return Math.pow(x2,5)+x2*x2-x2-.2},start=0,end=1,precision=.01,attempts=10){let roots=[];for(let i=0;iprecision){let step=-guess/slope2;let xn12=xn+step;guess=guess2;guess2=foo(xn12);let slope2=(guess2-guess)/(xn12-xn)}let idx;let f=roots.find((root,i2)=>{if(Math.abs(xn1-root){vec.push(point2[i]-c)});return vec}static getBufferedValueByCoordinates(vb=new Array(300).fill(1),dims=[10,10,2],coordinate=[1,2,1],cardinal=void 0){let getIdx=(foundIdx=0,dimIdx=0)=>{if(dimIdx===dims.length)return foundIdx;if(dimIdx==0)foundIdx+=coordinate[dimIdx];else if(dims[dimIdx]==0)dimsAt0++;else{let reMul=(val=coordinate[dimIdx],di=dimIdx-1)=>{val*=dims[di];di--;if(di==0)return val;else return reMul(val,di)};foundIdx+=reMul(coordinate[dimIdx]+1,dimIdx-1)}dimIdx++;return getIdx(foundIdx,dimIdx)};let found=getIdx();if(cardinal){if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb[found-lastnonzero+cardinal]}return vb[found-dims.length+cardinal]}else{if(coordinate[coordinate.length-1]===0){let lastnonzero=0;let idx=0;while(idx!==coordinate.length-1){if(coordinate[idx]!==0)lastnonzero=idx;idx++}return vb.slice(found-lastnonzero,found+1)}return vb.slice(found-dims.length,found+1)}}static forBufferedMat(vb=new Array(100).fill(1),dims=[10,10],asIndex=(v,i,x2,y)=>{return v+x2+y}){let coordinate=[];let idx=0;let recurseFor=(depth=0,nextDepth=depth+1)=>{let result=new Array(vb.length);for(let di=0;di{let result=new Array(vb.length);for(let di=0;di{console.log(`value:${v}, idx:${idx}, x:${i},y:${j}`);return v+i+j}){let coordinate=new Array(dimensions.length).fill(0);const iterateCoordinate=(coord,idx=0)=>{if(coord[idx]>=dimensions[idx]){coord[idx]=0;idx++;if(idx===dimensions.length)return;iterateCoordinate(coord,idx)}else coord[idx]++};let result=new Array(buffer.length);let i=0;if(typeof asIndex==="function"){while(i{result[i]=func(buffer[i],i,...coordinate);i++;iterateCoordinate(coordinate)})}}return result}static combinations(choices=["a","b","c"],vecsize=3){var result=[];if(vecsize<=0){result.push([])}else{_Math2.combinations(choices,vecsize-1).forEach(function(previousComb){choices.forEach(function(element){result.push([element].concat(previousComb))})})}return result}static generateCoordinateSpace(upperBounds=[10,10,10],lowerBounds=[-10,-10,-10],steps=[1,1,1],mutater=void 0){for(let i=0;iupperBounds[i]){let temp=upperBounds[i];upperBounds[i]=lowerBounds[i];lowerBounds[i]=temp}}let result=[];let copy=[...upperBounds];let lastindex=copy.length-1;result.push([...copy]);while(copy[0]>=lowerBounds[0]){let checkNextIndex=decrIdx2=>{if(copy[decrIdx2]<=lowerBounds[decrIdx2]){if(decrIdx2===0)return;copy[decrIdx2]=upperBounds[decrIdx2];decrIdx2--;if(decrIdx2<0)return;if(typeof steps[decrIdx2]=="function")copy[decrIdx2]-=steps[decrIdx2](copy[decrIdx2]);else copy[decrIdx2]-=steps[decrIdx2];checkNextIndex(decrIdx2)}};let decrIdx=lastindex;if(typeof steps[decrIdx]=="function")copy[decrIdx]-=steps[decrIdx](copy[decrIdx]);else copy[decrIdx]-=steps[decrIdx];result.push([...copy]);checkNextIndex(decrIdx);if(mutater)result[result.length-1]=mutater(result[result.length-1])}return result}static calcVectorField(coordinates=[[0,0],[0,1],[1,0],[1,1]],formula=(x2,y)=>{return[x2*10,y*10]}){return coordinates.map(vec=>formula(...vec))}static transpose(mat){return mat[0].map((_,colIndex)=>mat.map(row=>row[colIndex]))}static matmul(a,b){var aNumRows=a.length,aNumCols=a[0].length,bNumRows=b.length,bNumCols=b[0].length,m=new Array(aNumRows);for(var r=0;rbinStart+binidx){j++;binidx+=binSize;let binmin=binStart+binidx;let binmid=binmin+binidx*.5;binx.push(binmid);biny.push(0)}biny[biny.length-1]++}return[binx,biny]}static normalDistribution(samples=[],normalize=true,cutoff=1e-4){let m=this.mean(samples);let vari=this.variance(samples);let nSamples=samples.length;let probabilities=[];let denom=1/(this.TWO_PI*vari);let _variance=1/vari;let sum=0;for(let i=0;ix2*_sum)}return probabilities}static expectedValue(samples=[],probabilities=this.normalDistribution(samples)){return samples.reduce((sum,item,idx)=>sum+item*probabilities[idx])}static originMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){return samples.reduce((sum,item,idx)=>sum+Math.pow(item,order)*probabilities[idx])}static centralMoment(samples=[],probabilities=this.normalDistribution(samples),order=1){let m=this.mean(samples);return samples.reduce((sum,item,idx)=>sum+Math.pow(item-m,order)*probabilities[idx]/samples.length)}static linearDiscriminantAnalysis(samples=[],classifier=[]){let mean2=this.mean(samples);let meank=this.mean(classifier);let covariance=this.cov1d(samples,classifier);let probs=this.normalDistribution(samples);let dk=[];for(let i=0;i0){let pads=new Array(pad).fill(0);arr=[...pads,...arr,...pads]}let start=Math.floor(kern.length*.5);let end=arr.length-kern.length+start;for(let i=start;i0){let pads=new Array(pad).fill(0);mat_t=_Math2.transpose(mat);for(let i2=0;i2{rowmeans.push(this.mean(row))});mattransposed.forEach((col,idx)=>{colmeans.push(this.mean(col))});mat.forEach((row,idx)=>{matproducts.push([]);for(var col=0;col{covariance.push([]);dimensionalData.forEach((arr2,j)=>{covariance[i].push(this.cov1d(arr,arr2))})})}static eigens2x2(mat=[[1,2],[3,4]]){let det=mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0];let mean2=(mat[0][0]+mat[1][1])*.5;let sqrt=Math.sqrt(mean2*mean2-det);let eig1=mean2+sqrt;let eig2=mean2-sqrt;return[eig1,eig2]}static eigenvectors2x2(mat=[[1,2],[3,4]],eigens=[1,2]){let v1=[-mat[0][1],mat[0][0]-eigens[0]];if(v1[0]===0&&v1[1]===0){v1[0]=mat[1][1]-eigens[0];v1[1]=-mat[1][0]}let v2=[-mat[0][1],mat[0][0]-eigens[1]];if(v2[0]===0&&v2[1]===0){v2[0]=mat[1][1]-eigens[1];v2[1]=-mat[1][0]}return[v1,v2]}static fastpca2d(xarr,yarr){let cov1d=this.cov1d(xarr,yarr);let eigs=this.eigens2x2(cov1d);if(eigs[1]>eigs[0])eigs.reverse();let evs=this.eigenvectors2x2(cov1d,eigs);console.log(eigs,evs);return[eigs,evs]}static crosscorrelation(arr1,arr2){var arr2buf=[...arr2,...Array(arr2.length).fill(0)];var mean12=this.mean(arr1);var mean2=this.mean(arr2);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));var arr2Est2=arr2.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr2Est2=Math.sqrt(Math.abs(arr2Est2));let denom=arr1Est*arr2Est2;if(denom===0)denom=1e-26;var _arrEstsMul=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(arr2buf[delay+i]-mean2));correlations[delay]=r*_arrEstsMul}return correlations}static autocorrelation(arr1){var delaybuf=[...arr1,...Array(arr1.length).fill(0)];var mean12=this.mean(arr1);var arr1Est=arr1.reduce((sum,item)=>sum+=Math.pow(item-mean12,2));arr1Est=Math.sqrt(Math.abs(arr1Est));let denom=arr1Est*arr2Est;if(denom===0)denom=1e-26;var _arr1estsqrd=1/denom;var correlations=new Array(arr1.length).fill(0);for(var delay=0;delaysum+=(item-mean12)*(delaybuf[delay+i]-mean12));correlations[delay]=r*_arr1estsqrd}return correlations}static autocorrelation2dNormalized(mat2d2){let result=[];for(let y=0;y{dat.forEach((row2,j)=>{if(j>=i){correlograms.push(_Math2.crosscorrelation(row1,row2))}})});return correlograms}static dft(sineWave=[]){var TWOPI=2*3.141592653589793;var real=[];var imag=[];var mags=[];for(var k=0;k{return i-halflen});return{real,imag,freqs,mags}}static sma(arr=[],window2){var smaArr=[];for(var i=0;icurrent+=previous)/(i+1))}else{var arrslice=arr.slice(i-window2,i);smaArr.push(arrslice.reduce((previous,current)=>current+=previous)/window2)}}return smaArr}static sum(arr=[]){if(arr.length>0){var sum=arr.reduce((prev,curr)=>curr+=prev);return sum}else{return 0}}static reduceArrByFactor(arr,factor=2){let x2=arr.filter((element,index)=>{return index%factor===0});return x2}static makeArr(startValue,stopValue,nSteps){var arr=[];var step=(stopValue-startValue)/(nSteps-1);for(var i=0;iy*scalar+(_lines*(stackPosition+1)*2-1-_lines))}else{scalar=_lines/(max-min);return array.map(y=>2*((y-min)*scalar-1/(2*stackedLines))+(_lines*(stackPosition+1)*2-1-_lines))}}static absmax(array){return Math.max(Math.abs(Math.min(...array)),Math.max(...array))}static downsample(array,fitCount,scalar=1){if(array.length>fitCount){let output=new Array(fitCount);let incr=array.length/fitCount;let lastIdx=array.length-1;let last=0;let counter=0;for(let i=incr;ilastIdx)rounded=lastIdx;for(let j=last;j1){let pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}else if(critical==="valley"){if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}else{if(iMath.floor(ref.length*.5)&&val<=ref[Math.floor(ref.length*.5)]){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;i=ref[Math.floor(ref.length*.5)]){pass=false;break}else if(i>Math.floor(ref.length*.5)&&val>=ref[Math.floor(ref.length*.5)]){pass=false;break}}}return pass}else return void 0}static isCriticalPoint(arr,critical="peak"){let ref=[...arr];if(ref.length%2===0)ref.pop();if(arr.length>1){let pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}else if(critical==="valley"){if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}else{if(i=0){pass=false;break}else if(i>ref.length*.5&&val<0){pass=false;break}}}if(critical!=="peak"&&critical!=="valley"&&pass===false){pass=true;for(let i=0;iref.length*.5&&val>0){pass=false;break}}}return pass}else return void 0}static getPeakThreshold(arr,peakIndices,thresholdVar){let threshold;let filtered=arr.filter((o,i)=>{if(peakIndices.indexOf(i)>-1)return true});if(thresholdVar===0){threshold=this.mean(filtered)}else threshold=(thresholdVar+this.mean(filtered))*.5;return threshold}static column(mat,x2){let col=new Array(mat.length).fill(0).map(()=>new Array(1).fill(0));for(let i=0;inew Array(1).fill(Math.sqrt(rank)));let eigenvalue=this.eigenvalue_of_vector(mat,eigenvector);let epsilon=1;let iter=0;while(epsilon>tolerance&&itertolerance){iter++;p[0]=this.matmul(mat_t,t[0]);let tp=this.matmul(this.transpose(t[0]),t[0]);p[0]=this.matscale(p[0],1/tp);let p_length=Math.sqrt(this.matmul(this.transpose(p[0]),p[0]));p[0]=this.matscale(p[0],1/p_length);let t_new=this.matmul(mat,p[0]);let pp=this.matmul(this.transpose(p[0]),p[0]);t_new=this.matscale(t_new,1/pp);epsilon=this.squared_difference(t[0],t_new);t[0]=JSON.parse(JSON.stringify(t_new))}let components=this.matmul(this.transpose(t[0]),t[0]);return components}static circularBuffer(arr,newEntries){if(Array.isArray(newEntries)){if(newEntries.lengtharr.length){let len=arr.length;arr.splice(0,len,newEntries.slice(len-newEntries.length))}else{arr.splice(0,arr.length,...newEntries)}}else{arr.push(newEntries);arr.shift()}return arr}static HSLToRGB(h,s,l,scalar=255){s/=100;l/=100;let c=(1-Math.abs(2*l-1))*s,x2=c*(1-Math.abs(h/60%2-1)),m=l-c/2,r=0,g=0,b=0;if(0<=h&&h<60){r=c;g=x2;b=0}else if(60<=h&&h<120){r=x2;g=c;b=0}else if(120<=h&&h<180){r=0;g=c;b=x2}else if(180<=h&&h<240){r=0;g=x2;b=c}else if(240<=h&&h<300){r=x2;g=0;b=c}else if(300<=h&&h<360){r=c;g=0;b=x2}r=(r+m)*scalar;g=(g+m)*scalar;b=(b+m)*scalar;return[r,g,b]}static p300(event_timestamps=[],raw_signal=[],signal_timestamps=[],sps=256){let smoothingstep=Math.floor(sps/10);let smoothed=this.sma(raw_signal,smoothingstep);let peaks=this.peakDetect(smoothed,"peak",smoothingstep);let mean2=this.mean(smoothed);let std=this.std(smoothed,mean2);let p_idx=0;let candidates=[];if(peaks.length>0){event_timestamps.forEach((t,j)=>{while(signal_timestamps[peaks[p_idx]]1){let peakvals=[];tempcandidates.forEach(tc=>{peakvals.push(smoothed[peaks[tc]])});let max=Math.max(...peakvals);let maxi=tempcandidates[peakvals.indexOf(max)];candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[[peaks[maxi]]],signal_index:[peaks[maxi]],signal_amplitude:raw_signal[[peaks[maxi]]],zscore:(smoothed[peaks[maxi]]-mean2)/std})}else if(tempcandidates.length===1)candidates.push({event_timestamp:t,event_index:j,peak_timestamp:signal_timestamps[peaks[tempcandidates[0]]],signal_index:peaks[tempcandidates[0]],signal_amplitude:raw_signal[[peaks[tempcandidates[0]]]],zscore:(smoothed[peaks[tempcandidates[0]]]-mean2)/std})})}return candidates}};var Math2=_Math2;__publicField(Math2,"TWO_PI",Math.PI*2);__publicField(Math2,"C",299792458);__publicField(Math2,"G",66743e-15);__publicField(Math2,"h",662607015e-42);__publicField(Math2,"R",8314.32);__publicField(Math2,"Ra",287);__publicField(Math2,"H",69.3);__publicField(Math2,"kbar",1054571817e-43);__publicField(Math2,"kB",1380649e-29);__publicField(Math2,"ke",89875517923e-1);__publicField(Math2,"me",91093837015e-41);__publicField(Math2,"mp",167262192369e-38);__publicField(Math2,"mn",167492749804e-38);__publicField(Math2,"P0",101325);__publicField(Math2,"T0",288.15);__publicField(Math2,"p0",1.225);__publicField(Math2,"Na",60220978e16);__publicField(Math2,"y",1.405);__publicField(Math2,"M0",28.96643);__publicField(Math2,"g0",9.80665);__publicField(Math2,"Re",6378100);__publicField(Math2,"B",1458e-9);__publicField(Math2,"S",110.4);__publicField(Math2,"Sigma",365e-12);__publicField(Math2,"imgkernels",{edgeDetection:[[-1,-1,-1],[-1,8,-1],[-1,-1,-1]],boxBlur:[[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]],sobelLeft:[[1,0,-1],[2,0,-2],[1,0,-1]],sobelRight:[[-1,0,1],[-2,0,2],[-1,0,1]],sobelTop:[[1,2,1],[0,0,0],[-1,-2,-1]],sobelBottom:[[-1,2,1],[0,0,0],[1,2,1]],identity:[[0,0,0],[0,1,0],[0,0,0]],gaussian3x3:[[1,2,1],[2,4,2],[1,2,1]],guassian7x7:[[0,0,0,5,0,0,0],[0,5,18,32,18,5,0],[0,18,64,100,64,18,0],[5,32,100,100,100,32,5],[0,18,64,100,64,18,0],[0,5,18,32,18,5,0],[0,0,0,5,0,0,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]]});__publicField(Math2,"integral",(func=x2=>{let y=x2;return y},range=[],stepx=.01)=>{let area=0;for(let i=range[0];i{let z=x2+y;return z},range=[[],[]],stepx=.01,stepy=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let w=x2+y+z;return w},range=[[],[],[]],stepx=.01,stepy=stepx,stepz=stepx)=>{let volume=0;for(let i=range[0][0]+stepx;i{let y=x2;return y},range=[],stepx=.01)=>{let length=0;let y0=void 0;let yi=void 0;for(let i=range[0];i{let result=[];for(let y=0;y{function lerp(v02,v12,t){return(1-t)*v02+t*v12}function interpolerp(v02,v12,fit2,floor2=true){if(fit2<=2)return[v02,v12];let a=1/fit2;let result=new Array(fit2);result[0]=v02;for(let i=1;i<=fit2;i++){result[i]=lerp(v02,v12,a*i);if(floor2)result[i]=Math.floor(result[i])}return result}});__publicField(Math2,"peakDetect",(smoothedArray,type="peak",window2=49)=>{let mid=Math.floor(window2*.5);let peaks=[];for(let i=0;i{return methodString.replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i,"$2$3$4")};let getFunctionHead=methodString=>{let startindex=methodString.indexOf("=>")+1;if(startindex<=0){startindex=methodString.indexOf("){")}if(startindex<=0){startindex=methodString.indexOf(") {")}return methodString.slice(0,methodString.indexOf("{",startindex)+1)};let newFuncHead=getFunctionHead(method);let newFuncBody=getFunctionBody(method);let newFunc;if(newFuncHead.includes("function")){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody)}else{if(newFuncHead.substring(0,6)===newFuncBody.substring(0,6)){let varName=newFuncHead.split("(")[1].split(")")[0];newFunc=new Function(varName,newFuncBody.substring(newFuncBody.indexOf("{")+1,newFuncBody.length-1))}else{try{newFunc=(0,eval)(newFuncHead+newFuncBody+"}")}catch{}}}return newFunc}var stringifyWithCircularRefs=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx--}}}}function checkCircular(key,value2){if(value2!=null){if(typeof value2==="object"){if(key){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}}}return value2}return function stringifyWithCircularRefs2(obj,space){try{parents.push(obj);return JSON.stringify(obj,checkCircular,space)}finally{clear()}}}();if(JSON.stringifyWithCircularRefs===void 0){JSON.stringifyWithCircularRefs=stringifyWithCircularRefs}var stringifyFast=function(){const refs=new Map;const parents=[];const path=["this"];function clear(){refs.clear();parents.length=0;path.length=1}function updateParents(key,value2){var idx=parents.length-1;if(parents[idx]){var prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2||idx===0){path.push(key);parents.push(value2.pushed)}else{while(idx-->=0){prev=parents[idx];if(typeof prev==="object"){if(prev[key]===value2){idx+=2;parents.length=idx;path.length=idx;--idx;parents[idx]=value2;path[idx]=key;break}}idx++}}}}}function checkValues(key,value2){let val;if(value2!=null){if(typeof value2==="object"){let c=value2.constructor.name;if(key&&c==="Object"){updateParents(key,value2)}let other=refs.get(value2);if(other){return"[Circular Reference]"+other}else{refs.set(value2,path.join("."))}if(c==="Array"){if(value2.length>20){val=value2.slice(value2.length-20)}else val=value2}else if(c.includes("Set")){val=Array.from(value2)}else if(c!=="Object"&&c!=="Number"&&c!=="String"&&c!=="Boolean"){val="instanceof_"+c}else if(c==="Object"){let obj={};for(const prop in value2){if(value2[prop]==null){obj[prop]=value2[prop]}else if(Array.isArray(value2[prop])){if(value2[prop].length>20)obj[prop]=value2[prop].slice(value2[prop].length-20);else obj[prop]=value2[prop]}else if(value2[prop].constructor.name==="Object"){obj[prop]={};for(const p in value2[prop]){if(Array.isArray(value2[prop][p])){if(value2[prop][p].length>20)obj[prop][p]=value2[prop][p].slice(value2[prop][p].length-20);else obj[prop][p]=value2[prop][p]}else{if(value2[prop][p]!=null){let con=value2[prop][p].constructor.name;if(con.includes("Set")){obj[prop][p]=Array.from(value2[prop][p])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop][p]="instanceof_"+con}else{obj[prop][p]=value2[prop][p]}}else{obj[prop][p]=value2[prop][p]}}}}else{let con=value2[prop].constructor.name;if(con.includes("Set")){obj[prop]=Array.from(value2[prop])}else if(con!=="Number"&&con!=="String"&&con!=="Boolean"){obj[prop]="instanceof_"+con}else{obj[prop]=value2[prop]}}}val=obj}else{val=value2}}else{val=value2}}return val}return function stringifyFast2(obj,space){parents.push(obj);let res=JSON.stringify(obj,checkValues,space);clear();return res}}();if(JSON.stringifyFast===void 0){JSON.stringifyFast=stringifyFast}var GPUService=class extends Service{constructor(options){super(options);this.gpu=new gpuUtils;this.addFunc=fn=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addFunction(fn)};this.addKernel=(name2,fn,options)=>{if(typeof fn==="string")fn=parseFunctionFromText(fn);if(typeof fn==="function")this.gpu.addKernel(name2,fn,options)};this.callKernel=(name2,...args)=>{this.gpu.callKernel(name2,...args)};this.dft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.gpuDFT(signalBuffer,nSeconds,scalar)};this.multidft=(signalBuffer,nSeconds,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT(signalBuffer,nSeconds,scalar)};this.multidftbandpass=(buffered,nSeconds,freqStart,freqEnd,scalar)=>{if(scalar==void 0)scalar=1;return this.gpu.MultiChannelDFT_Bandpass(buffered,nSeconds,freqStart,freqEnd,scalar)};this.coherence=(buffered,nSeconds,freqStart,freqEnd)=>{const correlograms=Math2.correlograms(buffered);const buffer=[...buffered,...correlograms];var dfts;var scalar=1;dfts=this.gpu.MultiChannelDFT_Bandpass(buffer,nSeconds,freqStart,freqEnd,scalar);const cordfts=dfts[1].splice(buffered.length,buffer.length-buffered.length);const coherenceResults=[];const nChannels=buffered.length;var k=0;var l=0;cordfts.forEach((row,i)=>{if(l+k===nChannels){var temp=cordfts.splice(i,1);k++;cordfts.splice(k,0,...temp);l=0}l++});var autoFFTproducts=[];k=0;l=1;cordfts.forEach((dft2,i)=>{var newdft=new Array(dft2.length).fill(0);if(i{newdft[j]=amp});autoFFTproducts.push(newdft)}else{dft2.forEach((amp,j)=>{let denom=autoFFTproducts[k][j]*autoFFTproducts[k+l][j];if(denom!==0)newdft[j]=amp*amp/denom;else newdft[j]=0;if(newdft[j]>1){newdft[j]=1}});l++;if(l+k===nChannels){k++;l=1}coherenceResults.push(newdft)}});return[dfts[0],dfts[1],coherenceResults]};this.setTree(this)}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var dft={structs:{sps:250,nSec:1,freqStart:0,freqEnd:125,watch:["0","1","2","3"],blocking:false},oncreate:ctx=>{},ondata:(ctx,arraybuffer)=>{let results=globalThis.gpu.multidftbandpass(arraybuffer,ctx.nSec,ctx.freqStart,ctx.freqEnd,1);let dft2={};ctx.watch.forEach((tag,i)=>{dft2[tag]=results[1][i]});return{frequencies:results[0],dft:dft2}}};if(!globalThis.gpu)globalThis.gpu=new GPUService;var coherence={structs:{sps:250,nSec:1,freqStart:0,freqEnd:125,tags:["0","1","2","3"],coherenceTags:[]},oncreate:ctx=>{ctx.tags.forEach((tag,i)=>{if(i!==ctx.tags.length-1){for(let j=i+1;j{let ts=Date.now();let results=globalThis.gpu.coherence(arraybuffer,ctx.nSec,ctx.freqStart,ctx.freqEnd);let dft2={};ctx.tags.forEach((tag,i)=>{dft2[tag]=results[1][i]});let coherence2={};ctx.coherenceTags.forEach((tag,i)=>{coherence2[tag]=results[2][i]});return{timestamp:ts,frequencies:results[0],dft:dft2,coherence:coherence2}}};var gpualgorithms={dft,coherence};})(); +/** + * gpu.js + * http://gpu.rocks/ + * + * GPU Accelerated JavaScript + * + * @version 2.11.0 + * @date Tue Jan 05 2021 15:55:59 GMT-0500 (Eastern Standard Time) + * + * @license MIT + * The MIT License + * + * Copyright (c) 2021 gpu.js Team + */ diff --git a/extras/dist/index.services.esm.js b/extras/dist/index.services.esm.js new file mode 100644 index 00000000..504395ca --- /dev/null +++ b/extras/dist/index.services.esm.js @@ -0,0 +1,48 @@ +var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var require_objectid=__commonJS({"node_modules/bson-objectid/objectid.js"(exports,module){var MACHINE_ID=Math.floor(Math.random()*16777215);var index=ObjectID2.index=parseInt(Math.random()*16777215,10);var pid=(typeof process==="undefined"||typeof process.pid!=="number"?Math.floor(Math.random()*1e5):process.pid)%65535;var BufferCtr=(()=>{try{return _Buffer}catch(_2){try{return Buffer}catch(_3){return null}}})();var isBuffer=function(obj){return!!(obj!=null&&obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj))};var hexTable=[];for(i=0;i<256;i++){hexTable[i]=(i<=15?"0":"")+i.toString(16)}var i;var checkForHexRegExp=new RegExp("^[0-9a-fA-F]{24}$");var decodeLookup=[];i=0;while(i<10)decodeLookup[48+i]=i++;while(i<16)decodeLookup[65-10+i]=decodeLookup[97-10+i]=i++;function ObjectID2(id){if(!(this instanceof ObjectID2))return new ObjectID2(id);if(id&&(id instanceof ObjectID2||id._bsontype==="ObjectID"))return id;this._bsontype="ObjectID";if(id==null||typeof id==="number"){this.id=this.generate(id);return}var valid=ObjectID2.isValid(id);if(!valid&&id!=null){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}else if(valid&&typeof id==="string"&&id.length===24){return ObjectID2.createFromHexString(id)}else if(id!=null&&id.length===12){this.id=id}else if(id!=null&&typeof id.toHexString==="function"){return id}else{throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}}module.exports=ObjectID2;ObjectID2.default=ObjectID2;ObjectID2.createFromTime=function(time){time=parseInt(time,10)%4294967295;return new ObjectID2(hex(8,time)+"0000000000000000")};ObjectID2.createFromHexString=function(hexString){if(typeof hexString==="undefined"||hexString!=null&&hexString.length!==24){throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters")}var data="";var i2=0;while(i2<24){data+=String.fromCharCode(decodeLookup[hexString.charCodeAt(i2++)]<<4|decodeLookup[hexString.charCodeAt(i2++)])}return new ObjectID2(data)};ObjectID2.isValid=function(id){if(id==null)return false;if(typeof id==="number"){return true}if(typeof id==="string"){return id.length===12||id.length===24&&checkForHexRegExp.test(id)}if(id instanceof ObjectID2){return true}if(isBuffer(id)){return ObjectID2.isValid(id.toString("hex"))}if(typeof id.toHexString==="function"){if(BufferCtr&&(id.id instanceof BufferCtr||typeof id.id==="string")){return id.id.length===12||id.id.length===24&&checkForHexRegExp.test(id.id)}}return false};ObjectID2.prototype={constructor:ObjectID2,toHexString:function(){if(!this.id||!this.id.length){throw new Error("invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is ["+JSON.stringify(this.id)+"]")}if(this.id.length===24){return this.id}if(isBuffer(this.id)){return this.id.toString("hex")}var hexString="";for(var i2=0;i2>24&255,time>>16&255,time>>8&255,time&255,MACHINE_ID>>16&255,MACHINE_ID>>8&255,MACHINE_ID&255,pid>>8&255,pid&255,inc>>16&255,inc>>8&255,inc&255)}};function next(){return index=(index+1)%16777215}function hex(length,n){n=n.toString(16);return n.length===length?n:"00000000".substring(n.length,length)+n}var inspect=Symbol&&Symbol.for&&Symbol.for("nodejs.util.inspect.custom")||"inspect";ObjectID2.prototype[inspect]=function(){return"ObjectID("+this+")"};ObjectID2.prototype.toJSON=ObjectID2.prototype.toHexString;ObjectID2.prototype.toString=ObjectID2.prototype.toHexString}});var DataStructures_exports={};__export(DataStructures_exports,{AuthorizationStruct:()=>AuthorizationStruct,ChatroomStruct:()=>ChatroomStruct,CoherenceMap:()=>CoherenceMap,CoherenceStruct:()=>CoherenceStruct,CommentStruct:()=>CommentStruct,Data:()=>Data,DataStruct:()=>DataStruct,DateStruct:()=>DateStruct,ECGStruct:()=>ECGStruct,EDAStruct:()=>EDAStruct,EEGCoordinates:()=>EEGCoordinates,EEGStruct:()=>EEGStruct,EMGStruct:()=>EMGStruct,EventStruct:()=>EventStruct,EyeTrackerStruct:()=>EyeTrackerStruct,FNIRSStruct:()=>FNIRSStruct,FrequencyBandsStruct:()=>FrequencyBandsStruct,GroupStruct:()=>GroupStruct,HRVStruct:()=>HRVStruct,IMUStruct:()=>IMUStruct,NotificationStruct:()=>NotificationStruct,PPGStruct:()=>PPGStruct,ProfileStruct:()=>ProfileStruct,ScheduleStruct:()=>ScheduleStruct,Struct:()=>Struct,eegCoordinates:()=>eegCoordinates,setCoordinate:()=>setCoordinate,structRegistry:()=>structRegistry});function Struct(structType="struct",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){function randomId3(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}let struct={_id:randomId3(structType+"defaultId"),structType,ownerId:parentUser?._id,timestamp:Date.now(),parent:{structType:parentStruct?.structType,_id:parentStruct?._id}};if(!struct.ownerId)delete struct.ownerId;if(!struct?.parent?._id)delete struct.parent;if(Object.keys(assignProps).length>0)Object.assign(struct,assignProps);return struct}var eegCoordinates={FP1:[-21.2,66.9,12.1],FPZ:[1.4,65.1,11.3],FP2:[24.3,66.3,12.5],AF7:[-41.7,52.8,11.3],AF3:[-32.7,48.4,32.8],AFZ:[1.8,54.8,37.9],AF4:[35.1,50.1,31.1],AF8:[43.9,52.7,9.3],F5:[-51.4,26.7,24.7],F3:[-39.7,25.3,44.7],F1:[-22.1,26.8,54.9],FZ:[0,26.8,60.6],F2:[23.6,28.2,55.6],F4:[41.9,27.5,43.9],F6:[52.9,28.7,25.2],F7:[-52.1,28.6,3.8],F8:[53.2,28.4,3.1],FC5:[-59.1,3,26.1],FC3:[-45.5,2.4,51.3],FC1:[-24.7,.3,66.4],FCZ:[1,1,72.8],FC2:[26.1,3.2,66],FC4:[47.5,4.6,49.7],FC6:[60.5,4.9,25.5],FT9:[-53.8,-2.1,-29.1],FT7:[-59.2,3.4,-2.1],FT8:[60.2,4.7,-2.8],FT10:[55,-3.6,-31],T7:[-65.8,-17.8,-2.9],T5:[-61.5,-65.3,1.1],T3:[-70.2,-21.3,-10.7],T4:[71.9,-25.2,-8.2],T6:[59.3,-67.6,3.8],T8:[67.4,-18.5,-3.4],C5:[-63.6,-18.9,25.8],C3:[-49.1,-20.7,53.2],C1:[-25.1,-22.5,70.1],CZ:[.8,-21.9,77.4],C2:[26.7,-20.9,69.5],C4:[50.3,-18.8,53],C6:[65.2,-18,26.4],CP5:[-61.8,-46.2,22.5],CP3:[-46.9,-47.7,49.7],CP1:[-24,-49.1,66.1],CPZ:[.7,-47.9,72.6],CP2:[25.8,-47.1,66],CP4:[49.5,-45.5,50.7],CP6:[62.9,-44.6,24.4],TP9:[-73.6,-46.7,-4],TP7:[-63.6,-44.7,-4],TP8:[64.6,-45.4,-3.7],TP10:[74.6,-47.4,-3.7],P9:[-50.8,-51.3,-37.7],P7:[-55.9,-64.8,0],P5:[-52.7,-67.1,19.9],P3:[-41.4,-67.8,42.4],P1:[-21.6,-71.3,52.6],PZ:[.7,-69.3,56.9],P2:[24.4,-69.9,53.5],P4:[44.2,-65.8,42.7],P6:[54.4,-65.3,20.2],P8:[56.4,-64.4,.1],P10:[51,-53.9,-36.5],PO7:[-44,-81.7,1.6],PO3:[-33.3,-84.3,26.5],POZ:[0,-87.9,33.5],PO4:[35.2,-82.6,26.1],PO8:[43.3,-82,.7],O1:[-25.8,-93.3,7.7],OZ:[.3,-97.1,8.7],O2:[25,-95.2,6.2]};function setCoordinate(channelDict,assignTo={}){if(!eegCoordinates[channelDict.tag]&&channelDict.position){eegCoordinates[channelDict.tag]=[channelDict.position.x,channelDict.position.y,channelDict.position.z]}if(eegCoordinates[channelDict.tag]){let props={channel:"",position:{x:eegCoordinates[channelDict.tag][0],y:eegCoordinates[channelDict.tag][1],z:eegCoordinates[channelDict.tag][2]}};return Object.assign(assignTo,props)}else return Object.assign(assignTo,channelDict)}function EEGCoordinates(channelDicts=[],genCoherenceMap=true){let structs=[];for(let channelDict of channelDicts){let struct=EEGStruct(channelDict);structs.push(struct)}if(genCoherenceMap){structs.push(...CoherenceMap({channelDicts}))}return structs}function FrequencyBandsStruct(additionalBands=[],assignTo={}){let bands={scp:[],delta:[],theta:[],alpha1:[],alpha2:[],beta:[],lowgamma:[],highgamma:[]};additionalBands.forEach(band=>bands[band]=[]);return Object.assign(assignTo,bands)}function EEGStruct(tag="",assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag,position:{x:0,y:0,z:0},count:0,times:[],raw:[],filtered:[],fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("eeg",props,parentUser,parentStruct);if(tag)setCoordinate(props,struct);return Object.assign(struct,assignProps)}function CoherenceStruct(coords={0:EEGStruct("FP1"),1:EEGStruct("FP2")},assignProps={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){let bands=FrequencyBandsStruct();let props={tag:coords[0]?.tag+"::"+coords[1]?.tag,x0:coords[0]?.position?.x,y0:coords[0]?.position?.y,z0:coords[0]?.position?.z,x1:coords[1]?.position?.x,y1:coords[1]?.position?.y,z1:coords[1]?.position?.z,fftCount:0,fftTimes:[],ffts:[],slices:JSON.parse(JSON.stringify(bands)),means:JSON.parse(JSON.stringify(bands)),startTime:Date.now()};let struct=Struct("coherence",props,parentUser,parentStruct);return Object.assign(struct,assignProps)}function CoherenceMap(opts={channelDicts:[{ch:0,tag:"FP1",analyze:false},{ch:1,tag:"FP2",analyze:false}],taggedOnly:true},_2={},parentUser={_id:""},parentStruct={structType:"struct",_id:""}){var cmap=[];var l=1,k=0;for(var i=0;i{};Object.assign(this.data,props);this.dataSorts=new Map;this.watches={};this.setSort("event",dataObj=>{if(!this.data.events[dataObj.timestamp])this.data.events[dataObj.timestamp]=[dataObj];else this.data.events[dataObj.timestamp].push(dataObj);if(dataObj.event==="sleep"){if(!this.data.sleep[dataObj.timestamp])this.data.sleep[dataObj.timestamp]=[dataObj];else this.data.sleep[dataObj.timestamp].push(dataObj)}return dataObj});this.setSort(["notes","note","link"],dataObj=>{if(!this.data.notes[dataObj.timestamp])this.data.notes[dataObj.timestamp]=[dataObj];else this.data.notes[dataObj.timestamp].push(dataObj);if(!this.data.byTime[dataObj.timestamp])this.data.byTime[dataObj.timestamp]=[dataObj];else this.data.byTime[dataObj.timestamp].push(dataObj);return dataObj});this.id=this.randomId("dataTablet")}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections.get(type);if(!collection){collection=new Map;this.collections.set(type,collection)}collection.set(s._id,s);this.onCollectionSet(type,collection)};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId="";let key="";let value="";if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){this.collections.forEach(c=>{if((key==="_id"||key==="id")&&value){let found=c.get(value);if(found)result.push(found)}else{c.forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections.get(collection);if(!c)return result;if(!key&&!ownerId){c.forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return c.get(value);else{c.forEach((struct,_2)=>{if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}runSort(key,dataObj={},newdata=[],tablet=this){let result;let sort=this.getSort(key);if(sort)result=sort(dataObj,newdata,tablet);else return false;return result}setSort(key,response=(data,newdata=[],tablet=this)=>{}){if(Array.isArray(key))key.forEach(k=>{this.dataSorts.set(k,response)});else this.dataSorts.set(key,response)}getSort(key){return this.dataSorts.get(key)}checkWatches(sorted={}){for(const prop in this.watches){let triggered=this.watches[prop].ondata(sorted,this.watches[prop].accum,this.watches[prop].ownerId);if(triggered){this.watches[prop].ontrigger(this.watches[prop].accum);this.watches[prop].triggered=false}}}setWatch(name,ownerId,ondata=(sorted,accum,ownerId2)=>{if(sorted.ownerId===ownerId2)accum.data[sorted._id]=sorted;if(Object.keys(accum.data).length>10){return true}else return false},ontrigger=accum=>{console.log(accum);let alert=Struct("alert",{alert:true,data:accum},{_id:accum[Object.keys(accum)[0]].ownerId});accum={}}){this.watches[name]={accum:{},ownerId,ondata,ontrigger}}getWatch(name){return this.watches[name]}async sortStructsIntoTable(datastructs=[]){let ascending=function(a,b2){if(a.timestamp&&b2.timestamp)return a.timestamp-b2.timestamp};datastructs.sort(ascending);let newdata=[];for(let i=0;i{if(typeof dat==="object"&&!Array.isArray(dat)){let typ=dat.dataType;dat.ownerId=struct.ownerId;if(!dat.timestamp)dat.timestamp=timestamp;if(typ){let sorted=this.runSort(typ,dat,newdata,this);if(!sorted){if(!this.data[typ])this.data[typ]={};dat.timestamp=timestamp;if(!this.data[typ][timestamp])this.data[typ][timestamp]=[dat];else this.data[typ][timestamp].push(dat);if(!this.data.byTime[timestamp])this.data.byTime[timestamp]=[dat];else this.data.byTime[timestamp].push(dat);this.checkWatches(dat);this.onUpdate(timestamp,dat);newdata.push(dat)}else{if(sorted.constructor?.name!=="Promise"){this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}}})}else{let sorted=this.runSort(struct.structType,struct,newdata,this);if(!sorted){let typ=struct.structType;if(!this.data[typ])this.data[typ]={};if(!this.data[typ][timestamp])this.data[typ][timestamp]=[struct];else this.data[typ][timestamp].push(struct);this.checkWatches(struct);this.onUpdate(timestamp,struct);newdata.push(struct)}else{this.checkWatches(sorted);this.onUpdate(timestamp,sorted);newdata.push(sorted)}}}for(const prop in this.data){this.data[prop]=this.sortObjectByPropName(this.data[prop])}this.onSorted(newdata)}onUpdate(_2,__,___=this.data){}onSorted(_2=[]){}getDataByTimestamp(timestamp,ownerId){let result=this.data.byTime[timestamp];if(ownerId&&result)result=result.filter(o=>{if(!ownerId)return true;else if(ownerId===o.ownerId)return true;else return false});return result}getDataByTimeRange(begin,end,type,ownerId){let result={};if(type){for(const key in this.data[type]){let t=parseInt(key);if(t>begin&&tbegin&&t{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}return result}getDataByType(type,timestamp,ownerId){if(!this.data[type])return void 0;let result={...this.data[type]};if(timestamp)result=[...result[timestamp]];if(ownerId&&result){for(const key in result){let popidx=[];result[key]=[...result[key]];result[key].forEach((o,i)=>{if(o.ownerId!==ownerId){popidx.push(i)}});popidx.reverse().forEach(idx=>{result[key].splice(idx,1)});if(result[key].length===0)delete result[key]}}if(type==="sleep"){result=this.filterSleepResults(result)}return result}filterSleepResults(unfiltered={}){let events=[];for(const key in unfiltered){unfiltered[key]=[...unfiltered[key]];events.push(...unfiltered[key].filter(o=>{if(o.structType==="event")return true;else return false}))}events.forEach(ev2=>{let foundidx;for(const key in unfiltered){unfiltered[key].forEach((o,i)=>{if(o.structType==="fitbitsleep"&&ev2.startTime&&ev2.endTime){if(Math.abs(o.startTime-ev2.startTime)<1e3*12*3600&&Math.abs(o.endTime-ev2.endTime)<1e3*12*3600&&ev2.endTime-ev2.startTime>1e3*2*3600){foundidx=i;return true}else return false}else return false});if(foundidx)unfiltered[key].splice(foundidx,1)}});let result=unfiltered;return result}sortObjectByPropName(object){const ordered=Object.keys(object).sort().reduce((obj,key)=>{obj[key]=object[key];return obj},{});return ordered}checkRollover(collection,limit=this.rolloverLimit){if(!collection)return false;let c=this.collections.get(collection);if(!c)return false;c.forEach(struct=>{for(const prop in struct){if(Array.isArray(struct[prop])){if(struct[prop].length>limit){struct[prop].slice(struct[prop].length-limit);if(prop==="ffts"){struct.fftCount=struct[prop].length}else if(prop==="times"){struct.count=struct[prop].length}}}else if(typeof struct[prop]==="object"){this.checkRollover(struct[prop])}}});return true}};var EventHandler=class{constructor(data){this.pushToState={};this.data={};this.triggers={};this.setState=updateObj=>{Object.assign(this.data,updateObj);for(const prop of Object.getOwnPropertyNames(updateObj)){if(this.triggers[prop])this.triggers[prop].forEach(obj=>obj.onchange(this.data[prop]))}return this.data};this.setValue=(key,value)=>{this.data[key]=value;if(this.triggers[key])this.triggers[key].forEach(obj=>obj.onchange(this.data[key]))};this.subscribeTrigger=(key,onchange)=>{if(key){if(!this.triggers[key]){this.triggers[key]=[]}let l=this.triggers[key].length;this.triggers[key].push({sub:l,onchange});return this.triggers[key].length-1}else return void 0};this.unsubscribeTrigger=(key,sub)=>{let triggers=this.triggers[key];if(triggers){if(!sub)delete this.triggers[key];else{let sub2=void 0;let obj=triggers.find((o,i)=>{if(o.sub===sub2){sub2=i;return true}});if(obj)triggers.splice(sub2,1);if(this.onRemoved)this.onRemoved(obj);return true}}};this.subscribeTriggerOnce=(key,onchange)=>{let sub;let changed=value=>{onchange(value);this.unsubscribeTrigger(key,sub)};sub=this.subscribeTrigger(key,changed)};this.getTrigger=(key,sub)=>{for(const s in this.triggers[key]){if(this.triggers[key][s].sub===sub)return this.triggers[key][s]}};if(typeof data==="object")this.data=data}};var state=new EventHandler;var GraphNode=class{constructor(properties,parent2,graph){this.__node={tag:`node${Math.floor(Math.random()*1e15)}`,unique:`${Math.random()}`,state};this.__subscribe=(callback,key,subInput,bound,target)=>{const subscribeToFunction=(k,setTarget=(callback2,target2)=>callback2,triggerCallback=callback)=>{let sub=this.__node.state.subscribeTrigger(k,triggerCallback);let trigger=this.__node.state.getTrigger(k,sub);trigger.source=this.__node.tag;if(key)trigger.key=key;trigger.target=setTarget(callback);if(bound)trigger.bound=bound;return sub};const subscribeToGraph=callback2=>{let fn=this.__node.graph.get(callback2);if(!fn&&callback2.includes(".")){let n=this.__node.graph.get(callback2.substring(0,callback2.lastIndexOf(".")));let key2=callback2.substring(callback2.lastIndexOf(".")+1);if(n&&typeof n[key2]==="function")callback2=(...args)=>{return n[key2](...args)}}};if(key){if(!this.__node.localState){this.__addLocalState(this)}if(typeof callback==="string"){if(typeof this[callback]==="function")callback=this[callback];else if(this.__node.graph)subscribeToGraph(callback)}let sub;let k=subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}else{if(typeof callback==="string"){if(this.__node.graph)callback=this.__node.graph.get(callback);else callback=this.__node.graph.nodes.get(callback)}let sub;let k=subInput?this.__node.unique+"input":this.__node.unique;if(typeof callback==="function")sub=subscribeToFunction(k);else if(callback?.__node)sub=subscribeToFunction(k,(callback2,target2)=>target2?target2:callback2.__node.unique,state2=>{if(callback.__operator)callback.__operator(state2)});return sub}};this.__unsubscribe=(sub,key,subInput)=>{if(key){return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"."+key+"input":this.__node.unique+"."+key,sub)}else return this.__node.state.unsubscribeTrigger(subInput?this.__node.unique+"input":this.__node.unique,sub)};this.__setOperator=fn=>{fn=fn.bind(this);this.__operator=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(this.__node.state.triggers[this.__node.unique]){if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result)}return result};if(!this.__subscribedToParent){if(this.__parent instanceof GraphNode&&this.__parent.__operator){let sub=this.__parent.__subscribe(this);let ondelete=()=>{this.__parent?.__unsubscribe(sub);delete this.__subscribedToParent};this.__addOndisconnected(ondelete);this.__subscribedToParent=true}}return this.__operator};this.__proxyObject=obj=>{let allProps=getAllProperties(obj);for(const k of allProps){if(typeof this[k]==="undefined"){if(typeof obj[k]==="function"){this[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=obj[k](...args);if(this.__node.state.triggers[this.__node.unique+"."+k]){if(typeof result?.then==="function"){result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else this.__node.state.setValue(this.__node.unique+"."+k,result)}return result}}else{let definition={get:()=>{return obj[k]},set:value=>{obj[k]=value;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,value)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition)}}}};let orig=properties;if(typeof properties==="function"){if(isNativeClass(properties)){console.log(properties);properties=new properties}else properties={__operator:properties,__node:{forward:true,tag:properties.name}}}else if(typeof properties==="string"){if(graph?.get(properties)){properties=graph.get(properties)}}if(!properties.__node.initial)properties.__node.initial=orig;if(typeof properties==="object"){if(properties.__props){if(typeof properties.__props==="function")properties.__props=new properties.__props;if(typeof properties.__props==="object"){this.__proxyObject(properties.__props)}}if(typeof properties.__node==="string"){if(graph?.get(properties.__node.tag)){properties=graph.get(properties.__node.tag)}else properties.__node={}}else if(!properties.__node)properties.__node={};if(graph){properties.__node.graph=graph}if(properties.__operator){if(typeof properties.__operator==="string"){if(graph){let n=graph.get(properties.__operator);if(n)properties.__operator=n.__operator;if(!properties.__node.tag&&properties.__operator.name)properties.__node.tag=properties.__operator.name}}if(typeof properties.__operator==="function")properties.__operator=this.__setOperator(properties.__operator)}if(!properties.__node.tag){if(properties.__operator?.name)properties.__node.tag=properties.__operator.name;else properties.__node.tag=`node${Math.floor(Math.random()*1e15)}`}if(!properties.__parent&&parent2)properties.__parent=parent2;if(parent2?.__node&&!(parent2 instanceof Graph||properties instanceof Graph))properties.__node.tag=parent2.__node.tag+"."+properties.__node.tag;if(parent2 instanceof Graph&&properties instanceof Graph){if(properties.__node.loaders)Object.assign(parent2.__node.loaders?parent2.__node.loaders:{},properties.__node.loaders);if(parent2.__node.mapGraphs){properties.__node.nodes.forEach(n=>{parent2.set(properties.__node.tag+"."+n.__node.tag,n)});let ondelete=()=>{properties.__node.nodes.forEach(n=>{parent2.__node.nodes.delete(properties.__node.tag+"."+n.__node.tag)})};this.__addOndisconnected(ondelete)}}properties.__node=Object.assign(this.__node,properties.__node);let keys=Object.getOwnPropertyNames(properties);for(const key of keys){this[key]=properties[key]}if(typeof properties.default==="function"&&!properties.__operator){let fn=properties.default.bind(this);this.default=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"input",args);let result=fn(...args);if(typeof result?.then==="function"){result.then(res=>{if(res!==void 0)this.__node.state.setValue(this.__node.unique,res)}).catch(console.error)}else if(result!==void 0)this.__node.state.setValue(this.__node.unique,result);return result};properties.default=this.default}if(properties instanceof Graph)this.__node.source=properties}}__addLocalState(props){if(!props)return;if(!this.__node.localState){this.__node.localState={}}let localState=this.__node.localState;for(let k in props){if(this.__props&&this.__props[k])continue;if(typeof props[k]==="function"){if(!k.startsWith("_")){let fn=props[k].bind(this);props[k]=(...args)=>{if(this.__node.inputState)this.__node.state.setValue(this.__node.unique+"."+k+"input",args);let result=fn(...args);if(typeof result?.then==="function"){if(this.__node.state.triggers[this.__node.unique+"."+k])result.then(res=>{this.__node.state.setValue(this.__node.unique+"."+k,res)}).catch(console.error)}else if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,result);return result};this[k]=props[k]}}else{localState[k]=props[k];let definition={get:()=>{return localState[k]},set:v2=>{localState[k]=v2;if(this.__node.state.triggers[this.__node.unique+"."+k])this.__node.state.setValue(this.__node.unique+"."+k,v2)},enumerable:true,configurable:true};Object.defineProperty(this,k,definition);if(typeof this.__node.initial==="object"){let dec=Object.getOwnPropertyDescriptor(this.__node.initial,k);if(dec===void 0||dec?.configurable){Object.defineProperty(this.__node.initial,k,definition)}}}}}__addOnconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__onconnected.push(callback)}else if(typeof this.__onconnected==="function"){this.__onconnected=[callback,this.__onconnected]}else this.__onconnected=callback}__addOndisconnected(callback){if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.push(callback)}else if(typeof this.__ondisconnected==="function"){this.__ondisconnected=[callback,this.__ondisconnected]}else this.__ondisconnected=callback}__callConnected(node=this){if(typeof this.__onconnected==="function"){this.__onconnected(this)}else if(Array.isArray(this.__onconnected)){this.__onconnected.forEach(o=>{o(this)})}}__callDisconnected(node=this){if(typeof this.__ondisconnected==="function")this.__ondisconnected(this);else if(Array.isArray(this.__ondisconnected)){this.__ondisconnected.forEach(o=>{o(this)})}}};var Graph=class{constructor(options){this.__node={tag:`graph${Math.floor(Math.random()*1e15)}`,nodes:new Map,state};this.init=options=>{if(options){recursivelyAssign(this.__node,options);if(options.tree)this.setTree(options.tree)}};this.setTree=tree=>{this.__node.tree=Object.assign(this.__node.tree?this.__node.tree:{},tree);let cpy=Object.assign({},tree);if(cpy.__node)delete cpy.__node;let listeners=this.recursiveSet(cpy,this,void 0,tree);if(tree.__node){if(!tree.__node.tag)tree.__node._tag=`tree${Math.floor(Math.random()*1e15)}`;else if(!this.get(tree.__node.tag)){let node=new GraphNode(tree,this,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent,this,this.__node.tree,tree);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,this,this,tree,tree,tree.__node.tag)}if(node.__listeners){listeners[node.__node.tag]=node.__listeners}}}else if(tree.__listeners){this.setListeners(tree.__listeners)}this.setListeners(listeners);return cpy};this.setLoaders=(loaders2,replace)=>{if(replace)this.__node.loaders=loaders2;else Object.assign(this.__node.loaders,loaders2);return this.__node.loaders};this.add=(properties,parent2)=>{let listeners={};if(typeof parent2==="string")parent2=this.get(parent2);let instanced;if(typeof properties==="function"){if(isNativeClass(properties)){if(properties.prototype instanceof GraphNode){properties=properties.prototype.constructor(properties,parent2,this);instanced=true}else properties=new properties}else properties={__operator:properties}}else if(typeof properties==="string")properties=this.__node.tree[properties];if(!instanced){properties=Object.assign({},properties)}if(!properties.__node)properties.__node={};properties.__node.initial=properties;if(typeof properties==="object"&&(!properties?.__node?.tag||!this.get(properties.__node.tag))){let node;if(instanced)node=properties;else node=new GraphNode(properties,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){if(typeof this.__node.loaders[l]==="object"){if(this.__node.loaders[l].init)this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag);if(this.__node.loaders[l].connected)node.__addOnconnected(this.__node.loaders[l].connect);if(this.__node.loaders[l].disconnected)node.__addOndisconnected(this.__node.loaders[l].disconnect)}else if(typeof this.__node.loaders==="function")this.__node.loaders[l](node,parent2,this,this.__node.tree,properties,node.__node.tag)}this.__node.tree[node.__node.tag]=properties;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}this.setListeners(listeners);node.__callConnected();return node}return};this.recursiveSet=(t,parent2,listeners={},origin)=>{let keys=Object.getOwnPropertyNames(origin);for(const key of keys){if(key.includes("__"))continue;let p=origin[key];if(Array.isArray(p))continue;let instanced;if(typeof p==="function"){if(isNativeClass(p)){p=new p;if(p instanceof GraphNode){p=p.prototype.constructor(p,parent2,this);instanced=true}}else p={__operator:p}}else if(typeof p==="string")p=this.__node.tree[p];else if(typeof p==="boolean")p=this.__node.tree[key];if(typeof p==="object"){if(!instanced){p=Object.assign({},p)}if(!p.__node)p.__node={};if(!p.__node.tag)p.__node.tag=key;p.__node.initial=t[key];if(this.get(p.__node.tag)&&!(parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))||parent2?.__node&&this.get(parent2.__node.tag+"."+p.__node.tag))continue;let node;if(instanced)node=p;else node=new GraphNode(p,parent2,this);this.set(node.__node.tag,node);for(const l in this.__node.loaders){this.__node.loaders[l](node,parent2,this,t,t[key],key)}t[key]=node;this.__node.tree[node.__node.tag]=p;if(node.__listeners){listeners[node.__node.tag]=node.__listeners}if(node.__children){node.__children=Object.assign({},node.__children);this.recursiveSet(node.__children,node,listeners,node.__children)}node.__callConnected()}}return listeners};this.remove=(node,clearListeners=true)=>{this.unsubscribe(node);if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){this.delete(node.__node.tag);delete this.__node.tree[node.__node.tag];if(clearListeners){this.clearListeners(node)}node.__callDisconnected();const recursiveRemove=t=>{for(const key in t){this.unsubscribe(t[key]);this.delete(t[key].__node.tag);delete this.__node.tree[t[key].__node.tag];this.delete(key);delete this.__node.tree[key];t[key].__node.tag=t[key].__node.tag.substring(t[key].__node.tag.lastIndexOf(".")+1);if(clearListeners){this.clearListeners(t[key])}t[key].__callDisconnected();if(t[key].__children){recursiveRemove(t[key].__children)}}};if(node.__children){recursiveRemove(node.__children)}}if(node?.__node.tag&&node?.__parent){delete node?.__parent;node.__node.tag=node.__node.tag.substring(node.__node.tag.indexOf(".")+1)}return node};this.run=(node,...args)=>{if(typeof node==="string"){let nd=this.get(node);if(!nd&&node.includes(".")){nd=this.get(node.substring(0,node.lastIndexOf(".")));if(typeof nd?.[node.substring(node.lastIndexOf(".")+1)]==="function")return nd[node.substring(node.lastIndexOf(".")+1)](...args)}else if(nd?.__operator)return nd.__operator(...args)}if(node?.__operator){return node?.__operator(...args)}};this.setListeners=listeners=>{for(const key in listeners){let node=this.get(key);if(typeof listeners[key]==="object"){for(const k in listeners[key]){let n=this.get(k);let sub;if(typeof listeners[key][k]!=="object")listeners[key][k]={__callback:listeners[key][k]};else if(!listeners[key][k].__callback){for(const kk in listeners[key][k]){if(typeof listeners[key][k][kk]!=="object"){listeners[key][k][kk]={__callback:listeners[key][k][kk]};if(listeners[key][k][kk].__callback===true)listeners[key][k][kk].__callback=node.__operator}let nn=this.get(kk);if(nn){if(!nn){let tag=k.substring(0,k.lastIndexOf("."));nn=this.get(tag);if(n){sub=this.subscribe(nn,listeners[key][k][kk].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k][kk].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}else{sub=this.subscribe(nn,listeners[key][k][kk].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k][kk]!=="object")node.__listeners[k][kk]={__callback:listeners[key][k][kk].__callback,inputState:listeners[key][k][kk]?.inputState};node.__listeners[k][kk].sub=sub}}}}if(listeners[key][k].__callback){if(listeners[key][k].__callback===true)listeners[key][k].__callback=node.__operator;if(typeof listeners[key][k].__callback==="function")listeners[key][k].__callback=listeners[key][k].__callback.bind(node);if(typeof node.__listeners!=="object")node.__listeners={};if(!n){let tag=k.substring(0,k.lastIndexOf("."));n=this.get(tag);if(n){sub=this.subscribe(n,listeners[key][k].__callback,k.substring(k.lastIndexOf(".")+1),listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}else{sub=this.subscribe(n,listeners[key][k].__callback,void 0,listeners[key][k].inputState,key,k);if(typeof node.__listeners[k]!=="object")node.__listeners[k]={__callback:listeners[key][k].__callback,inputState:listeners[key][k]?.inputState};node.__listeners[k].sub=sub}}}}}};this.clearListeners=(node,listener)=>{if(typeof node==="string")node=this.get(node);if(node?.__listeners){for(const key in node.__listeners){if(listener&&key!==listener)continue;if(typeof node.__listeners[key].sub!=="number")continue;let n=this.get(key);if(!n){n=this.get(key.substring(0,key.lastIndexOf(".")));if(n){if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,key.substring(key.lastIndexOf(".")+1),node.__listeners[key].inputState)}}else{if(!node.__listeners[key].__callback){for(const k in node.__listeners[key]){this.unsubscribe(n,node.__listeners[key][k].sub,void 0,node.__listeners[key][k].inputState)}}else this.unsubscribe(n,node.__listeners[key].sub,void 0,node.__listeners[key].inputState)}delete node.__listeners[key]}}};this.get=tag=>{return this.__node.nodes.get(tag)};this.set=(tag,node)=>{return this.__node.nodes.set(tag,node)};this.delete=tag=>{return this.__node.nodes.delete(tag)};this.getProps=(node,getInitial)=>{if(typeof node==="string")node=this.get(node);if(node instanceof GraphNode){let cpy;if(getInitial)cpy=Object.assign({},this.__node.tree[node.__node.tag]);else{cpy=Object.assign({},node);delete cpy.__unsubscribe;delete cpy.__setOperator;delete cpy.__node;delete cpy.__subscribeState;delete cpy.__subscribe}}};this.subscribe=(node,callback,key,subInput,target,bound)=>{let nd=node;if(!(node instanceof GraphNode))nd=this.get(node);let sub;if(typeof callback==="string"){if(target){let method=this.get(target)?.[callback];if(typeof method==="function")callback=method}else callback=this.get(callback)?.__operator}if(nd instanceof GraphNode){sub=nd.__subscribe(callback,key,subInput,target,bound);let ondelete=()=>{nd.__unsubscribe(sub,key,subInput)};nd.__addOndisconnected(ondelete)}else if(typeof node==="string"){if(this.get(node)){if(callback instanceof GraphNode&&callback.__operator){sub=this.get(node).__subscribe(callback.__operator,key,subInput,target,bound);let ondelete=()=>{this.get(node).__unsubscribe(sub)};callback.__addOndisconnected(ondelete)}else if(typeof callback==="function"||typeof callback==="string"){sub=this.get(node).__subscribe(callback,key,subInput,target,bound);this.__node.state.getTrigger(this.get(node).__node.unique,sub).source=node}}else{if(typeof callback==="string")callback=this.__node.nodes.get(callback).__operator;if(typeof callback==="function")sub=this.__node.state.subscribeTrigger(node,callback)}}return sub};this.unsubscribe=(node,sub,key,subInput)=>{if(node instanceof GraphNode){return node.__unsubscribe(sub,key,subInput)}else return this.get(node)?.__unsubscribe(sub,key,subInput)};this.setState=update=>{this.__node.state.setState(update)};this.init(options)}};function recursivelyAssign(target,obj){for(const key in obj){if(obj[key]?.constructor.name==="Object"&&!Array.isArray(obj[key])){if(target[key]?.constructor.name==="Object"&&!Array.isArray(target[key]))recursivelyAssign(target[key],obj[key]);else target[key]=recursivelyAssign({},obj[key])}else{target[key]=obj[key]}}return target}function getAllProperties(obj){var allProps=[],curr=obj;do{var props=Object.getOwnPropertyNames(curr);props.forEach(function(prop){if(allProps.indexOf(prop)===-1)allProps.push(prop)})}while(curr=Object.getPrototypeOf(curr));return allProps}function isNativeClass(thing){return typeof thing==="function"&&thing.hasOwnProperty("prototype")&&!thing.hasOwnProperty("arguments")}var backprop=(node,parent2,graph)=>{if(node.__node.backward&&parent2 instanceof GraphNode){graph.setListeners({[parent2.__node.tag]:{[node.__node.tag]:parent2}})}};var loop=(node,parent2,graph)=>{if(node.__operator&&!node.__node.looperSet){node.__node.looperSet=true;if(typeof node.__node.delay==="number"){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{setTimeout(async()=>{res(await fn(...args))},node.__node.delay)})})}else if(node.__node.frame===true){let fn=node.__operator;node.__setOperator((...args)=>{return new Promise((res,rej)=>{requestAnimationFrame(async()=>{res(await fn(...args))})})})}if(typeof node.__node.repeat==="number"||typeof node.__node.recursive==="number"){let fn=node.__operator;node.__setOperator(async(...args)=>{let i=node.__node.repeat?node.__node.repeat:node.__node.recursive;let result;let repeater=async(tick,...inp)=>{while(tick>0){if(node.__node.delay||node.__node.frame){fn(...inp).then(async res=>{if(node.__node.recursive){await repeater(tick,res)}else await repeater(tick,...inp)});break}else result=await fn(...args);tick--}};await repeater(i,...args);return result})}if(node.__node.loop&&typeof node.__node.loop==="number"){let fn=node.__operator;node.__setOperator((...args)=>{if(!("looping"in node.__node))node.__node.looping=true;if(node.__node.looping){fn(...args);setTimeout(()=>{node.__operator(...args)},node.__node.loop)}});if(node.__node.looping)node.__operator();let ondelete=node2=>{if(node2.__node.looping)node2.__node.looping=false};node.__addOndisconnected(ondelete)}}};var animate=(node,parent2,graph)=>{if(node.__node.animate===true||node.__animation){let fn=node.__operator;node.__setOperator((...args)=>{if(!("animating"in node.__node))node.__node.animating=true;if(node.__node.animating){if(typeof node.__animation==="function")node.__animation(...args);else fn(...args);requestAnimationFrame(()=>{node.__operator(...args)})}});if(node.__node.animating||(!("animating"in node.__node)||node.__node.animating)&&node.__animation)setTimeout(()=>{requestAnimationFrame(node.__operator)},10);let ondelete=node2=>{if(node2.__node.animating)node2.__node.animating=false};node.__addOndisconnected(ondelete)}};var branching=(node,parent2,graph)=>{if(typeof node.__node.branch==="object"&&node.__operator&&!node.__node.branchApplied){let fn=node.__operator;node.__node.branchApplied=true;node.__operator=(...args)=>{let result=fn(...args);for(const key in node.__node.branch){let triggered=()=>{if(typeof node.__node.branch[key].then==="function"){node.__node.branch[key].then(result)}else if(node.__node.branch[key].then instanceof GraphNode&&node.__node.branch[key].then.__operator){node.__node.branch[key].then.__operator(result)}else result=node.__node.branch[key].then};if(typeof node.__node.branch[key].if==="function"){if(node.__node.branch[key].if(result)){triggered()}}else if(node.__node.branch[key].if===result){triggered()}}return result}}if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].branch&&!node.__listeners[key].branchApplied){let fn=node.__listeners[key].callback;node.__listeners[key].branchApplied=true;node.__listeners.callback=ret=>{let triggered=()=>{if(typeof node.__listeners[key].branch.then==="function"){ret=node.__listeners[key].branch.then(ret)}else if(node.__listeners[key].branch.then instanceof GraphNode&&node.__listeners[key].branch.then.__operator){ret=node.__listeners[key].branch.then.__operator(ret)}else ret=node.__listeners[key].branch.then};if(typeof node.__listeners[key].branch.if==="function"){if(node.__listeners[key].branch.if(ret)){triggered()}}else if(node.__listeners[key].branch.if===ret){triggered()}return fn(ret)}}}}}};var triggerListenerOncreate=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(node.__listeners[key].oncreate){node.__listeners[key].callback(node.__listeners[key].oncreate)}}}}};var bindListener=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].binding==="object"){node.__listeners.callback=node.__listeners.callback.bind(node.__listeners[key].binding)}}}}};var transformListenerResult=(node,parent2,graph)=>{if(node.__listeners){for(const key in node.__listeners){if(typeof node.__listeners[key]==="object"){if(typeof node.__listeners[key].transform==="function"&&!node.__listeners[key].transformApplied){let fn=node.__listeners[key].callback;node.__listeners[key].transformApplied=true;node.__listeners.callback=ret=>{ret=node.__listeners[key].transform(ret);return fn(ret)}}}}}};var substitute__operator=(node,parent2,graph)=>{if(node.post&&!node.__operator){node.__setOperator(node.post)}else if(!node.__operator&&typeof node.get=="function"){node.__setOperator(node.get)}if(!node.get&&node.__operator){node.get=node.__operator}if(node.aliases){node.aliases.forEach(a=>{graph.set(a,node);let ondelete=node2=>{graph.__node.nodes.delete(a)};node.__addOndisconnected(ondelete)})}if(typeof graph.__node.tree[node.__node.tag]==="object"&&node.get)graph.__node.tree[node.__node.tag].get=node.get};var loaders={backprop,loop,animate,branching,triggerListenerOncreate,bindListener,transformListenerResult,substitute__operator};var Service=class extends Graph{constructor(options){super({...options,loaders:options?.loaders?Object.assign({...loaders},options.loaders):{...loaders}});this.name=`service${Math.floor(Math.random()*1e15)}`;this.addServices=services=>{for(const s in services){if(typeof services[s]==="function")services[s]=new services[s];if(services[s]?.__node?.loaders)Object.assign(this.__node.loaders,services[s].__node.loaders);if(services[s]?.__node?.nodes){services[s].__node.nodes.forEach((n,tag)=>{if(!this.get(tag)){this.set(tag,n)}else this.set(s+"."+tag,n)});this.__node.nodes.forEach((n,k)=>{if(!services[s].__node.nodes.get(k))services[s].__node.nodes.set(k,n)});let set=this.set;this.set=(tag,node)=>{services[s].set(tag,node);return set(tag,node)};let del=this.delete;this.delete=tag=>{services[s].delete(tag);return del(tag)}}else if(typeof services[s]==="object"){this.setTree(services[s])}}};this.handleMethod=(route,method,args)=>{let m=method.toLowerCase();let src=this.__node.nodes.get(route);if(!src){src=this.__node.tree[route]}if(src?.[m]){if(!(src[m]instanceof Function)){if(args)src[m]=args;return src[m]}else return src[m](args)}else return this.handleServiceMessage({route,args,method})};this.transmit=(...args)=>{if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.receive=(...args)=>{if(args[0]){if(typeof args[0]==="string"){let substr=args[0].substring(0,8);if(substr.includes("{")||substr.includes("[")){if(substr.includes("\\"))args[0]=args[0].replace(/\\/g,"");if(args[0][0]==='"'){args[0]=args[0].substring(1,args[0].length-1)};args[0]=JSON.parse(args[0])}}}if(typeof args[0]==="object"){if(args[0].method){return this.handleMethod(args[0].route,args[0].method,args[0].args)}else if(args[0].route){return this.handleServiceMessage(args[0])}else if(args[0].node){return this.handleGraphNodeCall(args[0].node,args[0].args)}else if(this.__node.keepState){if(args[0].route)this.setState({[args[0].route]:args[0].args});if(args[0].node)this.setState({[args[0].node]:args[0].args})}return args}else return args};this.pipe=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return this.subscribe(source,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.subscribe(source,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.pipeOnce=(source,destination,endpoint,method,callback)=>{if(source instanceof GraphNode){if(callback)return source.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{let mod=callback(res);if(mod!==void 0)this.transmit({route:destination,args:mod,method});else this.transmit({route:destination,args:res,method},endpoint)});else return this.__node.state.subscribeTriggerOnce(source.__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})}else if(typeof source==="string")return this.__node.state.subscribeTriggerOnce(this.__node.nodes.get(source).__node.unique,res=>{this.transmit({route:destination,args:res,method},endpoint)})};this.terminate=(...args)=>{};this.isTypedArray=isTypedArray;this.recursivelyAssign=recursivelyAssign2;this.spliceTypedArray=spliceTypedArray;this.ping=()=>{console.log("pinged!");return"pong"};this.echo=(...args)=>{this.transmit(...args);return args};if(options?.services)this.addServices(options.services);this.setTree(this)}handleServiceMessage(message){let call;if(typeof message==="object"){if(message.route)call=message.route;else if(message.node)call=message.node}if(call){if(Array.isArray(message.args))return this.run(call,...message.args);else return this.run(call,message.args)}else return message}handleGraphNodeCall(route,args){if(!route)return args;if(args?.args){this.handleServiceMessage(args)}else if(Array.isArray(args))return this.run(route,...args);else return this.run(route,args)}};function isTypedArray(x3){return ArrayBuffer.isView(x3)&&Object.prototype.toString.call(x3)!=="[object DataView]"}var recursivelyAssign2=(target,obj)=>{for(const key in obj){if(typeof obj[key]==="object"&&!Array.isArray(obj[key])){if(typeof target[key]==="object"&&!Array.isArray(target[key]))recursivelyAssign2(target[key],obj[key]);else target[key]=recursivelyAssign2({},obj[key])}else target[key]=obj[key]}return target};function spliceTypedArray(arr,start,end){let s=arr.subarray(0,start);let e;if(end){e=arr.subarray(end+1)}let ta;if(s.length>0||e?.length>0)ta=new arr.constructor(s.length+e.length);if(ta){if(s.length>0)ta.set(s);if(e&&e.length>0)ta.set(e,s.length)}return ta}var randomId=prefix=>(prefix?`${prefix}`:"")+Math.floor(1e15*Math.random());var pseudoObjectId=(m=Math,d2=Date,h=16,s=s2=>m.floor(s2).toString(h))=>s(d2.now()/1e3)+" ".repeat(h).replace(/./g,()=>s(m.random()*h));var StructFrontend=class extends Service{constructor(options,user){super(options);this.name="structs";this.tablet=new DataTablet;this.collections=this.tablet.collections;this.id=randomId();this.baseServerCallback=data=>{let structs=data;if(typeof data==="object"&&data?.structType)structs=[data];if(Array.isArray(structs)){let filtered=structs.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered);structs.forEach(struct=>{if(typeof struct==="object"){if(!struct.structType||struct.structType==="USER"){if(struct.email)struct.structType="user";else struct.structType="uncategorized"}if(struct.structType==="user"||struct.structType==="authorization"||struct.structType==="group"){if(struct.structType==="user"){struct._id=struct.id}else if(struct.structType==="group"){if(this.currentUser){let uset=false;if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_admin"]){this.currentUser.userRoles[struct.name+"_admin"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_admin"]){delete this.currentUser.userRoles[struct.name+"_admin"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_peer"]){this.currentUser.userRoles[struct.name+"_peer"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_peer"]){delete this.currentUser.userRoles[struct.name+"_peer"];uset=true}if(struct.admins[this.currentUser?._id]&&!this.currentUser.userRoles?.[struct.name+"_client"]){this.currentUser.userRoles[struct.name+"_client"]=true;uset=true}else if(!struct.admins[this.currentUser?._id]&&this.currentUser.userRoles?.[struct.name+"_client"]){delete this.currentUser.userRoles[struct.name+"_client"];uset=true}if(uset)this.setUser(this.currentUser)}}this.setLocalData(struct)}else{if(struct.structType==="notification"){let found=this.getLocalData("notification",{"ownerId":struct.ownerId,"_id":struct.parent._id});if(found){this.setLocalData(struct)}else{if(this.getLocalData(struct.structType,{"_id":struct.parent._id})){}else{this.overwriteLocalData(struct)}}if(struct.ownerId===this.currentUser?._id&&(struct.parent.structType==="user"||struct.parent.structType==="dataInstance"||struct.parent.structType==="schedule"||struct.parent.structType==="authorization")){this.resolveNotifications([struct],true)}}else{this.overwriteLocalData(struct)}}}})}if(data?.message==="notifications"){this.checkForNotifications()}if(data?.message==="deleted"){this.deleteLocalData(data.data)}this.onResult(data)};this.getUser=async(info="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"getUser",args:[this.currentUser._id,info]}))?.[0];callback(res);return res}};this.getUsers=async(ids=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByIds",args:[this.currentUser._id,ids]});callback(res);return res}};this.getUsersByRole=async(userRole,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUsersByRole",args:[this.currentUser._id,userRole]});callback(res);return res}};this.getAllUserData=async(ownerId,excluded=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getAllData",args:[ownerId,excluded]});callback(res);return res}};this.query=async(collection,queryObj={},findOne=false,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!collection||!queryObj)return void 0;let res=await this.currentUser.request({route:"query",args:[this.currentUser._id,collection,queryObj,findOne,skip]});if(typeof callback==="function")callback(res);return res}};this.getData=async(collection,ownerId,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getData",args:[this.currentUser._id,collection,ownerId,searchDict,limit,skip]});if(typeof callback==="function")callback(res);return res}};this.getDataByIds=async(structIds=[],ownerId,collection,callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getDataByIds",args:[this.currentUser._id,structIds,ownerId,collection]});if(typeof callback==="function")callback(res);return res}};this.getStructParentData=async(struct,callback=this.baseServerCallback)=>{if(!struct.parent)return;if(this.currentUser?.request){let args=[this.currentUser._id,struct.parent?.structType,"_id",struct.parent?._id];let res=(await this.currentUser.request({route:"getData",args}))?.[0];if(typeof callback==="function")callback(res);return res}};this.setUser=async(userStruct={},callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"setUser",args:[this.currentUser._id,this.stripStruct(userStruct)]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.checkUserToken=async(usertoken,user=this.currentUser,callback=this.baseServerCallback)=>{if(!usertoken)return false;let changed=false;for(const prop in usertoken){let dummystruct=this.userStruct();if(user[prop]&&prop!=="_id"){if(Array.isArray(usertoken[prop])){for(let i=0;i{if(this.currentUser?.request){const copies=new Array;if(!Array.isArray(structs)&&typeof structs==="object")structs=[structs];structs.forEach(struct=>{copies.push(this.stripStruct(struct))});let res=await this.currentUser.request({route:"setData",args:[this.currentUser._id,copies,notify]});if(typeof callback==="function")callback(res);return res}};this.updateServerData=this.setData;this.deleteData=async(structs=[],callback=this.baseServerCallback)=>{if(this.currentUser?.request){let toDelete=[];structs.forEach(struct=>{if(typeof struct==="object"){if(struct?.structType&&struct?._id){toDelete.push({structType:struct.structType,_id:struct._id});this.deleteLocalData(struct)}}else if(typeof struct==="string"){let localstruct=this.getLocalData(void 0,{_id:struct});if(localstruct&&!Array.isArray(localstruct)){toDelete.push({structType:localstruct.structType,_id:localstruct._id})}else{toDelete.push({_id:struct})}}});let res=(await this.currentUser.request({route:"deleteData",args:[this.currentUser._id,toDelete]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.deleteUser=async(userId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!userId)return;let res=(await this.currentUser.request({route:"deleteUser",args:[this.currentUser._id,userId]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.setGroup=async(groupStruct={},callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"setGroup",args:[this.currentUser._id,this.stripStruct(groupStruct)]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.getUserGroups=async(userId=this.currentUser._id,groupId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=await this.currentUser.request({route:"getUserGroups",args:[this.currentUser._id,userId,groupId]});if(typeof callback==="function")callback(res);return res}};this.deleteGroup=async(groupId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!groupId)return;this.deleteLocalData(groupId);let res=(await this.currentUser.request({route:"deleteGroup",args:[this.currentUser._id,groupId]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.setAuthorization=async(authorizationStruct={},callback=this.baseServerCallback)=>{if(this.currentUser?.request){let res=(await this.currentUser.request({route:"setAuthorization",args:[this.currentUser._id,this.stripStruct(authorizationStruct)]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.getAuthorizations=async(userId=this.currentUser?._id,authorizationId="",callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(userId===void 0)return;let res=await this.currentUser.request({route:"getAuthorizations",args:[this.currentUser._id,userId,authorizationId]});if(typeof callback==="function")callback(res);return res}};this.deleteAuthorization=async(authorizationId,callback=this.baseServerCallback)=>{if(this.currentUser?.request){if(!authorizationId)return;this.deleteLocalData(authorizationId);let res=(await this.currentUser.request({route:"deleteAuthorization",args:[authorizationId]}))?.[0];if(typeof callback==="function")callback(res);return res}};this.checkForNotifications=async(userId=this.currentUser?._id)=>{return await this.getData("notification",userId)};this.resolveNotifications=async(notifications=[],pull=true,user=this.currentUser)=>{if(!user||notifications.length===0)return;let structIds=[];let notificationIds=[];let nTypes=[];let unote=false;if(notifications.length===0)notifications=this.getLocalData("notification",{"ownerId":user._id});notifications.forEach(struct=>{if(struct.parent.structType==="user")unote=true;nTypes.push(struct.parent.structType);structIds.push(struct.parent._id);notificationIds.push(struct._id);this.deleteLocalData(struct)});this.deleteData(notifications);if(pull){nTypes.reverse().forEach((note,i)=>{if(note==="user"){this.getUser(structIds[i]);structIds.splice(structIds.length-i-1,1)}});if(structIds.length===1)return await this.getDataByIds(structIds,void 0,notifications[0].parent.structType);if(structIds.length>0)return await this.getDataByIds(structIds)}return true};this.setAuthorizationsByGroup=async(user=this.currentUser)=>{let auths=this.getLocalData("authorization",{"ownerId":user._id});let newauths=[];if(user.userRoles)await Promise.all(Object.keys(user.userRoles).map(async role=>{let split=role.split("_");let team=split[0];let otherrole;if(role.includes("client")){otherrole=team+"_peer"}else if(role.includes("peer")){otherrole=team+"_client"}else if(role.includes("admin")){otherrole=team+"_owner"}if(otherrole){let users=await this.getUsersByRole(otherrole);if(users)await Promise.all(users.map(async groupie=>{let theirname=groupie.username;if(!theirname)theirname=groupie.email;if(!theirname)theirname=groupie._id;let myname=user.username;if(!myname)myname=user.email;if(!myname)myname=user._id;if(theirname!==myname){if(role.includes("client")){let found=auths.find(a=>{if(a.authorizerId===groupie._id&&a.authorizedId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),groupie._id,theirname,user._id,myname,{"peer":true},void 0,{group:team});newauths.push(auth)}}else if(role.includes("peer")){let found=auths.find(a=>{if(a.authorizedId===groupie._id&&a.authorizerId===user._id)return true});if(!found){let auth=await this.authorizeUser(DataStructures_exports.ProfileStruct("user",user,user),user._id,myname,groupie._id,theirname,{"peer":true},void 0,{group:team});newauths.push(auth)}}}}))}}));if(newauths.length>0)return newauths;return void 0};this.deleteRoom=async roomStruct=>{if(!roomStruct)return false;let toDelete=[roomStruct];roomStruct.comments?.forEach(id=>{let struct=this.getLocalData("comment",{"_id":id});toDelete.push(struct)});if(roomStruct)return await this.deleteData(toDelete);else return false};this.deleteComment=async commentStruct=>{let allReplies=[commentStruct];let getRepliesRecursive=(head=commentStruct)=>{if(head?.replies){head.replies.forEach(replyId=>{let reply=this.getLocalData("comment",{"_id":replyId});if(reply){if(reply.replies.length>0){reply.replies.forEach(replyId2=>{getRepliesRecursive(replyId2)})}allReplies.push(reply)}})}};getRepliesRecursive(commentStruct);let parent2=this.getLocalData(commentStruct.parent?.structType,{"_id":commentStruct.parent?._id});let toUpdate=[];if(parent2){toUpdate=[parent2];allReplies.forEach(r=>{let idx=parent2.replies?.indexOf(r._id);if(idx>-1)parent2.replies.splice(idx,1);let idx2=parent2.comments?.indexOf(r._id);if(idx2>-1)parent2.comments.splice(idx2,1)})}let replyTo=this.getLocalData("comment",{"_id":commentStruct.replyTo});if(replyTo?._id!==parent2?._id){let idx=replyTo.replies?.indexOf(parent2._id);if(idx>-1)replyTo.replies.splice(idx,1);toUpdate.push(replyTo)}if(toUpdate.length>0)await this.updateServerData(toUpdate);return await this.deleteData(allReplies)};this.getUserDataByAuthorization=async(authorizationStruct,collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let u=authorizationStruct.authorizerId;if(u){return new Promise(async resolve=>{this.getUser(u,async data=>{if(!collection)await this.getAllUserData(u,["notification"],callback);else await this.getData(collection,u,searchDict,limit,skip,callback);resolve(data);callback(data)})})}else return void 0};this.getUserDataByAuthorizationGroup=async(groupId="",collection,searchDict,limit=0,skip=0,callback=this.baseServerCallback)=>{let auths=this.getLocalData("authorization");let results=[];await Promise.all(auths.map(async o=>{if(o.groups?.includes(groupId)){let u=o.authorizerId;if(u){let data;let user=await this.getUser(u,callback);if(user)results.push(user);if(!collection)data=await this.getAllUserData(u,["notification"],callback);else data=await this.getData(collection,u,searchDict,limit,skip,callback);if(data)results.push(data)}return true}}));return results};this.getLocalUserPeerIds=(user=this.currentUser)=>{if(!user)return[];let result=[];let authorizations=this.getLocalData("authorization",user._id);authorizations.forEach(a=>{if(a.authorizations["peer"]&&a.authorizerId===user._id)result.push(a.authorizedId)});return result};this.authorizeUser=async(parentUser,authorizerUserId="",authorizerUserName="",authorizedUserId="",authorizedUserName="",authorizations={},structs={},excluded={},groups={},expires=false)=>{if(!parentUser)return void 0;let newAuthorization=this.createStruct("authorization",void 0,parentUser,void 0);newAuthorization.authorizedId=authorizedUserId;newAuthorization.authorizedName=authorizedUserName;newAuthorization.authorizerId=authorizerUserId;newAuthorization.authorizerName=authorizerUserName;newAuthorization.authorizations=authorizations;newAuthorization.structs=structs;newAuthorization.excluded=excluded;newAuthorization.groups=groups;newAuthorization.expires=expires;newAuthorization.status="PENDING";newAuthorization.associatedAuthId="";newAuthorization.ownerId=parentUser._id;newAuthorization=await this.setAuthorization(newAuthorization);return newAuthorization};this.addGroup=async(parentUser,name="",details="",admins={},peers={},clients={},updateServer=true)=>{if(!parentUser)return void 0;let newGroup=this.createStruct("group",void 0,parentUser);newGroup.name=name;newGroup.details=details;newGroup.admins=admins;newGroup.peers=peers;newGroup.clients=clients;newGroup.users={};Object.assign(newGroup.users,newGroup.admins);Object.assign(newGroup.users,newGroup.peers);Object.assign(newGroup.users,newGroup.clients);newGroup.ownerId=parentUser._id;if(updateServer){newGroup=await this.setGroup(newGroup)}return newGroup};this.addData=async(parentUser,author="",title="",type="",data=[],expires=false,updateServer=true)=>{if(!parentUser)return void 0;let newDataInstance=this.createStruct("dataInstance",void 0,parentUser);newDataInstance.author=author;newDataInstance.title=title;newDataInstance.type=type;newDataInstance.data=data;newDataInstance.expires=expires;newDataInstance.ownerId=parentUser._id;if(updateServer)newDataInstance=await this.updateServerData([newDataInstance])[0];return newDataInstance};this.addEvent=async(parentUser,author="",event="",notes="",startTime=0,endTime=0,grade=0,attachments=[],users={},updateServer=true)=>{if(!parentUser)return void 0;if(Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newEvent=this.createStruct("event",void 0,parentUser);newEvent.author=author;newEvent.event=event;newEvent.notes=notes;newEvent.startTime=startTime;newEvent.endTime=endTime;newEvent.grade=grade;newEvent.attachments=attachments;newEvent.users=users;newEvent.ownerId=parentUser._id;if(updateServer)newEvent=await this.updateServerData([newEvent])[0];return newEvent};this.addChatroom=async(parentUser,authorId="",message="",attachments=[],users={},updateServer=true)=>{if(!parentUser)return void 0;if(Object.keys(users).length===0)users=this.getLocalUserPeerIds(parentUser);let newChatroom=this.createStruct("chatroom",void 0,parentUser);newChatroom.message=message;newChatroom.attachments=attachments;newChatroom.authorId=authorId;newChatroom.users=users;newChatroom.replies=[];newChatroom.comments=[];newChatroom.ownerId=parentUser._id;let update=[newChatroom];if(updateServer)newChatroom=await this.updateServerData(update)[0];return newChatroom};this.addComment=async(parentUser,roomStruct,replyTo,authorId="",message="",attachments=[],updateServer=true)=>{if(!roomStruct)return void 0;if(!replyTo)replyTo=roomStruct;if(!parentUser)return void 0;let newComment=this.createStruct("comment",void 0,parentUser,roomStruct);newComment.authorId=authorId;newComment.replyTo=replyTo?._id;newComment.message=message;newComment.attachments=attachments;newComment.users=roomStruct?.users;newComment.replies=[];newComment.ownerId=parentUser._id;if(!updateServer)replyTo?.replies.push(newComment._id);if(!updateServer)roomStruct?.comments.push(newComment._id);let update=[newComment,roomStruct];if(replyTo?._id!==roomStruct._id)update.push(replyTo);let res;if(updateServer)res=await this.updateServerData(update);let updatedComment;if(typeof res==="object"){updatedComment=res.find(s=>{if(newComment.ownerId===s.ownerId&&newComment.timestamp===s.timestamp&&newComment.message===s.message){return true}})}if(updatedComment)return updatedComment;return res};this.setTree(this);if(user instanceof Object&&Object.keys(user).length>0)this.setupUser(user)}async setupUser(userinfo,callback=currentUser=>{}){if(!userinfo){console.error('must provide a minimum info object! e.g. {_id:"abc123"}');callback(void 0);return void 0}let changed=false;if(userinfo.id&&!userinfo._id)userinfo._id=userinfo.id;else if(userinfo._id)userinfo.id=userinfo._id;let res=await this.getUser(userinfo._id);let user=res?.user;let u;let newu=false;console.log("getUser result",user);if(!user||!user._id){console.log("creating new profile");u=this.userStruct(userinfo,true);newu=true;let wasSet=await this.setUser(u);let structs=this.getLocalData(void 0,{"ownerId":u._id});if(structs?.length>0)this.updateServerData(structs);this.setAuthorizationsByGroup(u)}else{u=user;if(res?.authorizations){if(Array.isArray(res.authorizations)){this.setLocalData(res.authorizations)}}if(res?.groups){if(Array.isArray(res.groups)){this.setLocalData(res.groups)}}}if(newu){this.setLocalData(u)}else{let data=await this.getAllUserData(u._id,void 0);if(!data||data.length===0){}else{this.setLocalData(data);let notes=data.filter(s=>{if(s.structType==="notification"){if(this.getLocalData("authorization",s.parent._id)){return true}if(s.parent.structType==="user"||s.parent.structType==="authorization"){return true}if(!this.getLocalData(s.parent.structType,s.parent._id))return true}});let comments=data.filter(s=>{if(s.structType==="comment"){return true}});let toDelete=[];comments.forEach(comment=>{if(!this.getLocalData("comment",{"_id":comment._id}))toDelete.push(comment._id)});if(toDelete.length>0)this.deleteData(toDelete);if(notes.length>0){this.resolveNotifications(notes,false,void 0);changed=true}let filtered=data.filter(o=>{if(o.structType!=="notification")return true});if(this.tablet)this.tablet.sortStructsIntoTable(filtered)}this.setLocalData(u);console.log("collections",this.tablet.collections)}if(u){this.currentUser=u;callback(this.currentUser);return this.currentUser}else{callback(u);return u}}onResult(data){}randomId(tag=""){return`${tag+Math.floor(Math.random()+Math.random()*Math.random()*1e16)}`}async addStruct(structType="struct",props={},parentUser,parentStruct,updateServer=true){let newStruct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);if(updateServer)newStruct=await this.updateServerData([newStruct])[0];return newStruct}overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":struct._id});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":structs._id});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){this.tablet.setLocalData(structs)}getLocalData(collection,query){return this.tablet.getLocalData(collection,query)}getLocalReplies(struct){let replies=[];if(!struct.replies)return replies;else if(struct.replies.reduce((a,b2)=>a*(typeof b2==="object"?1:0),1))return struct.replies;replies=this.getLocalData("comment",{"replyTo":struct._id});return replies}hasLocalAuthorization(otherUserId,ownerId=this.currentUser._id){let auths=this.getLocalData("authorization",{ownerId});let found=auths.find(a=>{if(a.authorizedId===ownerId&&a.authorizerId===otherUserId)return true;if(a.authorizerId===ownerId&&a.authorizedId===otherUserId)return true});if(found){return found}else return false}deleteLocalData(structs){if(Array.isArray(structs))structs.forEach(s=>this.deleteStruct(s));else this.deleteStruct(structs);return true}deleteStruct(struct){if(typeof struct==="string")struct=this.getLocalData(struct);if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;this.tablet.collections.get(struct.structType).delete(struct._id);return true}stripStruct(struct={}){const copy=Object.assign({},struct);for(const prop in copy){if(copy[prop]===void 0||copy[prop].constructor.name==="Map"||typeof copy[prop]==="function")delete copy[prop]}return copy}createStruct(structType,props,parentUser=this.currentUser,parentStruct){let struct=DataStructures_exports.Struct(structType,props,parentUser,parentStruct);return struct}userStruct(props={},currentUser=false){let user=DataStructures_exports.ProfileStruct(void 0,props,props);if(props._id)user.id=props._id;else if(props.id)user.id=props.id;else user.id="user"+Math.floor(Math.random()*1e10);user._id=user.id;user.ownerId=user.id;for(const prop in props){if(Object.keys(DataStructures_exports.ProfileStruct()).indexOf(prop)<0){delete user[prop]}}if(currentUser)this.currentUser=user;return user}dataObject(data=void 0,type="any",timestamp=Date.now()){return{type,data,timestamp}}};var import_bson_objectid=__toESM(require_objectid());var randomId2=prefix=>(prefix?`${prefix}_`:"")+Math.floor(1e15*Math.random());var toObjectID=str2=>{return typeof str2==="string"&&str2.length===24?(0,import_bson_objectid.default)(str2):str2};var getStringId=mongoid=>{if(typeof mongoid==="object")return mongoid.toString();else return mongoid};var defaultCollections=["profile","group","authorization","discussion","chatroom","comment","dataInstance","event","notification","schedule","date"];var StructBackend=class extends Service{constructor(options,dboptions){super(options);this.name="structs";this.debug=false;this.users={};this.collections={};this.useAuths=true;this.query=async(requestingUserId,collection,queryObj,findOne,skip)=>{let user=this.users[requestingUserId];if(!user)return false;if(this.mode.indexOf("mongo")>-1){return await this.queryMongo(user,collection,queryObj,findOne,skip)}else{let res=this.getLocalData(user,collection);if(res&&!Array.isArray(res)){let passed=!this.useAuths;if(!res?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,res)}if(typeof skip==="number"&&Array.isArray(res)){if(res.length>skip)res.splice(0,skip)}let data=[];if(res)await Promise.all(res.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}));return data}};this.getUser=async(requestingUserId,lookupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.getMongoUser(user,lookupId)}else{let struct=this.getLocalData("profile",{_id:lookupId});if(!struct)data={user:{}};else{let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed){let groups=this.getLocalData("group",{ownerId:lookupId});let auths=this.getLocalData("authorization",{ownerId:lookupId});data={user:struct,groups,authorizations:auths}}else data={user:{}}}}if(this.debug)console.log("getUser: user:",user,"input:",lookupId,"output",data);return data};this.setUser=async(requestingUserId,struct)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.indexOf("mongo")>-1){data=await this.setMongoUser(user,struct)}else{let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)this.setLocalData(struct);return true}if(this.debug)console.log("setUser user:",user,"input:",struct,"output",data);return data};this.getUsersByIds=async(requestingUserId,userIds)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByIds(user,userIds)}else{data=[];if(Array.isArray(userIds)){let struct=this.getLocalData("profile",{_id:userIds});if(struct)data.push(struct)}}if(this.debug)console.log("getUserByIds: user:",user,"input:",userIds,"output",data);return data};this.getUsersByRole=async(requestingUserId,role)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoUsersByRole(user,role)}else{let profiles=this.getLocalData("profile");data=[];profiles.forEach(struct=>{if(struct.userRoles[role]){data.push(struct)}})}if(this.debug)console.log("getUserByRoles: user:",user,"input:",role,"output",data);return data};this.deleteUser=async(requestingUserId,userId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoUser(user,userId)}else{data=false;let struct=this.getLocalData(userId);if(struct){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteUser: user:",user,"input:",userId,"output",data);return data};this.setData=async(requestingUserId,structs,notify)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.setMongoData(user,structs,notify)}else{let non_notes=[];data=[];await Promise.all(structs.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed){if(!this.collections[struct.structType]){this.collections[struct.structType]=this.db?{instance:this.db.collection(struct.structType)}:{};this.collections[struct.structType].reference={}}this.setLocalData(struct);data.push(struct);if(struct.structType!=="notification")non_notes.push(struct)}}));if(non_notes.length>0&&(notify===true||typeof notify==="undefined"))this.checkToNotify(user,non_notes,this.mode);if(this.debug)console.log("setData:",user,structs,data);return true}if(this.debug)console.log("setData: user:",user,"input:",structs,notify,"output",data);return data};this.getData=async(requestingUserId,collection,ownerId,dict,limit,skip)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoData(user,collection,ownerId,dict,limit,skip)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}))}if(this.debug)console.log("getData: user:",user,"input:",collection,ownerId,dict,limit,skip,"output",data);return data};this.getDataByIds=async(requestingUserId,structIds,ownerId,collection)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoDataByIds(user,structIds,ownerId,collection)}else{data=[];let structs;if(collection)structs=this.getLocalData(collection);if(structs&&ownerId)structs=structs.filter(o=>{if(o.ownerId===ownerId)return true});if(structs)await Promise.all(structs.map(async s=>{let struct=this.getLocalData(getStringId(s._id));let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}))}if(this.debug)console.log("getDataByIds: user:",user,"input:",structIds,ownerId,collection,"output",data);return data};this.getAllData=async(requestingUserId,ownerId,excludedCollections)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getAllUserMongoData(user,ownerId,excludedCollections)}else{let result=this.getLocalData(void 0,{ownerId});data=[];await Promise.all(result.map(async struct=>{if(excludedCollections){if(excludedCollections.indexOf(struct.structType)<0){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}}else{let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct);if(passed)data.push(struct)}}))}if(this.debug)console.log("getAllData: user:",user,"input:",ownerId,excludedCollections,"output",data);return data};this.deleteData=async(requestingUserId,structIds)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoData(user,structIds)}else{data=false;await Promise.all(structIds.map(async structId=>{let struct=this.getLocalData(structId);let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)this.deleteLocalData(struct);data=true}))}if(this.debug)console.log("deleteData: user:",user,"input:",structIds,"output",data);return data};this.getUserGroups=async(requestingUserId,userId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoGroups(user,userId,groupId)}else{if(typeof groupId==="string"){data=this.getLocalData("group",{_id:groupId})}else{data=[];let result=this.getLocalData("group");if(userId){result.forEach(struct=>{if(Object.keys(struct.users).includes(userId))data.push(struct)})}else{result.forEach(struct=>{if(Object.keys(struct.users).includes(getStringId(user._id)))data.push(struct)})}}}if(this.debug)console.log("getGroups: user:",user,"input:",userId,groupId,"output",data);return data};this.deleteGroup=async(requestingUserId,groupId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoGroup(user,groupId)}else{let struct=this.getLocalData("group",groupId);let passed=!this.useAuths;if(struct){if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE")}if(passed){data=true}}if(this.debug)console.log("deleteGroup: user:",user,"input:",groupId,"output",data);return data};this.getAuthorizations=async(requestingUserId,ownerId,authId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.getMongoAuthorizations(user,ownerId,authId)}else{if(authId){let result=this.getLocalData("authorization",{_id:authId});if(result)data=[result]}else{data=this.getLocalData("authorization",{ownerId})}}if(this.debug)console.log("getAuthorizations: user:",user,"input:",ownerId,authId,"output",data);return data};this.deleteAuthorization=async(requestingUserId,authId)=>{let user=this.users[requestingUserId];if(!user)return false;let data;if(this.mode.includes("mongo")){data=await this.deleteMongoAuthorization(user,authId)}else{data=true;let struct=this.getLocalData("authorization",{_id:authId});if(struct){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(passed)data=this.deleteLocalData(struct)}}if(this.debug)console.log("deleteAuthorization: user:",user,"input:",authId,"output",data);return data};this.wipeDB=async()=>{await Promise.all(Object.values(this.collections).map(c=>{try{c.instance.remove({})}catch(err){}}));return true};this.setTree(this);if(dboptions?.users)this.users=dboptions.users;if(dboptions?.db)this.mode=this.db?dboptions.mode?dboptions.mode:"local":"local";if(dboptions?.collections)this.collections=dboptions.collections;defaultCollections.forEach(k=>{if(!this.collections[k]){this.collections[k]=this.db?{instance:this.db.collection(k)}:{};this.collections[k].reference={}}})}notificationStruct(parentStruct={}){let structType="notification";let struct={structType,timestamp:Date.now(),_id:randomId2(structType),note:"",alert:false,ownerId:"",parentUserId:"",parent:{structType:parentStruct?.structType,_id:getStringId(parentStruct?._id)}};return struct}async checkToNotify(user,structs=[],mode=this.mode){if(structs.length===0)return false;if(typeof user==="string"){for(let key in this.users){const obj=this.users[key];if(getStringId(obj._id)===user)user=obj}}if(typeof user==="string"||user==null)return false;let usersToNotify={};let newNotifications=[];structs.forEach(async struct=>{if(struct?._id){if(user?._id!==struct.ownerId){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id);newNotification.ownerId=struct.ownerId;newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[struct.ownerId]=struct.ownerId}if(struct.users){Object.keys(struct.users).forEach(usr=>{if(usr!==user._id){let newNotification=this.notificationStruct(struct);newNotification._id="notification_"+getStringId(struct._id);newNotification.ownerId=usr;newNotification.note=struct.structType;if(struct.alert)newNotification.alert=struct.alert;newNotification.parentUserId=struct.ownerId;newNotifications.push(newNotification);usersToNotify[usr]=usr}})}else{let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$or:[{authorizedId:user._id},{authorizerId:user._id}]});if(await s.count()>0){await s.forEach(d2=>auths.push(d2))}}else{auths=this.getLocalData("authorization",{authorizedId:user._id});auths.push(...this.getLocalData("authorization",{authorizerId:user._id}))}if(auths.length>0){auths.forEach(auth=>{if(struct.authorizerId===struct.ownerId&&!usersToNotify[struct.authorizedId]){if(auth.status==="OKAY"&&auth.authorizations["peer"]){let newNotification=this.notificationStruct(struct);newNotification.ownerId=auth.authorizedId;newNotification._id="notification_"+getStringId(struct._id);newNotification.note=struct.structType;newNotification.parentUserId=struct.ownerId;if(struct.alert)newNotification.alert=struct.alert;newNotifications.push(newNotification);usersToNotify[newNotification.ownerId]=newNotification.ownerId}}})}}}});if(newNotifications.length>0){if(mode.includes("mongo")){await this.setMongoData(user,newNotifications)}else{this.setLocalData(newNotifications)}for(const uid in usersToNotify){this.users[uid].send({route:"structNotification",args:true})}return true}else return false}async queryMongo(user,collection,queryObj={},findOne=false,skip=0){if(!collection&&!queryObj)return void 0;else if(findOne){let res=this.db.collection(collection).findOne(queryObj);if(!res)return void 0;let passed=!this.useAuths;if(!res?.ownerId){passed=true}else if(getStringId(user._id)!==res.ownerId||getStringId(user._id)===res.ownerId&&user.userRoles?.admincontrol){if(this.useAuths)passed=await this.checkAuthorization(user,res)}if(passed)return res;else return void 0}else{let res=await this.db.collection(collection).find(queryObj).sort({$natural:-1}).skip(skip);let structs=[];if(await res.count()>0){let passed=!this.useAuths;let checkedAuth="";await res.forEach(async s=>{if(!s?.ownerId){passed=true}else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed)structs.push(s)})}return structs}}async setMongoData(user,structs=[],notify=true){let firstwrite=false;if(structs.length>0){let passed=!this.useAuths;let checkedAuth="";await Promise.all(structs.map(async struct=>{let secondary={};if(Array.isArray(struct)){secondary=struct[1];struct=struct[0]}if(!struct?.ownerId)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");checkedAuth=struct.ownerId}if(passed){if(struct.structType){if(!this.collections[struct.structType]){this.collections[struct.structType]=this.db?{instance:this.db.collection(struct.structType)}:{};this.collections[struct.structType].reference={}}let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(struct._id){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType).insertOne(copy);firstwrite=true}else if(struct.structType==="notification")await this.db.collection(struct.structType).updateOne({parent:struct.parent,_id:struct._id},{$set:copy,...secondary},{upsert:true,unique:false});else await this.db.collection(struct.structType).updateOne({_id:toObjectID(struct._id)},{$set:copy,...secondary},{upsert:true})}else if(struct.structType){this.db.collection(struct.structType).insertOne(copy)}}}}));if(firstwrite===true){let toReturn=[];await Promise.all(structs.map(async(struct,j)=>{let copy=JSON.parse(JSON.stringify(struct));if(copy._id&©.structType!=="profile")delete copy._id;if(struct.structType!=="comment"){let pulled;if(struct.structType!=="notification")pulled=await this.db.collection(copy.structType).findOne(copy);if(pulled){pulled._id=getStringId(pulled._id);toReturn.push(pulled)}}else if(struct.structType==="comment"){let comment=struct;let copy2=JSON.parse(JSON.stringify(comment));if(copy2._id)delete copy2._id;let pulledComment=await this.db.collection("comment").findOne(copy2);let replyToId=pulledComment?.replyTo;let replyTo=structs.find(s=>{if(getStringId(s._id)===replyToId)return true});if(replyTo){let copy3=JSON.parse(JSON.stringify(replyTo));if(copy3._id)delete copy3._id;let pulledReply;await Promise.all(["discussion","chatroom","comment"].map(async name=>{let found=await this.db.collection(name).findOne({_id:toObjectID(replyToId)});if(found)pulledReply=found}));if(pulledReply){let roomId=getStringId(pulledComment.parent._id);let room,pulledRoom;if(roomId!==replyToId){room=structs.find(s=>{if(getStringId(s._id)===roomId)return true});if(room){delete room._id;await Promise.all(["discussion","chatroom"].map(async name=>{let found=await this.db.collection(name).findOne(room);if(found)pulledRoom=found}))}}else pulledRoom=pulledReply;let toUpdate=[pulledComment];if(pulledReply){let i=pulledReply.replies.indexOf(getStringId(pulledComment._id));if(i<0){pulledReply.replies.push(getStringId(pulledComment._id));pulledComment.replyTo=getStringId(pulledReply._id)}toUpdate.push(pulledReply)}if(pulledRoom){let i=pulledRoom.comments.indexOf(pulledComment._id);if(i<0){pulledRoom.comments.push(getStringId(pulledComment._id));pulledComment.parent._id=getStringId(pulledRoom._id)}}await Promise.all(toUpdate.map(async s=>{let copy4=JSON.parse(JSON.stringify(s));delete copy4._id;await this.db.collection(s.structType).updateOne({_id:toObjectID(s._id)},{$set:copy4},{upsert:false})}));[...toReturn].reverse().forEach((s,j2)=>{if(toUpdate.find(o=>{if(getStringId(s._id)===getStringId(o._id))return true})){toReturn.splice(toReturn.length-j2-1,1)}});toReturn.push(...toUpdate)}}else if(pulledComment){toReturn.push(pulledComment)}}}));if(notify)this.checkToNotify(user,toReturn);return toReturn}else{let non_notes=[];structs.forEach(s=>{if(s.structType!=="notification")non_notes.push(s)});if(notify)this.checkToNotify(user,non_notes);return true}}else return false}async setMongoUser(user,struct){if(struct._id){const _id=toObjectID(struct._id);let usersearch=_id!==struct._id?{_id}:{id:struct.id};let userexists=await this.collections.profile.instance.findOne(usersearch);if(userexists){if(getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(!passed)return false}}let copy=JSON.parse(JSON.stringify(struct));if(this.debug)console.log("RETURNS PROFILE",struct);await this.collections.profile.instance.updateOne(usersearch,{$set:copy},{upsert:true});user=await this.collections.profile.instance.findOne(usersearch);this.checkToNotify(user,[struct]);return user}else return false}async setGroup(user,struct,mode=this.mode){if(struct?._id){let exists=void 0;if(mode.includes("mongo")){exists=await this.collections.group.instance.findOne({name:struct.name})}else{exists=this.getLocalData("group",{_id:getStringId(struct._id)})}if(exists&&(exists.ownerId!==struct.ownerId||struct.admins.indexOf(getStringId(user._id))<0))return false;if(getStringId(user._id)!==struct.ownerId){let passed=!this.useAuths;if(!struct?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE");if(!passed)return false}let allusers=[];Object.keys(struct.users).forEach(u=>{allusers.push({email:u},{id:u},{username:u})});let users={};let ids={};if(mode.includes("mongo")){let cursor=this.collections.profile.instance.find({$or:allusers});if(await cursor.count()>0){await cursor.forEach(user2=>{users[getStringId(user2._id)]=user2;ids[getStringId(user2._id)]=true})}}else{allusers.forEach(search=>{let result=this.getLocalData("profile",search);if(result.length>0){users[getStringId(result[0]._id)]=result[0];ids[getStringId(result[0]._id)]=true}})}struct.users=ids;let admins={};let peers={};let clients={};Object.keys(users).forEach(id=>{let u=users[id];if(struct.admins[getStringId(u._id)]||struct.admins[u.email]||struct.admins[u.username]||struct.admins[struct.ownerId]){if(!admins[getStringId(u._id)])admins[getStringId(u._id)]=true}if(struct.peers[getStringId(u._id)]||struct.peers[u.email]||struct.peers[u.username]||struct.peers[struct.ownerId]){if(!peers[getStringId(u._id)])peers[getStringId(u._id)]=true}if(struct.clients[getStringId(u._id)]||struct.clients[u.email]||struct.clients[u.username]||struct.clients[struct.ownerId]){if(!clients[getStringId(u._id)])clients[getStringId(u._id)]=true}});struct.admins=admins;struct.peers=peers;struct.clients=clients;let copy=JSON.parse(JSON.stringify(struct));if(copy._id)delete copy._id;if(mode.includes("mongo")){if(getStringId(struct._id).includes("defaultId")){await this.db.collection(struct.structType).insertOne(copy);delete struct._id;struct=await this.db.collection(struct.structType).findOne(struct);struct._id=getStringId(struct._id)}else await this.collections.group.instance.updateOne({_id:toObjectID(struct._id)},{$set:copy},{upsert:true})}else{this.setLocalData(struct)}this.checkToNotify(user,[struct],this.mode);if(this.debug)console.log("setGroup: user:",user,"output",struct);return struct}else return false}async getMongoUser(user,info="",bypassAuth=false){return new Promise(async resolve=>{const query=[{email:info},{id:info},{username:info}];try{query.push({_id:toObjectID(info)})}catch(e){}let u=await this.collections.profile.instance.findOne({$or:query});if(!u||u==null)resolve({});else{u._id=getStringId(u._id);if(!u.ownerId)u.ownerId=u._id;if(u&&bypassAuth===false){if(getStringId(user._id)!==u._id||getStringId(user._id)===u._id&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,u);if(!passed)resolve(void 0)}let authorizations=[];let auths=this.collections.authorization.instance.find({ownerId:u._id});if(await auths.count()>0){await auths.forEach(d2=>authorizations.push(d2))}let gs=this.collections.group.instance.find({users:{$all:[u._id]}});let groups=[];if(await gs.count()>0){await gs.forEach(d2=>groups.push(d2))}resolve({user:u,authorizations,groups})}else resolve({user:u})}})}async getMongoUsersByIds(user,userIds=[]){let usrs=[];userIds.forEach(u=>{try{usrs.push({_id:toObjectID(u)})}catch{}});let found=[];if(usrs.length>0){let users=this.collections.profile.instance.find({$or:usrs});if(await users.count()>0){await users.forEach(u=>{found.push(u)})}}return found}async getMongoUsersByRole(user,role){let users=this.collections.profile.instance.find({userRoles:{$all:{[role]:true}}});let found=[];if(await users.count()>0){await users.forEach(u=>{found.push(u)})}return found}async getMongoDataByIds(user,structIds,ownerId,collection){if(structIds.length>0){let query=[];structIds.forEach(_id=>{let q={_id:toObjectID(_id)};if(ownerId)q.ownerId=ownerId;query.push(q)});let found=[];if(!collection){await Promise.all(Object.keys(this.collections).map(async name=>{let cursor=await this.db.collection(name).find({$or:query});if(await cursor.count()>0){let passed=true;let checkedAuth="";await cursor.forEach(async s=>{if(!s?.ownerId)passed=true;else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed)found.push(s)})}}))}else{let cursor=await this.db.collection(collection).find({$or:query});if(await cursor.count()>0){let passed=true;let checkedAuth="";await cursor.forEach(async s=>{if(!s?.ownerId)passed=true;else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed)found.push(s)})}}return found}}async getMongoData(user,collection,ownerId,dict={},limit=0,skip=0){if(!ownerId)ownerId=dict?.ownerId;if(!dict)dict={};if(dict._id)dict._id=toObjectID(dict._id);let structs=[];let passed=true;let checkedAuth="";if(!collection&&!ownerId&&!dict)return[];else if(!collection&&ownerId&&Object.keys(dict).length===0)return await this.getAllUserMongoData(user,ownerId);else if((!dict||Object.keys(dict).length===0)&&ownerId&&collection){let cursor=this.db.collection(collection).find({ownerId}).sort({$natural:-1}).skip(skip);if(limit>0)cursor.limit(limit);if(await cursor.count()>0){await cursor.forEach(async s=>{if(!s?.ownerId)passed=true;else if((getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==s.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,s);checkedAuth=s.ownerId}if(passed===true)structs.push(s)})}}else if(Object.keys(dict).length>0&&ownerId){let found=await this.db.collection(collection).findOne({ownerId,...dict});if(found)structs.push(found)}else if(Object.keys(dict).length>0&&!ownerId){await Promise.all(Object.keys(this.collections).map(async name=>{let found=await this.db.collection(name).findOne(dict);if(found){if(!found?.ownerId)passed=true;else if((getStringId(user._id)!==found.ownerId||getStringId(user._id)===found.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==found.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,found);checkedAuth=found.ownerId}structs.push(found);return}}))}if(!passed)return[];return structs}async getAllUserMongoData(user,ownerId,excluded=[]){let structs=[];let passed=true;let checkedId="";await Promise.all(Object.keys(this.collections).map(async(name,j)=>{if(passed&&excluded.indexOf(name)<0){let cursor=this.db.collection(name).find({ownerId});let count=await cursor.count();for(let k=0;k0){let checkedAuth="";structRefs.forEach(async ref=>{if(ref.structType&&getStringId(ref._id)){let struct=await this.db.collection(ref.structType).findOne({_id:toObjectID(ref._id)});if(struct){let passed=true;if(!struct?.ownerId)passed=true;else if((getStringId(user._id)!==struct.ownerId||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&checkedAuth!==struct.ownerId){if(this.useAuths)passed=await this.checkAuthorization(user,struct);checkedAuth=struct.ownerId}if(passed===true){structs.push(struct)}}}})}return structs}async getMongoAuthorizations(user,ownerId=getStringId(user._id),authId=""){let auths=[];if(authId.length===0){let cursor=this.collections.authorization.instance.find({ownerId});if(await cursor.count>0){await cursor.forEach(a=>{auths.push(a)})}}else auths.push(await this.collections.authorization.instance.findOne({_id:toObjectID(authId),ownerId}));if(!auths[0]?.ownerId)true;else if(getStringId(user._id)!==auths[0]?.ownerId){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,auths[0]);if(!passed)return void 0}return auths}async getMongoGroups(user,userId=getStringId(user._id),groupId=""){let groups=[];if(groupId.length===0){let cursor=this.collections.group.instance.find({users:{$all:[userId]}});if(await cursor.count>0){await cursor.forEach(a=>{groups.push(a)})}}else{try{groups.push(await this.collections.group.instance.findOne({_id:toObjectID(groupId),users:{$all:[userId]}}))}catch{}}return groups}async deleteMongoData(user,structRefs=[]){let structs=[];await Promise.all(structRefs.map(async ref=>{try{let _id=toObjectID(ref._id);let struct=await this.db.collection(ref.structType).findOne({_id});if(struct){structs.push(struct);let notifications=await this.collections.notifications.instance.find({parent:{structType:ref.structType,_id:getStringId(ref._id)}});let count=await notifications.count();for(let i=0;i{let passed=true;if(!struct?.ownerId)passed=true;else if((struct.ownerId!==getStringId(user._id)||getStringId(user._id)===struct.ownerId&&user.userRoles?.admincontrol)&&struct.ownerId!==checkedOwner){checkedOwner=struct.ownerId;if(this.useAuths)passed=await this.checkAuthorization(user,struct,"WRITE")}if(passed){await this.db.collection(struct.structType).deleteOne({_id:toObjectID(struct._id)});if(struct.users){Object.keys(struct.users).forEach(uid=>{if(uid!==getStringId(user._id)&&uid!==struct.ownerId&&this.users[uid])this.users[uid].send({route:"structDeleted",args:getStringId(struct._id)})})}if(struct.ownerId!==user._id&&this.users[struct.ownerId]){this.users[struct.ownerId].send({route:"structDeleted",args:getStringId(struct._id)})}}}));return true}async deleteMongoUser(user,userId){if(getStringId(user._id)!==userId||getStringId(user._id)===userId&&user.userRoles?.admincontrol){let u=await this.collections.profile.instance.findOne({id:userId});let passed=!this.useAuths;if(!u?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,u,"WRITE");if(!passed)return false}await this.collections.profile.instance.deleteOne({id:userId});if(getStringId(user._id)!==userId&&this.users[userId])this.users[userId].send({route:"structDeleted",args:userId});return true}async deleteMongoGroup(user,groupId){let s=await this.collections.group.instance.findOne({_id:toObjectID(groupId)});if(s){if(!s?.ownerId)true;else if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE");if(!passed)return false}if(s.users){Object.keys(s.users).forEach(u=>{this.users[s.authorizerId].send({route:"structDeleted",args:getStringId(s._id)})})}await this.collections.group.instance.deleteOne({_id:toObjectID(groupId)});return true}else return false}async deleteMongoAuthorization(user,authId){let s=await this.collections.authorization.instance.findOne({_id:toObjectID(authId)});if(s){if(getStringId(user._id)!==s.ownerId||getStringId(user._id)===s.ownerId&&user.userRoles?.admincontrol){let passed=!this.useAuths;if(!s?.ownerId)passed=true;else if(this.useAuths)passed=await this.checkAuthorization(user,s,"WRITE");if(!passed)return false}if(s.associatedAuthId){if(this.debug)console.log(s);await this.collections.authorization.instance.deleteOne({_id:toObjectID(s.associatedAuthId)});if(s.authorizerId&&s.authorizerId!==getStringId(user._id))this.users[s.authorizerId].send({route:"structDeleted",args:getStringId(s._id)});else if(s.authorizedId&&s.authorizedId!==getStringId(user._id))this.users[s.authorizerId].send({route:"structDeleted",args:getStringId(s._id)})}await this.collections.authorization.instance.deleteOne({_id:toObjectID(authId)});return true}else return false}async setAuthorization(user,authStruct,mode=this.mode){let u1,u2;if(mode.includes("mongo")){u1=(await this.getMongoUser(user,authStruct.authorizedId,true)).user;u2=(await this.getMongoUser(user,authStruct.authorizerId,true)).user}else{u1=this.getLocalData("profile",{"_id":authStruct.authorizedId})[0];u2=this.getLocalData("profile",{"_id":authStruct.authorizerId})[0]}if(!u1||!u2)return false;if(authStruct.authorizedId!==getStringId(u1._id))authStruct.authorizedId=getStringId(u1._id);if(authStruct.authorizerId!==getStringId(u2._id))authStruct.authorizerId=getStringId(u2._id);if(!authStruct.authorizedName){if(u1.username)authStruct.authorizedName=u1.username;else if(u1.email)authStruct.authorizedName=u1.email}if(!authStruct.authorizerName){if(u2.username)authStruct.authorizerName=u2.username;else if(u2.email)authStruct.authorizerName=u2.email}if(!authStruct?.ownerId)true;else if((getStringId(user._id)!==authStruct.ownerId||getStringId(user._id)===authStruct.ownerId&&user.userRoles?.admincontrol)&&(getStringId(user._id)!==authStruct.authorizedId&&getStringId(user._id)!==authStruct.authorizerId)){let passed=!this.useAuths;if(this.useAuths)passed=await this.checkAuthorization(user,authStruct,"WRITE");if(!passed)return false}let auths=[];if(mode.includes("mongo")){let s=this.collections.authorization.instance.find({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId}]});if(await s.count()>0){await s.forEach(d2=>auths.push(d2))}}else{let s=this.getLocalData("authorization",{authorizedId:authStruct.authorizedId});if(Array.isArray(s)){s.forEach(d2=>{if(d2.authorizerId===authStruct.authorizerId)auths.push(d2)})}}let otherAuthset;if(Array.isArray(auths)){auths.forEach(async auth=>{if(auth.ownerId===getStringId(user._id)){}else{if(authStruct.authorizerId===getStringId(user._id)){auth.authorizations=authStruct.authorizations;auth.structs=authStruct.structs;auth.excluded=authStruct.excluded;auth.expires=authStruct.expires;auth.status="OKAY";authStruct.status="OKAY"}else{authStruct.authorizations=auth.authorizations;authStruct.structs=auth.structs;authStruct.excluded=auth.excluded;authStruct.expires=auth.expires;auth.status="OKAY";authStruct.status="OKAY"}authStruct.associatedAuthId=getStringId(auth._id);auth.associatedAuthId=getStringId(authStruct._id);otherAuthset=auth;let copy2=JSON.parse(JSON.stringify(auth));if(mode.includes("mongo")){delete copy2._id;await this.collections.authorization.instance.updateOne({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId},{ownerId:auth.ownerId}]},{$set:copy2},{upsert:true})}else{this.setLocalData(copy2)}}})}let copy=JSON.parse(JSON.stringify(authStruct));if(mode.includes("mongo")){delete copy._id;await this.collections.authorization.instance.updateOne({$and:[{authorizedId:authStruct.authorizedId},{authorizerId:authStruct.authorizerId},{ownerId:authStruct.ownerId}]},{$set:copy},{upsert:true})}else{this.setLocalData(copy)}if(getStringId(authStruct._id).includes("defaultId")&&mode.includes("mongo")){let replacedAuth=await this.collections.authorization.instance.findOne(copy);if(replacedAuth){authStruct._id=getStringId(replacedAuth._id);if(otherAuthset){let otherAuth=await this.collections.authorization.instance.findOne({$and:[{authorizedId:otherAuthset.authorizedId},{authorizerId:otherAuthset.authorizerId},{ownerId:otherAuthset.ownerId}]});if(otherAuth){otherAuth.associatedAuthId=getStringId(authStruct._id);let copy2=JSON.parse(JSON.stringify(otherAuth));delete copy2._id;await this.collections.authorization.instance.updateOne({$and:[{authorizedId:otherAuth.authorizedId},{authorizerId:otherAuth.authorizerId},{ownerId:otherAuth.ownerId}]},{$set:copy2},{upsert:true});this.checkToNotify(user,[otherAuth])}}}}return authStruct}async checkAuthorization(user,struct,request="READ",mode=this.mode){if(!user||!struct)return false;if(!struct.ownerId)return true;if(typeof user==="object"){if(struct.ownerId===getStringId(user._id)){if(user.userRoles?.["admincontrol"]){}else return true}}else if(typeof user==="string"){if(struct.ownerId===user){return true}else user={_id:user}}let auth1,auth2;if(mode.includes("mongo")){auth1=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:getStringId(user._id)},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:getStringId(user._id)}]});auth2=await this.collections.authorization.instance.findOne({$or:[{authorizedId:getStringId(user._id),authorizerId:struct.ownerId,ownerId:struct.ownerId},{authorizedId:struct.ownerId,authorizerId:getStringId(user._id),ownerId:struct.ownerId}]})}else{auth1=this.getLocalData("authorization",{ownerId:getStringId(user._id)}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true});auth2=this.getLocalData("authorization",{ownerId:struct.ownerId}).find(o=>{if(o.authorizedId===getStringId(user._id)&&o.authorizerId===struct.ownerId)return true})}if(!auth1||!auth2){return false}let passed=false;if(auth1.status==="OKAY"&&auth2.status==="OKAY"){if(struct.structType==="group"){if(auth1.authorizations[struct.name+"_admin"]&&auth2.authorizations[struct.name+"_admin"])passed=true;else passed=false}else if(auth1.authorizations["peer"]&&auth2.authorizations["peer"])passed=true;else if(auth1.authorizations["admincontrol"]&&auth2.authorizations["admincontrol"])passed=true;else if(auth1.structIds[getStringId(struct._id)]&&auth2.structIds[getStringId(struct._id)])passed=true;else if(auth1.excluded[struct.structType]&&struct.ownerId===getStringId(user._id)&&request==="WRITE")passed=false}return passed}overwriteLocalData(structs){if(Array.isArray(structs)){structs.forEach(struct=>{let localdat=this.getLocalData(struct.structType,{"ownerId":struct.ownerId,"_id":getStringId(struct._id)});if(!localdat||localdat?.length===0){this.setLocalData(struct)}else Object.assign(localdat,struct)})}else{let localdat=this.getLocalData(structs.structType,{"ownerId":structs.ownerId,"_id":getStringId(structs._id)});if(!localdat||localdat?.length===0){this.setLocalData(structs)}else Object.assign(localdat,structs)}}setLocalData(structs){let setInCollection=s=>{let type=s.structType;let collection=this.collections[type]?.reference;if(!collection){collection={};if(!this.collections[type])this.collections[type]={};this.collections[type].reference=collection}collection[getStringId(s._id)]=s};if(Array.isArray(structs)){structs.forEach(s=>{setInCollection(s)})}else setInCollection(structs)}getLocalData(collection,query){let ownerId,key,value;if(typeof query==="object"){ownerId=query.ownerId;const keys=Object.keys(query).filter(k=>k!="ownerId");key=keys[0];value=query[key]}else value=query;if(!collection&&!ownerId&&!key&&!value)return[];let result=[];if(!collection&&(ownerId||key)){Object.values(this.collections).forEach(c=>{c=c.reference;if((key==="_id"||key==="id")&&value){let found=c[value];if(found)result.push(found)}else{Object.values(c).forEach(struct=>{if(key&&value){if(struct[key]===value&&struct.ownerId===ownerId){result.push(struct)}}else if(struct.ownerId===ownerId){result.push(struct)}})}});return result}else{let c=this.collections[collection]?.reference;if(!c)return result;if(!key&&!ownerId){Object.values(c).forEach(struct=>{result.push(struct)});return result}if((key==="_id"||key==="id")&&value)return getStringId(c[value]);else{Object.keys(c).forEach(k=>{const struct=c[k];if(key&&value&&!ownerId){if(struct[key]===value)result.push(struct)}else if(ownerId&&!key){if(struct.ownerId===ownerId)result.push(struct)}else if(ownerId&&key&&value){if(struct.ownerId===ownerId&&struct[key]){if(struct[key]===value)result.push(struct)}}})}}return result}deleteLocalData(struct){if(!struct)throw new Error("Struct not supplied");if(!struct.structType||!struct._id)return false;if(this.collections[struct.structType])delete this.collections[struct.structType].reference[struct._id];return true}};var Systems={collision:{setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))entity.collisionEnabled=true;if(!entity.collisionType)entity.collisionType="sphere";if(!entity.collisionRadius)entity.collisionRadius=1;if(!entity.collisionBoundsScale)entity.collisionBoundsScale={x:1,y:1,z:1};if(!entity.colliding)entity.colliding={};if(!entity.position)entity.position={x:0,y:0,z:0};return entity},__node:{tag:"collision"},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{if(body1.collisionEnabled===false||body2.collisionEnabled===false)return false;const dist=Systems.collision.distance(body1.position,body2.position);if(dist{if(dist===void 0)dist=Systems.collision.distance(body1.position,body2.position);return dist{let body1minX=(body1.position.x-body1.collisionRadius)*body1.collisionBoundsScale.x;let body1maxX=(body1.position.x+body1.collisionRadius)*body1.collisionBoundsScale.x;let body1minY=(body1.position.y-body1.collisionRadius)*body1.collisionBoundsScale.y;let body1maxY=(body1.position.y+body1.collisionRadius)*body1.collisionBoundsScale.y;let body1minZ=(body1.position.z-body1.collisionRadius)*body1.collisionBoundsScale.z;let body1maxZ=(body1.position.z+body1.collisionRadius)*body1.collisionBoundsScale.z;let body2minX=(body2.position.x-body2.collisionRadius)*body1.collisionBoundsScale.x;let body2maxX=(body2.position.x+body2.collisionRadius)*body1.collisionBoundsScale.x;let body2minY=(body2.position.y-body2.collisionRadius)*body1.collisionBoundsScale.y;let body2maxY=(body2.position.y+body2.collisionRadius)*body1.collisionBoundsScale.y;let body2minZ=(body2.position.z-body2.collisionRadius)*body1.collisionBoundsScale.z;let body2maxZ=(body2.position.z+body2.collisionRadius)*body1.collisionBoundsScale.z;return(body1maxX<=body2maxX&&body1maxX>=body2minX||body1minX<=body2maxX&&body1minX>=body2minX)&&(body1maxY<=body2maxY&&body1maxY>=body2minY||body1minY<=body2maxY&&body1minY>=body2minY)&&(body1maxZ<=body2maxZ&&body1maxZ>=body2minZ||body1minZ<=body2maxZ&&body1minZ>=body2minZ)},sphereBoxCollisionCheck:(sphere,box,dist)=>{let boxMinX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxMaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxMinY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.y;let boxMaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.y;let boxMinZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.z;let boxMaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.z;let clamp={x:Math.max(boxMinX,Math.min(sphere.position.x,boxMaxX)),y:Math.max(boxMinY,Math.min(sphere.position.y,boxMaxY)),z:Math.max(boxMinZ,Math.min(sphere.position.z,boxMaxZ))};if(dist===void 0)dist=Systems.collision.distance(sphere.position,clamp);return dist>sphere.collisionRadius},isPointInsideSphere:(point,sphere,dist)=>{if(dist===void 0)dist=Systems.collision.distance(point,sphere.position);return dist{let boxminX=(box.position.x-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxX=(box.position.x+box.collisionRadius)*box.collisionBoundsScale.x;let boxminY=(box.position.y-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxY=(box.position.y+box.collisionRadius)*box.collisionBoundsScale.x;let boxminZ=(box.position.z-box.collisionRadius)*box.collisionBoundsScale.x;let boxmaxZ=(box.position.z+box.collisionRadius)*box.collisionBoundsScale.x;return point.x>=boxminX&&point.x<=boxmaxX&&(point.y>=boxminY&&point.y<=boxmaxY)&&(point.z>=boxminZ&&point.z<=boxmaxZ)},closestPointOnLine:(point,lineStart,lineEnd)=>{let a={x:lineEnd.x-lineStart.x,y:lineEnd.y-lineStart.y,z:lineEnd.z-lineStart.z};let b2={x:lineStart.x-point.x,y:lineStart.y-point.y,z:lineStart.z-point.z};let c={x:lineEnd.x-point.x,y:lineEnd.y-point.y,z:lineEnd.z-point.z};let bdota=Systems.collision.dot(b2,a);if(bdota<=0)return lineStart;let cdota=Systems.collision.dot(c,a);if(cdota<=0)return lineEnd;let _bdotapluscdota=1/(bdota+cdota);return{x:lineStart.x+(lineEnd.x-lineStart.x)*bdota*_bdotapluscdota,y:lineStart.y+(lineEnd.y-lineStart.y)*bdota*_bdotapluscdota,z:lineStart.z+(lineEnd.z-lineStart.z)*bdota*_bdotapluscdota}},closestPointOnPolygon:(point,t0,t1,t2)=>{let n=Systems.collision.calcNormal(t0,t1,t2);let dist=Systems.collision.dot(point,n)-Systems.collision.dot(t0,n);let projection=Systems.collision.vecadd(point,Systems.collision.vecscale(n,-dist));let v0x=t2[0]-t0[0];let v0y=t2[1]-t0[1];let v0z=t2[2]-t0[2];let v1x=t1[0]-t0[0];let v1y=t1[1]-t0[1];let v1z=t1[2]-t0[2];let v2x=projection[0]-t0[0];let v2y=projection[1]-t0[1];let v2z=projection[2]-t0[2];let dot00=v0x*v0x+v0y*v0y+v0z*v0z;let dot01=v0x*v1x+v0y*v1y+v0z*v1z;let dot02=v0x*v2x+v0y*v2y+v0z*v2z;let dot11=v1x*v1x+v1y*v1y+v1z*v1z;let dot12=v1x*v2x+v1y*v2y+v1z*v2z;let denom=dot00*dot11-dot01*dot01;if(Math.abs(denom)<1e-30){return void 0}let _denom=1/denom;let u=(dot11*dot02-dot01*dot12)*_denom;let v2=(dot00*dot12-dot01*dot02)*_denom;if(u>=0&&v2>=0&&u+v2<1){return projection}else return void 0},calcNormal:(t0,t1,t2,positive=true)=>{var QR=Systems.collision.makeVec(t0,t1);var QS=Systems.collision.makeVec(t0,t2);if(positive===true){return Systems.collision.normalize(Systems.collision.cross3D(QR,QS))}else{return Systems.collision.normalize(Systems.collision.cross3D(QS,QR))}},dot:(v1,v2)=>{let dot=0;for(const key in v1){dot+=v1[key]*v2[key]}return dot},makeVec(p1,p2){return{x:p2.x-p1.x,y:p2.y-p1.y,z:p2.z-p1.z}},vecadd:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]+=v2[key]}return result},vecsub:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]-=v2[key]}return result},vecmul:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=v2[key]}return result},vecdiv:(v1,v2)=>{let result=Object.assign({},v1);for(const key in result){result[key]/=v2[key]}return result},vecscale:(v1,scalar)=>{let result=Object.assign({},v1);for(const key in result){result[key]*=scalar}return result},distance:(v1,v2)=>{let distance=0;for(const key in v1){distance+=Math.pow(v1[key]-v2[key],2)}return Math.sqrt(distance)},magnitude:v2=>{let magnitude=0;for(const key in v2){magnitude+=v2[key]*v2[key]}return Math.sqrt(magnitude)},normalize:v2=>{let magnitude=Systems.collision.magnitude(v2);let _mag=magnitude?1/magnitude:0;let vn=Object.assign({},v2);for(const key in v2){vn[key]=v2[key]*_mag}return vn},distance3D(v1,v2){return Math.sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)+(v1.z-v2.z)*(v1.z-v2.z))},cross3D(v1,v2){return{x:v1.y*v2.z-v1.z*v2.y,y:v1.z*v2.x-v1.x*v2.z,z:v1.x*v2.y-v1.y*v2.x}},nearestNeighborSearch(entities,isWithinRadius=1e15){var tree={};;for(const key in entities){let newnode={tag:key,position:void 0,neighbors:[]};newnode.position=entities[key].position;tree[key]=newnode}for(const i in tree){for(const j in tree){var dist=Systems.collision.distance3D(tree[i].position,tree[j].position);if(distxx)minX=xx;if(maxYyy)minY=yy;if(maxZzz)minZ=zz;if(minRadius>body.collisionRadius)minRadius=body.collisionRadius;positions[key]=body.position};let head=JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto));let boxpos={x:(maxX+minX)*.5,y:(maxY+minY)*.5,z:(maxZ+minZ)*.5};let boxbounds={x:maxX-boxpos.x,y:maxY-boxpos.y,z:maxZ-boxpos.z};head.position=boxpos;head.collisionBoundsScale=boxbounds;head.entities=entities;dynamicBoundingVolumeTree.tree=head;minRadius*=2;if(mode==="octree"){let genOct=function(parentPos,halfbounds){let oct1={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct2={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z+halfbounds.z};let oct3={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct4={x:parentPos.x+halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct5={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z+halfbounds.z};let oct6={x:parentPos.x-halfbounds.x,y:parentPos.y+halfbounds.y,z:parentPos.z-halfbounds.z};let oct7={x:parentPos.x+halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};let oct8={x:parentPos.x-halfbounds.x,y:parentPos.y-halfbounds.y,z:parentPos.z-halfbounds.z};return[oct1,oct2,oct3,oct4,oct5,oct6,oct7,oct8]},genOctTree=function(head2){let halfbounds={x:head2.collisionBoundsScale.x*.5,y:head2.collisionBoundsScale.y*.5,z:head2.collisionBoundsScale.z*.5};let octPos=genOct(head2.position,halfbounds);let check=Object.assign({},head2.bodies);for(let i=0;i<8;i++){let octquadrant=Object.assign(JSON.parse(JSON.stringify(dynamicBoundingVolumeTree.proto)),{position:octPos[i],collisionBoundsScale:halfbounds});octquadrant.parent=head2;for(const j in check){let collided=Systems.collision.collisionCheck(check[j],octquadrant);if(collided){octquadrant.entities[j]=check[j];delete check[j]}}if(Object.keys(octquadrant.entities).length>minEntities-1){head2.children[i]=octquadrant;octquadrant.parent=head2;if(Object.keys(octquadrant.entities).length>minEntities&&octquadrant.collisionRadius*.5>minRadius){genOctTree(octquadrant)}}}};genOctTree(head);return head}else{let tree=Systems.collision.nearestNeighborSearch(positions,withinRadius);let keys=Object.keys(tree);let tag=keys[Math.floor(Math.random()*keys.length)];let searching=true;let count=0;let genBoundingBoxLevel=(tree2,volumes)=>{let newVolumes={};let foundidxs={};let treekeys=Object.keys(tree2);while(searching&&countuxn)ux=uxn;if(mxuyn)uy=uyn;if(myuzn)uz=uzn;if(mz2){let nextTree=Systems.collision.nearestNeighborSearch(result,withinRadius);result=genBoundingBoxLevel(nextTree,result)}head.children=result;head.children.forEach(n=>{n.parent=head});return head}}},collider:{lastTime:performance.now(),setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collision.setupEntity(entity);if(!("boundingBox"in entity))entity.boundingBox={bot:0,top:100,left:0,right:100,front:0,back:100};if(!("position"in entity)){Systems.movement.setupEntity(entity)}if(!("restitution"in entity))entity.restitution=1;if(!("useBoundingBox"in entity))entity.useBoundingBox=true;if(!entity.position.x&&!entity.position.y&&!entity.position.z){entity.position.x=Math.random()*entity.boundingBox.right;entity.position.y=Math.random()*entity.boundingBox.back;entity.position.z=Math.random()*entity.boundingBox.top}return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;i{const xsize=entity.collisionRadius*entity.collisionBoundsScale.x;const ysize=entity.collisionRadius*entity.collisionBoundsScale.y;const zsize=entity.collisionRadius*entity.collisionBoundsScale.z;if(entity.position.y-ysize<=entity.boundingBox.front){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.front+ysize}if(entity.position.y+ysize>=entity.boundingBox.back){entity.velocity.y*=-entity.restitution;entity.position.y=entity.boundingBox.back-ysize}if(entity.position.x-xsize<=entity.boundingBox.left){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.left+xsize}if(entity.position.x+xsize>=entity.boundingBox.right){entity.velocity.x*=-entity.restitution;entity.position.x=entity.boundingBox.right-xsize}if(entity.position.z-zsize<=entity.boundingBox.bot){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.bot+zsize}if(entity.position.z+zsize>=entity.boundingBox.top){entity.velocity.z*=-entity.restitution;entity.position.z=entity.boundingBox.top-zsize}},resolveBoxCollision:(body1,box,negate)=>{let positionVec=Systems.collision.makeVec(body1.position,box.position);var directionVec=Object.values(positionVec);let closestSide;let closestDist=Infinity;let mul=-1;if(directionVec[idx]<0)mul=1;if(negate)mul=-mul;for(const key in body1.position){let dist=Math.abs(box.position[key]-body1.position[key]);if(dist{if(dist===void 0)dist=Systems.collision.distance(entity1.position,entity2.position);let vecn=Systems.collision.normalize(Systems.collision.makeVec(entity1.position,entity2.position));let sumMass=entity1.mass+entity2.mass;let ratio=entity1.mass/sumMass;let rmin=1-ratio;if(entity1.fixed===false){entity1.position.x+=vecn.x*rmin*1.01;entity1.position.y+=vecn.y*rmin*1.01;entity1.position.z+=vecn.z*rmin*1.001}else{entity2.position.x-=vecn.x*1.01;entity2.position.y-=vecn.y*1.01;entity2.position.z-=vecn.z*1.01}if(entity2.fixed===false){entity2.position.x+=vecn.x*ratio*1.01;entity2.position.y+=vecn.y*ratio*1.01;entity2.position.z+=vecn.z*ratio*1.01}else{entity1.position.x+=vecn.x*1.01;entity1.position.y+=vecn.y*1.01;entity1.position.z+=vecn.z*1.01}dist=Systems.collision.distance(entity1.position,entity2.position);let vrel={x:entity1.velocity.x-entity2.velocity.x,y:entity1.velocity.y-entity2.velocity.y,z:entity1.velocity.z-entity2.velocity.z};let speed=vrel.x*vecn.x+vrel.y*vecn.y+vrel.z*vecn.z;if(speed>0){let impulse=2*speed/sumMass;if(entity1.fixed===false){entity1.velocity.x-=impulse*vecn.x*entity2.mass*entity1.restitution;entity1.velocity.y-=impulse*vecn.y*entity2.mass*entity1.restitution;entity1.velocity.z-=impulse*vecn.z*entity2.mass*entity1.restitution}if(entity2.fixed===false){entity2.velocity.x+=impulse*vecn.x*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.y+=impulse*vecn.y*entity2.mass*entity2.restitution/entity2.mass;entity2.velocity.z+=impulse*vecn.z*entity2.mass*entity2.restitution/entity2.mass}}}},nbody:{lastTime:performance.now(),G:6674e-14,setupEntities:function(entities){for(const key in entities){const entity=entities[key];if(entity.components){if(!entity.components[this.__node.tag])continue}this.setupEntity(entity)}return entities},setupEntity:function(entity){if(!("collisionEnabled"in entity))Systems.collider.setupEntity(entity);entity.isAttractor=true;if(!("attractorGroup"in entity))entity.attractorGroup=0;if(!("attractorFrameSearchMax"in entity))entity.attractorFrameSearchMax=10;if(!("attractorGroupRules"in entity))entity.attractorGroupRules={0:{G:this.G,maxDist:void 0}};return entity},__operator:function(entities){let keys=this.entityKeys;for(let i=0;ientity.attractorFrameSearchMax)break nested}}return entities},__node:{tag:"nbody"},attract:function(body1,body2,dist,G=this.G,vecn){if(dist===void 0)dist=Systems.collision.distance3D(body1.position,body2.position);if(vecn===void 0)vecn=Systems.collision.normalize(Systems.collision.makeVec(body1.position,body2.position));let Fg=0;if(dist<.01)dist=.01;if(body1.attractorGroupRules[body2.attractorGroup]){if(typeof body1.attractorGroupRules[body2.attractorGroup]==="object"){if(body1.attractorGroupRules[body2.attractorGroup].maxDist&&body1.attractorGroupRules[body2.attractorGroup].maxDist1e3){entity.boid.groupSize=1;entity.boid.searchLimit=1}return entity},__operator:function(entities){let now=performance.now();let timeStep=now-this.lastTime;this.lastTime=now;let keys=this.entityKeys;let length=keys.length;let _timeStep=1/timeStep;let w2=-1;outer:for(let i=0;ip0.boid.groupSize||k>p0.boid.searchLimit){break nested}let randj=keys[Math.floor(Math.random()*length)];if(k===w2||randj===keys[i]||inRange.indexOf(randj)>-1){continue nested}else{let pr=entities[randj];let disttemp=Math.sqrt((p0.position.x-pr.position.x)*(p0.position.x-pr.position.x)+(p0.position.y-pr.position.y)*(p0.position.y-pr.position.y)+(p0.position.z-pr.position.z)*(p0.position.z-pr.position.z));if(disttemp>p0.boid.groupRadius){continue nested}else{distances.push(disttemp);inRange.push(randj);let distInv;if(p0.boid.useSeparation||p0.boid.useAlignment){distInv=p0.boid.groupRadius/(disttemp*disttemp);if(distInv>p0.maxSpeed)distInv=p0.maxSpeed;else if(distInv<-p0.maxSpeed)distInv=-p0.maxSpeed}if(p0.boid.useCohesion){boidVelocities[0]+=(pr.position.x-p0.position.x)*.5*disttemp*_timeStep;boidVelocities[1]+=(pr.position.y-p0.position.y)*.5*disttemp*_timeStep;boidVelocities[2]+=(pr.position.z-p0.position.z)*.5*disttemp*_timeStep}if(isNaN(disttemp)||isNaN(boidVelocities[0])||isNaN(pr.position.x)){console.log(disttemp,i,randj,p0.position,pr.position,boidVelocities);p0.position.x=NaN;return}if(p0.boid.useSeparation){boidVelocities[3]=boidVelocities[3]+(p0.position.x-pr.position.x)*distInv;boidVelocities[4]=boidVelocities[4]+(p0.position.y-pr.position.y)*distInv;boidVelocities[5]=boidVelocities[5]+(p0.position.z-pr.position.z)*distInv}if(p0.boid.useAttraction&&pr.boid.useAttraction){Systems.nbody.attract(p0,pr,disttemp)}if(p0.boid.useAlignment){boidVelocities[6]=boidVelocities[6]+pr.velocity.x*distInv;boidVelocities[7]=boidVelocities[7]+pr.velocity.y*distInv;boidVelocities[8]=boidVelocities[8]+pr.velocity.z*distInv}groupCount++}}}let _groupCount=1/groupCount;if(p0.boid.useCohesion){boidVelocities[0]=p0.boid.cohesion*(boidVelocities[0]*_groupCount);boidVelocities[1]=p0.boid.cohesion*(boidVelocities[1]*_groupCount);boidVelocities[2]=p0.boid.cohesion*(boidVelocities[2]*_groupCount)}else{boidVelocities[0]=0;boidVelocities[1]=0;boidVelocities[2]=0}if(p0.boid.useSeparation){boidVelocities[3]=p0.boid.separation*boidVelocities[3];boidVelocities[4]=p0.boid.separation*boidVelocities[4];boidVelocities[5]=p0.boid.separation*boidVelocities[5]}else{boidVelocities[3]=0;boidVelocities[4]=0;boidVelocities[5]=0}if(p0.boid.useAlignment){boidVelocities[6]=-(p0.boid.alignment*boidVelocities[6]*_groupCount);boidVelocities[7]=p0.boid.alignment*boidVelocities[7]*_groupCount;boidVelocities[8]=p0.boid.alignment*boidVelocities[8]*_groupCount}else{boidVelocities[6]=0;boidVelocities[7]=0;boidVelocities[8]=0}const swirlVec=[0,0,0];if(p0.boid.useSwirl==true){boidVelocities[9]=-(p0.position.y-p0.boid.swirl.y)*p0.boid.swirl.mul;boidVelocities[10]=(p0.position.z-p0.boid.swirl.z)*p0.boid.swirl.mul;boidVelocities[11]=(p0.position.x-p0.boid.swirl.x)*p0.boid.swirl.mul}const attractorVec=[0,0,0];if(p0.boid.useAttractor==true){boidVelocities[12]=(p0.boid.attractor.x-p0.position.x)*p0.boid.attractor.mul;if(p0.position.x>p0.boundingBox.left||p0.position.xp0.boundingBox.top||p0.position.yp0.boundingBox.front||p0.position.z0){let magnitude=Systems.collision.magnitude(entity.velocity);if(magnitude>entity.maxSpeed){let scalar=entity.maxSpeed/magnitude;entity.velocity.x*=scalar;entity.velocity.y*=scalar;entity.velocity.z*=scalar}}if(entity.velocity.x)entity.position.x+=entity.velocity.x*timeStep;if(entity.velocity.y)entity.position.y+=entity.velocity.y*timeStep;if(entity.velocity.z)entity.position.z+=entity.velocity.z*timeStep}return entities}}};var b=class{constructor(e,t,s,h){this.r=e,this.g=t,this.b=s,this.a=h}};var x2=class{constructor(){this.scaleX=1,this.scaleY=1,this.offsetX=0,this.offsetY=0,this.loop=false,this._vbuffer=0,this._coord=0,this.visible=true,this.intensity=1,this.xy=new Float32Array([]),this.numPoints=0,this.color=new b(0,0,0,1),this.webglNumPoints=0}};var v=class extends x2{constructor(e,t){super(),this.currentIndex=0,this.webglNumPoints=t,this.numPoints=t,this.color=e,this.xy=new Float32Array(2*this.webglNumPoints)}setX(e,t){this.xy[e*2]=t}setY(e,t){this.xy[e*2+1]=t}getX(e){return this.xy[e*2]}getY(e){return this.xy[e*2+1]}lineSpaceX(e,t){for(let s=0;s{let s={x:0,y:0};return s.x=c.x+e.x*t,s.y=c.y+e.y*t,s};var _=c=>P(-c.y,c.x);var w=(c,e)=>{let t=T(c,e);return t=M(t),t};var S=(c,e)=>{let t={x:0,y:0};return t.x=c.x+e.x,t.y=c.y+e.y,t};var R=(c,e)=>c.x*e.x+c.y*e.y;var M=c=>{let e={x:0,y:0},t=c.x*c.x+c.y*c.y;return t>0&&(t=1/Math.sqrt(t),e.x=c.x*t,e.y=c.y*t),e};var P=(c,e)=>{let t={x:0,y:0};return t.x=c,t.y=e,t};var T=(c,e)=>{let t={x:0,y:0};return t.x=c.x-e.x,t.y=c.y-e.y,t};var C=c=>{let e,t={x:0,y:0},s={x:0,y:0},h=[],r=(n,l)=>{h.push({vec2:n,miterLength:l})},a=n=>({x:c[n*2],y:c[n*2+1]});t=w(a(1),a(0)),e=_(t),r(e,1);let o=c.length/2;for(let n=1;n{let t=S(c,e);return t=M(t),P(-t.y,t.x)};var N=(c,e,t)=>{let s=P(-c.y,c.x);return t/R(e,s)};var d=class extends x2{constructor(e,t,s){super(),this.currentIndex=0,this._thicknessRequested=0,this._actualThickness=0,this.webglNumPoints=t*2,this.numPoints=t,this.color=e,this._thicknessRequested=s,this._linePoints=new Float32Array(t*2),this.xy=new Float32Array(2*this.webglNumPoints)}convertToTriPoints(){let e=this._actualThickness/2,t=C(this._linePoints);for(let s=0;s{if(s.visible){t.useProgram(this._progLine);let h=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(h,false,new Float32Array([s.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,s.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let r=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(r,new Float32Array([s.offsetX+this.gOffsetX,s.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let o=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(o,[s.color.r,s.color.g,s.color.b,s.color.a]),t.bufferData(t.ARRAY_BUFFER,s.xy,t.STREAM_DRAW),t.drawArrays(s.loop?t.LINE_LOOP:t.LINE_STRIP,0,s.webglNumPoints)}})}_drawSurfaces(e){let t=this.webgl;e.forEach(s=>{if(s.visible){t.useProgram(this._progLine);let h=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(h,false,new Float32Array([s.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,s.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let r=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(r,new Float32Array([s.offsetX+this.gOffsetX,s.offsetY+this.gOffsetY]));let a=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(a,new Int32Array([this.gLog10X?1:0,this.gLog10Y?1:0]));let o=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(o,[s.color.r,s.color.g,s.color.b,s.color.a]),t.bufferData(t.ARRAY_BUFFER,s.xy,t.STREAM_DRAW),t.drawArrays(t.TRIANGLE_STRIP,0,s.webglNumPoints)}})}_drawTriangles(e){let t=this.webgl;t.bufferData(t.ARRAY_BUFFER,e.xy,t.STREAM_DRAW),t.useProgram(this._progLine);let s=t.getUniformLocation(this._progLine,"uscale");t.uniformMatrix2fv(s,false,new Float32Array([e.scaleX*this.gScaleX*(this.gLog10X?1/Math.log(10):1),0,0,e.scaleY*this.gScaleY*this.gXYratio*(this.gLog10Y?1/Math.log(10):1)]));let h=t.getUniformLocation(this._progLine,"uoffset");t.uniform2fv(h,new Float32Array([e.offsetX+this.gOffsetX,e.offsetY+this.gOffsetY]));let r=t.getUniformLocation(this._progLine,"is_log");t.uniform2iv(r,new Int32Array([0,0]));let a=t.getUniformLocation(this._progLine,"uColor");t.uniform4fv(a,[e.color.r,e.color.g,e.color.b,e.color.a]),t.drawArrays(t.TRIANGLE_STRIP,0,e.xy.length/2)}_drawThickLines(){this._thickLines.forEach(e=>{if(e.visible){let t=Math.min(this.gScaleX,this.gScaleY);e.setActualThickness(e.getThickness()/t),e.convertToTriPoints(),this._drawTriangles(e)}})}update(){this.clear(),this.draw()}draw(){this._drawLines(this.linesData),this._drawLines(this.linesAux),this._drawThickLines(),this._drawSurfaces(this.surfaces)}clear(){this.webgl.clear(this.webgl.COLOR_BUFFER_BIT)}_addLine(e){e._vbuffer=this.webgl.createBuffer(),this.webgl.bindBuffer(this.webgl.ARRAY_BUFFER,e._vbuffer),this.webgl.bufferData(this.webgl.ARRAY_BUFFER,e.xy,this.webgl.STREAM_DRAW),e._coord=this.webgl.getAttribLocation(this._progLine,"coordinates"),this.webgl.vertexAttribPointer(e._coord,2,this.webgl.FLOAT,false,0,0),this.webgl.enableVertexAttribArray(e._coord)}addDataLine(e){this._addLine(e),this.linesData.push(e)}addAuxLine(e){this._addLine(e),this.linesAux.push(e)}addThickLine(e){this._addLine(e),this._thickLines.push(e)}addSurface(e){this._addLine(e),this.surfaces.push(e)}initThinLineProgram(){let e=` + attribute vec2 coordinates; + uniform mat2 uscale; + uniform vec2 uoffset; + uniform ivec2 is_log; + + void main(void) { + float x = (is_log[0]==1) ? log(coordinates.x) : coordinates.x; + float y = (is_log[1]==1) ? log(coordinates.y) : coordinates.y; + vec2 line = vec2(x, y); + gl_Position = vec4(uscale*line + uoffset, 0.0, 1.0); + }`,t=this.webgl.createShader(this.webgl.VERTEX_SHADER);this.webgl.shaderSource(t,e),this.webgl.compileShader(t);let s=` + precision mediump float; + uniform highp vec4 uColor; + void main(void) { + gl_FragColor = uColor; + }`,h=this.webgl.createShader(this.webgl.FRAGMENT_SHADER);this.webgl.shaderSource(h,s),this.webgl.compileShader(h),this._progLine=this.webgl.createProgram(),this.webgl.attachShader(this._progLine,t),this.webgl.attachShader(this._progLine,h),this.webgl.linkProgram(this._progLine)}popDataLine(){this.linesData.pop()}removeAllLines(){this._linesData=[],this._linesAux=[],this._thickLines=[],this._surfaces=[]}removeDataLines(){this._linesData=[]}removeAuxLines(){this._linesAux=[]}viewport(e,t,s,h){this.webgl.viewport(e,t,s,h)}log(e){this.debug&&console.log("[webgl-plot]:"+e)}};var y=class{constructor(){this.plots={}}initPlot(e,t){if(t||(t=new A(e.canvas,e.webglOptions)),!e._id)e._id=`plot${Math.floor(Math.random()*1e15)}`;else if(this.plots[e._id]){let l=this.plots[e._id].initial;if(e.lines){for(let i in e.lines)if(l.lines[i]&&Array.isArray(e.lines[i])){let f=e.lines[i];e.lines[i]=l.lines[i]}}e=Object.assign(l,e)}e.overlay&&(typeof e.overlay!="object"&&(e.overlay=document.createElement("canvas"),e.overlay.style.position="absolute",e.overlay.width=e.canvas.width,e.overlay.height=e.canvas.height,e.canvas.appendChild(e.overlay)),e.overlayCtx||(e.overlayCtx=e.overlay.getContext("2d"))),e.width&&(e.canvas.width=e.width,e.canvas.style&&(e.canvas.style.width=e.width+"px"),typeof e.overlay=="object"&&(e.overlay.width=e.width,e.overlay.style&&(e.overlay.style.width=e.width+"px"))),e.height&&(e.canvas.height=e.height,e.canvas.style&&(e.canvas.style.height=e.height+"px"),typeof e.overlay=="object"&&(e.overlay.height=e.height,e.overlay.style&&(e.overlay.style.height=e.height+"px"))),e.lines?.timestamp&&delete e.lines.timestamp;let s={};for(let l in e.lines)s[l]=Object.assign({},s[l]),"viewing"in e.lines[l]||(e.lines[l].viewing=true),s[l].viewing=e.lines[l].viewing,s[l].sps=e.lines[l].sps,s[l].nSec=e.lines[l].nSec,s[l].nPoints=e.lines[l].nPoints,s[l].ymin=e.lines[l].ymin,s[l].ymax=e.lines[l].ymax,s[l].units=e.lines[l].units;let h={plot:t,settings:e,initial:Object.assign(Object.assign({},e),{lines:s}),anim:()=>{t.update()}};this.plots[e._id]=h;let r=0,a=0;Object.keys(e.lines).forEach(l=>{e.lines[l]?.viewing!==false&&a++}),e.nLines=a;let o,n;typeof e.overlay=="object"&&(o=e.overlay,n=e.overlayCtx,n.clearRect(0,0,e.overlay.width,e.overlay.height),n.font=e.overlayFont?e.overlayFont:"1em Courier",n.fillStyle=e.overlayColor?e.overlayColor:"white");for(let l in e.lines){let i=e.lines[l];if(Array.isArray(i)&&(i={values:i},e.lines[l]=i),"viewing"in i||(i.viewing=true),i.color)Array.isArray(i.color)&&(i.color=new b(...i.color));else{let m=y.HSLToRGB(360*(r/a)%360,100,50,1);h.initial.lines[l].color=[...m,1],i.color=new b(...m,1)}let f;if(i.nSec&&i.sps?f=Math.ceil(i.nSec*i.sps):i.nPoints?f=i.nPoints:i.points?f=i.points:e.linePoints?f=e.linePoints:i.values?f=i.values.length:f=1e3,i.points=f,e.lines[l].viewing===false)continue;if((i.width||e.lineWidth)&&i.width!==0){let m=e.lineWidth;m||(m=i.width),i.width?i.line=new d(i.color,f,i.width):e.lineWidth&&(i.line=new d(i.color,f,e.lineWidth)),i.line.lineSpaceX(-1,2/i.line.numPoints)}else i.line=new v(i.color,f),i.line.arrangeX();i.values?.length===i.points?i.values.length!==f&&(i.interpolate?i.values.length>f?i.values=y.downsample(i.values,f):i.values.lengthi.points?i.values=i.values.slice(i.values.length-i.points):i.values=[...new Array(i.points-i.values.length).fill(0),...i.values]):Array.isArray(i.values)?i.values=[...new Array(f-i.values.length).fill(0),...i.values]:i.values=new Array(i.points).fill(0);let u=i.ymin,g=i.ymax;if(u===g?(g=i.values.length<=1e5?Math.max(...i.values):1,u=i.values.length<=1e5?Math.min(...i.values):0):isNaN(g)&&(g=i.values.length<=1e5?Math.max(...i.values):1),isNaN(u)&&(u=i.values.length<=1e5?Math.min(...i.values):0),u>g){let m=u;g=u,u=m}let p=Math.abs(u);if(i.absmax=p>g?p:g,"autoscale"in i||(i.autoscale=true),i.position||(i.position=e.nLines-r-1),i.autoscale?i.autoscale===2?("clamp"in i||(i.clamp=true),i.scaled=y.autoscale(i.values,i.position,a,i.centerZero,u,g,i.clamp)):(i.scaled=i.values,i.line.scaleY=y.getYScalar(i.values,a,i.centerZero,u,g),i.line.offsetY=y.getYOffset(i.position,a,u,i.line.scaleY)):i.scaled=i.values,i.scaled.forEach((m,L)=>i.line.setY(L,m)),i.line instanceof d?t.addThickLine(i.line):i.line instanceof v&&t.addDataLine(i.line),"xAxis"in i||(i.xAxis=true),i.xAxis){i.xColor?Array.isArray(i.xColor)&&(i.xColor=new b(...i.xColor)):i.xColor=new b(1,1,1,.3);let m=new v(i.xColor,2),L=i.autoscale?(r+1)*2/a-1-1/a:0;m.constY(L),m.arrangeX(),m.xy[2]=1,i.x=m,t.addAuxLine(m)}if(a>1&&i.autoscale&&r!==a-1){e.dividerColor?Array.isArray(e.dividerColor)&&(e.dividerColor=new b(...e.dividerColor)):e.dividerColor=new b(1,1,1,1);let m=new v(e.dividerColor,2);m.constY(i.autoscale?(r+1)*2/a-1:1),m.arrangeX(),m.xy[2]=1,i.divider=m,t.addAuxLine(m)}if(typeof e.overlay=="object"&&(i.useOverlay||!("useOverlay"in i))){let m=e.nLines-i.position-1;n.fillText(l,20,o.height*(m+.2)/e.nLines),n.fillText(`${Math.floor(g)===g?g:g?.toFixed(5)} ${i.units?i.units:""}`,o.width-100,o.height*(m+.2)/e.nLines),n.fillText(`${Math.floor(u)===u?u:u?.toFixed(5)} ${i.units?i.units:""}`,o.width-100,o.height*(m+.9)/e.nLines)}r++}return requestAnimationFrame(h.anim),this.plots[e._id]}deinitPlot(e){return typeof e=="string"&&(e=this.plots[e]),e.plot.clear(),e.plot.removeAllLines(),true}reinitPlot(e,t){if(typeof e=="string"){let s=e;e=this.plots[e],t._id||(t._id=s)}if(!!e.plot)return e.plot.clear(),e.plot.removeAllLines(),e.settings.overlayCtx&&e.settings.overlayCtx.clearRect(0,0,e.settings.overlay?.width,e.settings.overlay?.height),this.initPlot(t,e.plot)}getChartSettings(e,t){let s=this.plots[e];if(s){let h=Object.assign({},s.initial);for(let r in s.initial.lines)typeof s.initial.lines[r]?.ymax!="number"&&(h.lines[r].ymax=s.settings.lines[r]?.ymax),typeof s.initial.lines[r]?.ymin!="number"&&(h.lines[r].ymin=s.settings.lines[r]?.ymin),t&&(h.lines[r].values=s.settings.lines[r].values);return delete h.canvas,delete h.overlay,delete h.overlayCtx,h}}update(e,t,s=true){if(typeof e=="string"&&(e=this.plots[e]),!e)return false;if(t){let h=false,r,a;typeof e.settings.overlay=="object"&&(r=e.settings.overlay,a=e.settings.overlayCtx,a.font=e.settings.overlayFont?e.settings.overlayFont:"1em Courier",a.fillStyle=e.settings.overlayColor?e.settings.overlayColor:"white");for(let o in t)if(e.settings.lines[o]&&e.settings.lines[o].line){if(e.settings.lines[o]?.viewing===false)continue;let n=e.settings.lines[o];if(Array.isArray(t[o])&&n.values.length<1e5?t[o].length===n.values.length?n.values=t[o]:y.circularBuffer(n.values,t[o]):typeof t[o]=="number"?(n.values.push(t[o]),n.values.shift()):t[o]?.values&&(t[o].values.length===n.values.length?n.values=t[o].values:y.circularBuffer(n.values,t[o].values)),n.values){n.values.length!==n.points&&(n.interpolate?n.values.length>n.points?n.values=y.downsample(n.values,n.points):n.scaled.lengthn.points?n.values.splice(0,n.values.length-n.points):n.values=new Array(n.points).fill(0).splice(n.points-n.values.length,0,n.values));let l=n.ymin,i=n.ymax;if(l===i?(i=n.values.length<=1e5?Math.max(...n.values):1,l=n.values.length<=1e5?Math.min(...n.values):0):isNaN(i)&&(i=n.values.length<=1e5?Math.max(...n.values):1),isNaN(l)&&(l=n.values.length<=1e5?Math.min(...n.values):0),l>i){let u=l;i=l,l=u}let f=Math.abs(l);if(n.absmax=f>i?f:i,n.autoscale?n.autoscale===2?n.scaled=y.autoscale(n.values,n.position,e.settings.nLines,n.centerZero,l,i,n.clamp):(n.scaled=n.values,n.line.scaleY=y.getYScalar(n.values,e.settings.nLines,n.centerZero,l,i),n.line.offsetY=y.getYOffset(n.position,e.settings.nLines,l,n.line.scaleY)):n.scaled=n.values,n.scaled.forEach((u,g)=>{!n.autoscale&&n.absmax>1?n.line.setY(g,u/n.absmax):n.line.setY(g,u)}),typeof e.settings.overlay=="object"&&(n.useOverlay||!("useOverlay"in n))){let u=e.settings.nLines-n.position-1;a.clearRect(0,r.height*u/e.settings.nLines,r.width,r.height/e.settings.nLines),a.fillText(o,20,r.height*(u+.2)/e.settings.nLines),a.fillText(`${Math.floor(i)===i?i:i?.toFixed(5)} ${n.units?n.units:""}`,r.width-100,r.height*(u+.2)/e.settings.nLines),a.fillText(`${Math.floor(l)===l?l:l?.toFixed(5)} ${n.units?n.units:""}`,r.width-100,r.height*(u+.9)/e.settings.nLines)}}}else e.settings.generateNewLines&&!o.includes("timestamp")&&(Array.isArray(t[o])&&(t[o]={values:t[o]}),!t[o].nSec&&!t[o].nPoints&&!e.settings.linePoints&&(t[o].nPoints=1e3),h=true);if(h)return e.settings.cleanGeneration||Object.keys(e.initial.lines).forEach(o=>{t[o]?t[o]=Object.assign(e.initial.lines[o],t[o]):t[o]=e.initial.lines[o]}),this.reinitPlot(e,{_id:e.settings._id,lines:t}),true}return s&&requestAnimationFrame(e.anim),true}updateLine(e,t,s,h,r,a,o){return e.numPoints!==t.length&&(s?e.numPoints>t.length?t=y.downsample(t,e.numPoints):e.numPointse.numPoints?t=t.slice(t.length-e.numPoints):t=[...new Array(t.length).fill(0),...t]),h&&(t=y.autoscale(t,r,a,o)),t.forEach((n,l)=>e.setY(l,n)),true}static autoscale(e,t=0,s=1,h=false,r,a,o){if(e?.length===0)return e;let n=typeof a=="number"?a:e.length<=1e5?Math.max(...e):1,l=typeof r=="number"?r:e.length<=1e5?Math.min(...e):0,i=1/s,f=1;if(h){let u=Math.max(Math.abs(l),Math.abs(n));return u!==0&&(f=i/u),e.map(g=>(o&&(gn&&(g=n)),g*f+(i*(t+1)*2-1-i)))}else return n===l?n!==0?f=i/n:l!==0&&(f=i/Math.abs(l)):f=i/(n-l),e.map(u=>(o&&(un&&(u=n)),2*((u-l)*f-1/(2*s))+(i*(t+1)*2-1-i)))}static getYScalar(e,t=1,s=false,h,r){if(e?.length===0)return e;let a=typeof r=="number"?r:e.length<=1e5?Math.max(...e):1,o=typeof h=="number"?h:e.length<=1e5?Math.min(...e):0,n=1/t,l=1;if(s){let i=Math.max(Math.abs(o),Math.abs(a));return i!==0&&(l=n/i),2*l}else return a===o?a!==0?l=n/a:o!==0&&(l=n/Math.abs(o)):l=n/(a-o),2*l}static getYOffset(e=0,t=1,s=0,h=1){let r=1/t,a=r*(e+1)*2-1-r;return s>0&&(a-=s*h+1/t),a}static absmax(e){return Math.max(Math.abs(Math.min(...e)),Math.max(...e))}static downsample(e,t,s=1){if(e.length>t){let h=new Array(t),r=e.length/t,a=e.length-1,o=0,n=0;for(let l=r;la&&(i=a);for(let f=o;ft?y.downsample(e,t,s):e.lengthe.length){let s=e.length;e.splice(0,s,t.slice(s-t.length))}else e.splice(0,e.length,...t);return e}static formatDataForCharts(e,t){if(Array.isArray(e)){if(Array.isArray(e[0])){let s={};if(e.forEach((h,r)=>{s[r]=h}),e=s,isNaN(e[0][0]))return}else if(t){if(e={[t]:e},isNaN(e[t][0]))return}else if(e={0:e},isNaN(e[0][0]))return}else if(typeof e=="object"){for(let s in e)if(typeof e[s]=="number"?e[s]=[e[s]]:e[s]?.values&&typeof e[s].values=="number"&&(e[s].values=[e[s].values]),isNaN(e[s][0]))return}else if(typeof e=="string"){let s;if(e.includes(`\r +`)){let h=e.split(`\r +`);e={},h.forEach((r,a)=>{r.includes(" ")?s=r.split(" "):r.includes(",")?s=r.split(","):r.includes("|")&&(s=r.split("|")),s&&s.forEach((o,n)=>{if(o.includes(":")){let[l,i]=o.split(":"),f=parseFloat(i);isNaN(f)||(e[l]=[f])}else{let l=parseFloat(o);isNaN(l)||(e[n]=[l])}})})}else e.includes(" ")?s=e.split(" "):e.includes(",")?s=e.split(","):e.includes("|")&&(s=e.split("|"));e={},s&&s.forEach((h,r)=>{if(h.includes(":")){let[a,o]=h.split(":"),n=parseFloat(o);isNaN(n)||(e[a]=[n])}else{let a=parseFloat(h);isNaN(a)||(e[r]=[a])}})}else typeof e=="number"&&(t?e={[t]:[e]}:e={0:[e]});return e}static padTime(e,t,s,h){let r=(e[0]-t)/s/h;return[...new Array(h-e.length).map((o,n)=>t+r*(n+1)),...e]}static interpolateForTime(e,t,s){return y.interpolate(e,Math.ceil(s*t))}};var webglPlotRoutes={setupChart:function setupChart(settings){console.log("initializing chart",settings);if(!this?.__node?.graph?.plotter){this.__node.graph.plotter=new y;return this.__node.graph.plotter.initPlot(settings).settings._id}else{globalThis.plotter=new y;return globalThis.plotter.initPlot(settings).settings._id}},updateChartData:function updateChartData(plot,lines,draw=true){if(typeof lines==="object"){if(globalThis.plotter)globalThis.plotter.update(plot,lines,draw);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.update(plot,lines,draw);return true}return false},clearChart:function clearChart(plot){if(globalThis.plotter)globalThis.plotter.deinitPlot(plot);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.deinitPlot(plot);return true},resetChart:function resetChart(plot,settings){if(globalThis.plotter)globalThis.plotter.reinitPlot(plot,settings);else if(this?.__node?.graph?.plotter)this.__node.graph.plotter.reinitPlot(plot,settings);return settings._id},getChartSettings:function getChartSettings(plotId){let settings;if(globalThis.plotter)settings=globalThis.plotter.getChartSettings(plotId);else if(this?.__node?.graph?.plotter)settings=this.__node.graph.plotter.getChartSettings(plotId);return settings}};async function setSignalControls(controlsDiv,plotId,streamworker,chartworker,chartSettings,filterSettings){let controls=controlsDiv;if(!controls)return false;if(!chartSettings&&chartworker)chartSettings=await chartworker.run("getChartSettings",plotId);if(!filterSettings&&streamworker)filterSettings=await streamworker.run("getFilterSettings");if(chartSettings?.lines){let body=``;let viewingall=true;let scalingall=true;let n50all=true;let n60all=true;let dcall=true;let lpall=true;let bpall=true;for(const prop in chartSettings.lines){let line=chartSettings.lines[prop];body+=` +
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass
      ${prop}HzHz to Hz
      Name SPSPlot nSecScalar UnitsLower BoundUpper Bound50Hz Notch 60Hz Notch DC Block Lowpass Bandpass